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
1import asyncio2import json3import os4import threading5import time6import typing78import pytest9import trustme10from cryptography.hazmat.backends import default_backend11from cryptography.hazmat.primitives.serialization import (12 BestAvailableEncryption,13 Encoding,14 PrivateFormat,15 load_pem_private_key,16)17from uvicorn.config import Config18from uvicorn.main import Server1920from httpx import URL, AsyncioBackend2122ENVIRONMENT_VARIABLES = {23 "SSL_CERT_FILE",24 "SSL_CERT_DIR",25 "HTTP_PROXY",26 "HTTPS_PROXY",27 "ALL_PROXY",28 "NO_PROXY",29 "SSLKEYLOGFILE",30}313233@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()37 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 )45 yield46 os.environ.clear()47 os.environ.update(original_environ)484950@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])51def backend(request):52 backend_cls = request.param53 return backend_cls()545556async def app(scope, receive, send):57 assert scope["type"] == "http"58 if scope["path"].startswith("/slow_response"):59 await slow_response(scope, receive, send)60 elif scope["path"].startswith("/status"):61 await status_code(scope, receive, send)62 elif scope["path"].startswith("/echo_body"):63 await echo_body(scope, receive, send)64 elif scope["path"].startswith("/echo_headers"):65 await echo_headers(scope, receive, send)66 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):82 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)88 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!"})108109110async def echo_body(scope, receive, send):111 body = b""112 more_body = True113114 while more_body:115 message = await receive()116 body += message.get("body", b"")117 more_body = message.get("more_body", False)118119 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})127128129async 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()})142143144SERVER_SCOPE = "session"145146147@pytest.fixture(scope=SERVER_SCOPE)148def cert_authority():149 return trustme.CA()150151152@pytest.fixture(scope=SERVER_SCOPE)153def ca_cert_pem_file(cert_authority):154 with cert_authority.cert_pem.tempfile() as tmp:155 yield tmp156157158@pytest.fixture(scope=SERVER_SCOPE)159def localhost_cert(cert_authority):160 return cert_authority.issue_cert("localhost")161162163@pytest.fixture(scope=SERVER_SCOPE)164def cert_pem_file(localhost_cert):165 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:166 yield tmp167168169@pytest.fixture(scope=SERVER_SCOPE)170def cert_private_key_file(localhost_cert):171 with localhost_cert.private_key_pem.tempfile() as tmp:172 yield tmp173174175@pytest.fixture(scope=SERVER_SCOPE)176def 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:189 yield tmp190191192class TestServer(Server):193 @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}/")197198 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()237238239@pytest.fixture240def 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()256 try:257 while not server.started:258 time.sleep(1e-3)259 yield server260 finally:261 server.should_exit = True262 thread.join()263264265@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):274 config = Config(275 app=app,276 lifespan="off",277 ssl_certfile=cert_pem_file,278 ssl_keyfile=cert_private_key_file,279 host="localhost",280 port=8001,281 loop="asyncio",282 )283 server = TestServer(config=config)284 yield from serve_in_thread(server)