okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf88b738
main
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 ): 13def do_GET (self ): 14self .send_response (200 ) 15self .end_headers () 16self .wfile .write (b"ok" ) 17 18def log_message (self ,* a ): 19pass 20 21 22class LoopbackTests (unittest .TestCase ): 23def test_is_loopback (self ): 24for u in ("http://127.0.0.1:1/x" ,"http://localhost:2/" ,"http://[::1]:3/" ): 25self .assertTrue (loopback .is_loopback (u ),u ) 26for u in ("https://example.com/" ,"http://192.168.1.5:8080/" ,"not a url" ): 27self .assertFalse (loopback .is_loopback (u ),u ) 28 29def test_local_server_is_reached_with_a_dead_proxy_set (self ): 30srv = http .server .HTTPServer (("127.0.0.1" ,0 ),Hello ) 31threading .Thread (target = srv .serve_forever ,daemon = True ).start () 32try : 33env = {"HTTP_PROXY" :"http://127.0.0.1:9" ,"http_proxy" :"http://127.0.0.1:9" ,"NO_PROXY" :"" ,"no_proxy" :"" } 34with mock .patch .dict (os .environ ,env ): 35with loopback .urlopen (f"http://127.0.0.1: { srv . server_port } /" ,timeout = 5 )as r : 36self .assertEqual (r .read (),b"ok" ) 37finally : 38srv .shutdown () 39 40def test_other_addresses_still_use_urllib (self ): 41with mock .patch ("urllib.request.urlopen" ,return_value = "remote" )as m : 42self .assertEqual (loopback .urlopen ("https://example.com/" ,timeout = 3 ),"remote" ) 43m .assert_called_once () 44 45 46if __name__ == "__main__" : 47unittest .main ()