okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-refusals: environmental refusals repair or warn instead of blocking (audit items 1-4, 6, 8-10, 12-15)bcf88b738

main
1.7 KiB47 linesraw
1"""Calls to this computer's own servers must ignore the system proxy (a company proxy cannot reach 127.0.0.1)."""
2
3import http.server
4import os
5import threading
6import unittest
7from unittest import mock
8
9from strata_control import loopback
10
11
12class Hello(http.server.BaseHTTPRequestHandler):
13    def do_GET(self):
14        self.send_response(200)
15        self.end_headers()
16        self.wfile.write(b"ok")
17
18    def log_message(self, *a):
19        pass
20
21
22class LoopbackTests(unittest.TestCase):
23    def test_is_loopback(self):
24        for u in ("http://127.0.0.1:1/x", "http://localhost:2/", "http://[::1]:3/"):
25            self.assertTrue(loopback.is_loopback(u), u)
26        for u in ("https://example.com/", "http://192.168.1.5:8080/", "not a url"):
27            self.assertFalse(loopback.is_loopback(u), u)
28
29    def test_local_server_is_reached_with_a_dead_proxy_set(self):
30        srv = http.server.HTTPServer(("127.0.0.1", 0), Hello)
31        threading.Thread(target=srv.serve_forever, daemon=True).start()
32        try:
33            env = {"HTTP_PROXY": "http://127.0.0.1:9", "http_proxy": "http://127.0.0.1:9", "NO_PROXY": "", "no_proxy": ""}
34            with mock.patch.dict(os.environ, env):
35                with loopback.urlopen(f"http://127.0.0.1:{srv.server_port}/", timeout=5) as r:
36                    self.assertEqual(r.read(), b"ok")
37        finally:
38            srv.shutdown()
39
40    def test_other_addresses_still_use_urllib(self):
41        with mock.patch("urllib.request.urlopen", return_value="remote") as m:
42            self.assertEqual(loopback.urlopen("https://example.com/", timeout=3), "remote")
43            m.assert_called_once()
44
45
46if __name__ == "__main__":
47    unittest.main()