conftest.py
This file
Path
tests/conftest.py
337 lines · 9.2 KiB · Python
Last changed by
Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
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 URL21from httpx.concurrency.asyncio import AsyncioBackend22from httpx.concurrency.trio import TrioBackend2324ENVIRONMENT_VARIABLES = {25 "SSL_CERT_FILE",26 "SSL_CERT_DIR",27 "HTTP_PROXY",28 "HTTPS_PROXY",29 "ALL_PROXY",30 "NO_PROXY",31 "SSLKEYLOGFILE",32}333435@pytest.fixture(scope="function", autouse=True)36def clean_environ() -> typing.Dict[str, typing.Any]:37 """Keeps os.environ clean for every test without having to mock os.environ"""38 original_environ = os.environ.copy()39 os.environ.clear()40 os.environ.update(41 {42 k: v43 for k, v in original_environ.items()44 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES45 }46 )47 yield48 os.environ.clear()49 os.environ.update(original_environ)505152@pytest.fixture(53 params=[54 pytest.param(AsyncioBackend, marks=pytest.mark.asyncio),55 pytest.param(TrioBackend, marks=pytest.mark.trio),56 ]57)58def backend(request):59 backend_cls = request.param60 return backend_cls()616263async def app(scope, receive, send):64 assert scope["type"] == "http"65 if scope["path"].startswith("/slow_response"):66 await slow_response(scope, receive, send)67 elif scope["path"].startswith("/premature_close"):68 await premature_close(scope, receive, send)69 elif scope["path"].startswith("/status"):70 await status_code(scope, receive, send)71 elif scope["path"].startswith("/echo_body"):72 await echo_body(scope, receive, send)73 elif scope["path"].startswith("/echo_headers"):74 await echo_headers(scope, receive, send)75 elif scope["path"].startswith("/redirect_301"):76 await redirect_301(scope, receive, send)77 else:78 await hello_world(scope, receive, send)798081async def hello_world(scope, receive, send):82 await send(83 {84 "type": "http.response.start",85 "status": 200,86 "headers": [[b"content-type", b"text/plain"]],87 }88 )89 await send({"type": "http.response.body", "body": b"Hello, world!"})909192async def slow_response(scope, receive, send):93 delay_ms_str: str = scope["path"].replace("/slow_response/", "")94 try:95 delay_ms = float(delay_ms_str)96 except ValueError:97 delay_ms = 10098 await asyncio.sleep(delay_ms / 1000.0)99 await send(100 {101 "type": "http.response.start",102 "status": 200,103 "headers": [[b"content-type", b"text/plain"]],104 }105 )106 await send({"type": "http.response.body", "body": b"Hello, world!"})107108109async def premature_close(scope, receive, send):110 await send(111 {112 "type": "http.response.start",113 "status": 200,114 "headers": [[b"content-type", b"text/plain"]],115 }116 )117118119async def status_code(scope, receive, send):120 status_code = int(scope["path"].replace("/status/", ""))121 await send(122 {123 "type": "http.response.start",124 "status": status_code,125 "headers": [[b"content-type", b"text/plain"]],126 }127 )128 await send({"type": "http.response.body", "body": b"Hello, world!"})129130131async def echo_body(scope, receive, send):132 body = b""133 more_body = True134135 while more_body:136 message = await receive()137 body += message.get("body", b"")138 more_body = message.get("more_body", False)139140 await send(141 {142 "type": "http.response.start",143 "status": 200,144 "headers": [[b"content-type", b"text/plain"]],145 }146 )147 await send({"type": "http.response.body", "body": body})148149150async def echo_headers(scope, receive, send):151 body = {}152 for name, value in scope.get("headers", []):153 body[name.capitalize().decode()] = value.decode()154155 await send(156 {157 "type": "http.response.start",158 "status": 200,159 "headers": [[b"content-type", b"application/json"]],160 }161 )162 await send({"type": "http.response.body", "body": json.dumps(body).encode()})163164165async def redirect_301(scope, receive, send):166 await send(167 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}168 )169 await send({"type": "http.response.body"})170171172SERVER_SCOPE = "session"173174175@pytest.fixture(scope=SERVER_SCOPE)176def cert_authority():177 return trustme.CA()178179180@pytest.fixture(scope=SERVER_SCOPE)181def ca_cert_pem_file(cert_authority):182 with cert_authority.cert_pem.tempfile() as tmp:183 yield tmp184185186@pytest.fixture(scope=SERVER_SCOPE)187def localhost_cert(cert_authority):188 return cert_authority.issue_cert("localhost")189190191@pytest.fixture(scope=SERVER_SCOPE)192def cert_pem_file(localhost_cert):193 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:194 yield tmp195196197@pytest.fixture(scope=SERVER_SCOPE)198def cert_private_key_file(localhost_cert):199 with localhost_cert.private_key_pem.tempfile() as tmp:200 yield tmp201202203@pytest.fixture(scope=SERVER_SCOPE)204def cert_encrypted_private_key_file(localhost_cert):205 # Deserialize the private key and then reserialize with a password206 private_key = load_pem_private_key(207 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()208 )209 encrypted_private_key_pem = trustme.Blob(210 private_key.private_bytes(211 Encoding.PEM,212 PrivateFormat.TraditionalOpenSSL,213 BestAvailableEncryption(password=b"password"),214 )215 )216 with encrypted_private_key_pem.tempfile() as tmp:217 yield tmp218219220class TestServer(Server):221 @property222 def url(self) -> URL:223 protocol = "https" if self.config.is_ssl else "http"224 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")225226 def install_signal_handlers(self) -> None:227 # Disable the default installation of handlers for signals such as SIGTERM,228 # because it can only be done in the main thread.229 pass230231 async def serve(self, sockets=None):232 self.restart_requested = asyncio.Event()233234 loop = asyncio.get_event_loop()235 tasks = {236 loop.create_task(super().serve(sockets=sockets)),237 loop.create_task(self.watch_restarts()),238 }239 await asyncio.wait(tasks)240241 async def restart(self) -> None:242 # Ensure we are in an asyncio environment.243 assert asyncio.get_event_loop() is not None244 # This may be called from a different thread than the one the server is245 # running on. For this reason, we use an event to coordinate with the server246 # instead of calling shutdown()/startup() directly.247 self.restart_requested.set()248 self.started = False249 while not self.started:250 await asyncio.sleep(0.5)251252 async def watch_restarts(self):253 while True:254 if self.should_exit:255 return256257 try:258 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)259 except asyncio.TimeoutError:260 continue261262 self.restart_requested.clear()263 await self.shutdown()264 await self.startup()265266267@pytest.fixture268def restart(backend):269 """Restart the running server from an async test function.270271 This fixture deals with possible differences between the environment of the272 test function and that of the server.273 """274275 async def restart(server):276 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)277278 return restart279280281def serve_in_thread(server: Server):282 thread = threading.Thread(target=server.run)283 thread.start()284 try:285 while not server.started:286 time.sleep(1e-3)287 yield server288 finally:289 server.should_exit = True290 thread.join()291292293@pytest.fixture(scope=SERVER_SCOPE)294def server():295 config = Config(app=app, lifespan="off", loop="asyncio")296 server = TestServer(config=config)297 yield from serve_in_thread(server)298299300@pytest.fixture(scope=SERVER_SCOPE)301def uds_server():302 uds = "test_server.sock"303 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)304 server = TestServer(config=config)305 yield from serve_in_thread(server)306 os.remove(uds)307308309@pytest.fixture(scope=SERVER_SCOPE)310def https_server(cert_pem_file, cert_private_key_file):311 config = Config(312 app=app,313 lifespan="off",314 ssl_certfile=cert_pem_file,315 ssl_keyfile=cert_private_key_file,316 host="localhost",317 port=8001,318 loop="asyncio",319 )320 server = TestServer(config=config)321 yield from serve_in_thread(server)322323324@pytest.fixture(scope=SERVER_SCOPE)325def https_uds_server(cert_pem_file, cert_private_key_file):326 uds = "https_test_server.sock"327 config = Config(328 app=app,329 lifespan="off",330 ssl_certfile=cert_pem_file,331 ssl_keyfile=cert_private_key_file,332 uds=uds,333 loop="asyncio",334 )335 server = TestServer(config=config)336 yield from serve_in_thread(server)337 os.remove(uds)