conftest.py
This file
Path
tests/conftest.py
284 lines · 7.8 KiB · Python
Last changed by
Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
History of this fileTake it
The walk stopped after 200 commits: lines older than f1b10e5 point at it.
Minor docstring tweakTom Christiebefore adoptionf1b10e5
line 1why, one step back1import asyncioAdd `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
line 2why, one step back2import jsonAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 3why, one step back3import osServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 4–5why, one step back4import threading5import timeAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 6why, one step back6import typingMinor docstring tweakTom Christiebefore adoptionf1b10e5
lines 7–8why, one step back78import pytestMerge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
line 9why, one step back9import trustmeUse a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 10why, one step back10from cryptography.hazmat.backends import default_backendSupport client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 11–14why, one step back11from cryptography.hazmat.primitives.serialization import (12 BestAvailableEncryption,13 Encoding,14 PrivateFormat,Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
line 15why, one step back15 load_pem_private_key,Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 16why, one step back16)Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 17–19why, one step back17from uvicorn.config import Config18from uvicorn.main import Server19Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
line 20why, one step back20from httpx import URL, AsyncioBackendAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 21why, one step back21Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 22why, one step back22ENVIRONMENT_VARIABLES = {Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 23why, one step back23 "SSL_CERT_FILE",Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 24why, one step back24 "SSL_CERT_DIR",Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 25–29why, one step back25 "HTTP_PROXY",26 "HTTPS_PROXY",27 "ALL_PROXY",28 "NO_PROXY",29 "SSLKEYLOGFILE",Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 30why, one step back30}Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 31–36why, one step back313233@pytest.fixture(scope="function", autouse=True)34def clean_environ() -> typing.Dict[str, typing.Any]:35 """Keeps os.environ clean for every test without having to mock os.environ"""36 original_environ = os.environ.copy()Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 37–44why, one step back37 os.environ.clear()38 os.environ.update(39 {40 k: v41 for k, v in original_environ.items()42 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES43 }44 )Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 45–47why, one step back45 yield46 os.environ.clear()47 os.environ.update(original_environ)Minor docstring tweakTom Christiebefore adoptionf1b10e5
line 48why, one step back48Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 49–55why, one step back4950@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])51def backend(request):52 backend_cls = request.param53 return backend_cls()5455Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 56–57why, one step back56async def app(scope, receive, send):57 assert scope["type"] == "http"Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117
line 58why, one step back58 if scope["path"].startswith("/slow_response"):Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 59–61why, one step back59 await slow_response(scope, receive, send)60 elif scope["path"].startswith("/status"):61 await status_code(scope, receive, send)Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 62–63why, one step back62 elif scope["path"].startswith("/echo_body"):63 await echo_body(scope, receive, send)Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 64–65why, one step back64 elif scope["path"].startswith("/echo_headers"):65 await echo_headers(scope, receive, send)Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 66–81why, one step back66 else:67 await hello_world(scope, receive, send)686970async def hello_world(scope, receive, send):71 await send(72 {73 "type": "http.response.start",74 "status": 200,75 "headers": [[b"content-type", b"text/plain"]],76 }77 )78 await send({"type": "http.response.body", "body": b"Hello, world!"})798081async def slow_response(scope, receive, send):Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117
lines 82–87why, one step back82 delay_ms_str: str = scope["path"].replace("/slow_response/", "")83 try:84 delay_ms = float(delay_ms_str)85 except ValueError:86 delay_ms = 10087 await asyncio.sleep(delay_ms / 1000.0)Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 88–107why, one step back88 await send(89 {90 "type": "http.response.start",91 "status": 200,92 "headers": [[b"content-type", b"text/plain"]],93 }94 )95 await send({"type": "http.response.body", "body": b"Hello, world!"})969798async def status_code(scope, receive, send):99 status_code = int(scope["path"].replace("/status/", ""))100 await send(101 {102 "type": "http.response.start",103 "status": status_code,104 "headers": [[b"content-type", b"text/plain"]],105 }106 )107 await send({"type": "http.response.body", "body": b"Hello, world!"})Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 108–110why, one step back108109110async def echo_body(scope, receive, send):Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 111why, one step back111 body = b""Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 112–115why, one step back112 more_body = True113114 while more_body:115 message = await receive()Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
lines 116–117why, one step back116 body += message.get("body", b"")117 more_body = message.get("more_body", False)Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 118–126why, one step back118119 await send(120 {121 "type": "http.response.start",122 "status": 200,123 "headers": [[b"content-type", b"text/plain"]],124 }125 )126 await send({"type": "http.response.body", "body": body})Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 127–141why, one step back127128129async def echo_headers(scope, receive, send):130 body = {}131 for name, value in scope.get("headers", []):132 body[name.capitalize().decode()] = value.decode()133134 await send(135 {136 "type": "http.response.start",137 "status": 200,138 "headers": [[b"content-type", b"application/json"]],139 }140 )141 await send({"type": "http.response.body", "body": json.dumps(body).encode()})Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 142–143why, one step back142143Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 144why, one step back144SERVER_SCOPE = "session"Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 145–146why, one step back145146Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 147–149why, one step back147@pytest.fixture(scope=SERVER_SCOPE)148def cert_authority():149 return trustme.CA()Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 150why, one step back150Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 151why, one step back151Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 152–155why, one step back152@pytest.fixture(scope=SERVER_SCOPE)153def ca_cert_pem_file(cert_authority):154 with cert_authority.cert_pem.tempfile() as tmp:155 yield tmpServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 156why, one step back156Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 157why, one step back157Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 158why, one step back158@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 159–160why, one step back159def localhost_cert(cert_authority):160 return cert_authority.issue_cert("localhost")Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
lines 161–162why, one step back161162Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 163why, one step back163@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 164–165why, one step back164def cert_pem_file(localhost_cert):165 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 166–168why, one step back166 yield tmp167168Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 169why, one step back169@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 170–171why, one step back170def cert_private_key_file(localhost_cert):171 with localhost_cert.private_key_pem.tempfile() as tmp:Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 172–174why, one step back172 yield tmp173174Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 175why, one step back175@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 176–188why, one step back176def cert_encrypted_private_key_file(localhost_cert):177 # Deserialize the private key and then reserialize with a password178 private_key = load_pem_private_key(179 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()180 )181 encrypted_private_key_pem = trustme.Blob(182 private_key.private_bytes(183 Encoding.PEM,184 PrivateFormat.TraditionalOpenSSL,185 BestAvailableEncryption(password=b"password"),186 )187 )188 with encrypted_private_key_pem.tempfile() as tmp:Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 189–191why, one step back189 yield tmp190191Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 192why, one step back192class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 193–197why, one step back193 @property194 def url(self) -> URL:195 protocol = "https" if self.config.is_ssl else "http"196 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")197Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 198–238why, one step back198 def install_signal_handlers(self) -> None:199 # Disable the default installation of handlers for signals such as SIGTERM,200 # because it can only be done in the main thread.201 pass202203 async def serve(self, sockets=None):204 self.restart_requested = asyncio.Event()205206 loop = asyncio.get_event_loop()207 tasks = {208 loop.create_task(super().serve(sockets=sockets)),209 loop.create_task(self.watch_restarts()),210 }211 await asyncio.wait(tasks)212213 async def restart(self) -> None:214 # Ensure we are in an asyncio environment.215 assert asyncio.get_event_loop() is not None216 # This may be called from a different thread than the one the server is217 # running on. For this reason, we use an event to coordinate with the server218 # instead of calling shutdown()/startup() directly.219 self.restart_requested.set()220 self.started = False221 while not self.started:222 await asyncio.sleep(0.5)223224 async def watch_restarts(self):225 while True:226 if self.should_exit:227 return228229 try:230 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)231 except asyncio.TimeoutError:232 continue233234 self.restart_requested.clear()235 await self.shutdown()236 await self.startup()237238Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 239why, one step back239@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 240–255why, one step back240def restart(backend):241 """Restart the running server from an async test function.242243 This fixture deals with possible differences between the environment of the244 test function and that of the server.245 """246247 async def restart(server):248 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)249250 return restart251252253def serve_in_thread(server: Server):254 thread = threading.Thread(target=server.run)255 thread.start()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 256–257why, one step back256 try:257 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 258why, one step back258 time.sleep(1e-3)Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 259–261why, one step back259 yield server260 finally:261 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 262why, one step back262 thread.join()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 263–264why, one step back263264Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 265–273why, one step back265@pytest.fixture(scope=SERVER_SCOPE)266def server():267 config = Config(app=app, lifespan="off", loop="asyncio")268 server = TestServer(config=config)269 yield from serve_in_thread(server)270271272@pytest.fixture(scope=SERVER_SCOPE)273def https_server(cert_pem_file, cert_private_key_file):Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 274why, one step back274 config = Config(Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 275–278why, one step back275 app=app,276 lifespan="off",277 ssl_certfile=cert_pem_file,278 ssl_keyfile=cert_private_key_file,Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 279why, one step back279 host="localhost",Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 280why, one step back280 port=8001,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 281why, one step back281 loop="asyncio",Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 282why, one step back282 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 283–284why, one step back283 server = TestServer(config=config)284 yield from serve_in_thread(server)