conftest.py
This file
Path
tests/conftest.py
272 lines · 7.3 KiB · Python
Last changed by
Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
History of this fileTake it
1import asyncio2import json3import os4import threading5import time6import typing78import pytest9import trustme10from cryptography.hazmat.primitives.serialization import (11 BestAvailableEncryption,12 Encoding,13 PrivateFormat,14)15from uvicorn.config import Config16from uvicorn.main import Server1718from httpx import URL, AsyncioBackend1920ENVIRONMENT_VARIABLES = {21 "SSL_CERT_FILE",22 "SSL_CERT_DIR",23 "HTTP_PROXY",24 "HTTPS_PROXY",25 "ALL_PROXY",26 "NO_PROXY",27 "SSLKEYLOGFILE",28}293031@pytest.fixture(scope="function", autouse=True)32def clean_environ() -> typing.Dict[str, typing.Any]:33 """Keeps os.environ clean for every test without having to mock os.environ"""34 original_environ = os.environ.copy()35 os.environ.clear()36 os.environ.update(37 {38 k: v39 for k, v in original_environ.items()40 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES41 }42 )43 yield44 os.environ.clear()45 os.environ.update(original_environ)464748@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])49def backend(request):50 backend_cls = request.param51 return backend_cls()525354async def app(scope, receive, send):55 assert scope["type"] == "http"56 if scope["path"] == "/slow_response":57 await slow_response(scope, receive, send)58 elif scope["path"].startswith("/status"):59 await status_code(scope, receive, send)60 elif scope["path"].startswith("/echo_body"):61 await echo_body(scope, receive, send)62 elif scope["path"].startswith("/echo_headers"):63 await echo_headers(scope, receive, send)64 else:65 await hello_world(scope, receive, send)666768async def hello_world(scope, receive, send):69 await send(70 {71 "type": "http.response.start",72 "status": 200,73 "headers": [[b"content-type", b"text/plain"]],74 }75 )76 await send({"type": "http.response.body", "body": b"Hello, world!"})777879async def slow_response(scope, receive, send):80 await asyncio.sleep(0.1)81 await send(82 {83 "type": "http.response.start",84 "status": 200,85 "headers": [[b"content-type", b"text/plain"]],86 }87 )88 await send({"type": "http.response.body", "body": b"Hello, world!"})899091async def status_code(scope, receive, send):92 status_code = int(scope["path"].replace("/status/", ""))93 await send(94 {95 "type": "http.response.start",96 "status": status_code,97 "headers": [[b"content-type", b"text/plain"]],98 }99 )100 await send({"type": "http.response.body", "body": b"Hello, world!"})101102103async def echo_body(scope, receive, send):104 body = b""105 more_body = True106107 while more_body:108 message = await receive()109 body += message.get("body", b"")110 more_body = message.get("more_body", False)111112 await send(113 {114 "type": "http.response.start",115 "status": 200,116 "headers": [[b"content-type", b"text/plain"]],117 }118 )119 await send({"type": "http.response.body", "body": body})120121122async def echo_headers(scope, receive, send):123 body = {}124 for name, value in scope.get("headers", []):125 body[name.capitalize().decode()] = value.decode()126127 await send(128 {129 "type": "http.response.start",130 "status": 200,131 "headers": [[b"content-type", b"application/json"]],132 }133 )134 await send({"type": "http.response.body", "body": json.dumps(body).encode()})135136137class CAWithPKEncryption(trustme.CA):138 """Implementation of trustme.CA() that can emit139 private keys that are encrypted with a password.140 """141142 @property143 def encrypted_private_key_pem(self):144 return trustme.Blob(145 self._private_key.private_bytes(146 Encoding.PEM,147 PrivateFormat.TraditionalOpenSSL,148 BestAvailableEncryption(password=b"password"),149 )150 )151152153SERVER_SCOPE = "session"154155156@pytest.fixture(scope=SERVER_SCOPE)157def example_cert():158 ca = CAWithPKEncryption()159 ca.issue_cert("example.org")160 return ca161162163@pytest.fixture(scope=SERVER_SCOPE)164def cert_pem_file(example_cert):165 with example_cert.cert_pem.tempfile() as tmp:166 yield tmp167168169@pytest.fixture(scope=SERVER_SCOPE)170def cert_private_key_file(example_cert):171 with example_cert.private_key_pem.tempfile() as tmp:172 yield tmp173174175@pytest.fixture(scope=SERVER_SCOPE)176def cert_encrypted_private_key_file(example_cert):177 with example_cert.encrypted_private_key_pem.tempfile() as tmp:178 yield tmp179180181class TestServer(Server):182 @property183 def url(self) -> URL:184 protocol = "https" if self.config.is_ssl else "http"185 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")186187 def install_signal_handlers(self) -> None:188 # Disable the default installation of handlers for signals such as SIGTERM,189 # because it can only be done in the main thread.190 pass191192 async def serve(self, sockets=None):193 self.restart_requested = asyncio.Event()194195 loop = asyncio.get_event_loop()196 tasks = {197 loop.create_task(super().serve(sockets=sockets)),198 loop.create_task(self.watch_restarts()),199 }200 await asyncio.wait(tasks)201202 async def restart(self) -> None:203 # Ensure we are in an asyncio environment.204 assert asyncio.get_event_loop() is not None205 # This may be called from a different thread than the one the server is206 # running on. For this reason, we use an event to coordinate with the server207 # instead of calling shutdown()/startup() directly.208 self.restart_requested.set()209 self.started = False210 while not self.started:211 await asyncio.sleep(0.5)212213 async def watch_restarts(self):214 while True:215 if self.should_exit:216 return217218 try:219 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)220 except asyncio.TimeoutError:221 continue222223 self.restart_requested.clear()224 await self.shutdown()225 await self.startup()226227228@pytest.fixture229def restart(backend):230 """Restart the running server from an async test function.231232 This fixture deals with possible differences between the environment of the233 test function and that of the server.234 """235236 async def restart(server):237 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)238239 return restart240241242def serve_in_thread(server: Server):243 thread = threading.Thread(target=server.run)244 thread.start()245 try:246 while not server.started:247 time.sleep(1e-3)248 yield server249 finally:250 server.should_exit = True251 thread.join()252253254@pytest.fixture(scope=SERVER_SCOPE)255def server():256 config = Config(app=app, lifespan="off", loop="asyncio")257 server = TestServer(config=config)258 yield from serve_in_thread(server)259260261@pytest.fixture(scope=SERVER_SCOPE)262def https_server(cert_pem_file, cert_private_key_file):263 config = Config(264 app=app,265 lifespan="off",266 ssl_certfile=cert_pem_file,267 ssl_keyfile=cert_private_key_file,268 port=8001,269 loop="asyncio",270 )271 server = TestServer(config=config)272 yield from serve_in_thread(server)