conftest.py
This file
Path
tests/conftest.py
352 lines · 9.6 KiB · Python
Last changed by
Clean up 'backend' fixture (#664)Florimond Mancabefore adoptiond0427be
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.backends.asyncio import AsyncioBackend22from httpx.backends.base import lookup_backend2324ENVIRONMENT_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(36 params=[37 pytest.param("asyncio", marks=pytest.mark.asyncio),38 pytest.param("trio", marks=pytest.mark.trio),39 ]40)41def async_environment(request: typing.Any) -> str:42 """43 Mark a test function to be run on both asyncio and trio.4445 Equivalent to having a pair of tests, each respectively marked with46 '@pytest.mark.asyncio' and '@pytest.mark.trio'.4748 Intended usage:4950 ```51 @pytest.mark.usefixtures("async_environment")52 async def my_async_test():53 ...54 ```55 """56 return request.param575859@pytest.fixture(scope="function", autouse=True)60def clean_environ() -> typing.Dict[str, typing.Any]:61 """Keeps os.environ clean for every test without having to mock os.environ"""62 original_environ = os.environ.copy()63 os.environ.clear()64 os.environ.update(65 {66 k: v67 for k, v in original_environ.items()68 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES69 }70 )71 yield72 os.environ.clear()73 os.environ.update(original_environ)747576async def app(scope, receive, send):77 assert scope["type"] == "http"78 if scope["path"].startswith("/slow_response"):79 await slow_response(scope, receive, send)80 elif scope["path"].startswith("/premature_close"):81 await premature_close(scope, receive, send)82 elif scope["path"].startswith("/status"):83 await status_code(scope, receive, send)84 elif scope["path"].startswith("/echo_body"):85 await echo_body(scope, receive, send)86 elif scope["path"].startswith("/echo_headers"):87 await echo_headers(scope, receive, send)88 elif scope["path"].startswith("/redirect_301"):89 await redirect_301(scope, receive, send)90 else:91 await hello_world(scope, receive, send)929394async def hello_world(scope, receive, send):95 await send(96 {97 "type": "http.response.start",98 "status": 200,99 "headers": [[b"content-type", b"text/plain"]],100 }101 )102 await send({"type": "http.response.body", "body": b"Hello, world!"})103104105async def slow_response(scope, receive, send):106 delay_ms_str: str = scope["path"].replace("/slow_response/", "")107 try:108 delay_ms = float(delay_ms_str)109 except ValueError:110 delay_ms = 100111 await asyncio.sleep(delay_ms / 1000.0)112 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": b"Hello, world!"})120121122async def premature_close(scope, receive, send):123 await send(124 {125 "type": "http.response.start",126 "status": 200,127 "headers": [[b"content-type", b"text/plain"]],128 }129 )130131132async def status_code(scope, receive, send):133 status_code = int(scope["path"].replace("/status/", ""))134 await send(135 {136 "type": "http.response.start",137 "status": status_code,138 "headers": [[b"content-type", b"text/plain"]],139 }140 )141 await send({"type": "http.response.body", "body": b"Hello, world!"})142143144async def echo_body(scope, receive, send):145 body = b""146 more_body = True147148 while more_body:149 message = await receive()150 body += message.get("body", b"")151 more_body = message.get("more_body", False)152153 await send(154 {155 "type": "http.response.start",156 "status": 200,157 "headers": [[b"content-type", b"text/plain"]],158 }159 )160 await send({"type": "http.response.body", "body": body})161162163async def echo_headers(scope, receive, send):164 body = {}165 for name, value in scope.get("headers", []):166 body[name.capitalize().decode()] = value.decode()167168 await send(169 {170 "type": "http.response.start",171 "status": 200,172 "headers": [[b"content-type", b"application/json"]],173 }174 )175 await send({"type": "http.response.body", "body": json.dumps(body).encode()})176177178async def redirect_301(scope, receive, send):179 await send(180 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}181 )182 await send({"type": "http.response.body"})183184185SERVER_SCOPE = "session"186187188@pytest.fixture(scope=SERVER_SCOPE)189def cert_authority():190 return trustme.CA()191192193@pytest.fixture(scope=SERVER_SCOPE)194def ca_cert_pem_file(cert_authority):195 with cert_authority.cert_pem.tempfile() as tmp:196 yield tmp197198199@pytest.fixture(scope=SERVER_SCOPE)200def localhost_cert(cert_authority):201 return cert_authority.issue_cert("localhost")202203204@pytest.fixture(scope=SERVER_SCOPE)205def cert_pem_file(localhost_cert):206 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:207 yield tmp208209210@pytest.fixture(scope=SERVER_SCOPE)211def cert_private_key_file(localhost_cert):212 with localhost_cert.private_key_pem.tempfile() as tmp:213 yield tmp214215216@pytest.fixture(scope=SERVER_SCOPE)217def cert_encrypted_private_key_file(localhost_cert):218 # Deserialize the private key and then reserialize with a password219 private_key = load_pem_private_key(220 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()221 )222 encrypted_private_key_pem = trustme.Blob(223 private_key.private_bytes(224 Encoding.PEM,225 PrivateFormat.TraditionalOpenSSL,226 BestAvailableEncryption(password=b"password"),227 )228 )229 with encrypted_private_key_pem.tempfile() as tmp:230 yield tmp231232233class TestServer(Server):234 @property235 def url(self) -> URL:236 protocol = "https" if self.config.is_ssl else "http"237 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")238239 def install_signal_handlers(self) -> None:240 # Disable the default installation of handlers for signals such as SIGTERM,241 # because it can only be done in the main thread.242 pass243244 async def serve(self, sockets=None):245 self.restart_requested = asyncio.Event()246247 loop = asyncio.get_event_loop()248 tasks = {249 loop.create_task(super().serve(sockets=sockets)),250 loop.create_task(self.watch_restarts()),251 }252 await asyncio.wait(tasks)253254 async def restart(self) -> None:255 # Ensure we are in an asyncio environment.256 assert asyncio.get_event_loop() is not None257 # This may be called from a different thread than the one the server is258 # running on. For this reason, we use an event to coordinate with the server259 # instead of calling shutdown()/startup() directly.260 self.restart_requested.set()261 self.started = False262 while not self.started:263 await asyncio.sleep(0.5)264265 async def watch_restarts(self):266 while True:267 if self.should_exit:268 return269270 try:271 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)272 except asyncio.TimeoutError:273 continue274275 self.restart_requested.clear()276 await self.shutdown()277 await self.startup()278279280@pytest.fixture281def restart():282 """Restart the running server from an async test function.283284 This fixture deals with possible differences between the environment of the285 test function and that of the server.286 """287 asyncio_backend = AsyncioBackend()288289 async def restart(server):290 backend = lookup_backend()291 await backend.run_in_threadpool(asyncio_backend.run, server.restart)292293 return restart294295296def serve_in_thread(server: Server):297 thread = threading.Thread(target=server.run)298 thread.start()299 try:300 while not server.started:301 time.sleep(1e-3)302 yield server303 finally:304 server.should_exit = True305 thread.join()306307308@pytest.fixture(scope=SERVER_SCOPE)309def server():310 config = Config(app=app, lifespan="off", loop="asyncio")311 server = TestServer(config=config)312 yield from serve_in_thread(server)313314315@pytest.fixture(scope=SERVER_SCOPE)316def uds_server():317 uds = "test_server.sock"318 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)319 server = TestServer(config=config)320 yield from serve_in_thread(server)321 os.remove(uds)322323324@pytest.fixture(scope=SERVER_SCOPE)325def https_server(cert_pem_file, cert_private_key_file):326 config = Config(327 app=app,328 lifespan="off",329 ssl_certfile=cert_pem_file,330 ssl_keyfile=cert_private_key_file,331 host="localhost",332 port=8001,333 loop="asyncio",334 )335 server = TestServer(config=config)336 yield from serve_in_thread(server)337338339@pytest.fixture(scope=SERVER_SCOPE)340def https_uds_server(cert_pem_file, cert_private_key_file):341 uds = "https_test_server.sock"342 config = Config(343 app=app,344 lifespan="off",345 ssl_certfile=cert_pem_file,346 ssl_keyfile=cert_private_key_file,347 uds=uds,348 loop="asyncio",349 )350 server = TestServer(config=config)351 yield from serve_in_thread(server)352 os.remove(uds)