conftest.py
This file
Path
tests/conftest.py
345 lines · 9.6 KiB · Python
Last changed by
Rename `concurrency` directory to `backends` (#662)Andrés Álvarezbefore adoptione34df7a
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(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 uses the marks to set up the specified async environment and run55 # 'async def' test functions. The "auto" backend should then auto-detect56 # the environment it's running in.57 # Passing the backend explicitly, e.g. `backend="asyncio"`,58 # is tested separately.59 pytest.param("auto", marks=pytest.mark.asyncio),60 pytest.param("auto", marks=pytest.mark.trio),61 ]62)63def backend(request):64 return request.param656667async def app(scope, receive, send):68 assert scope["type"] == "http"69 if scope["path"].startswith("/slow_response"):70 await slow_response(scope, receive, send)71 elif scope["path"].startswith("/premature_close"):72 await premature_close(scope, receive, send)73 elif scope["path"].startswith("/status"):74 await status_code(scope, receive, send)75 elif scope["path"].startswith("/echo_body"):76 await echo_body(scope, receive, send)77 elif scope["path"].startswith("/echo_headers"):78 await echo_headers(scope, receive, send)79 elif scope["path"].startswith("/redirect_301"):80 await redirect_301(scope, receive, send)81 else:82 await hello_world(scope, receive, send)838485async def hello_world(scope, receive, send):86 await send(87 {88 "type": "http.response.start",89 "status": 200,90 "headers": [[b"content-type", b"text/plain"]],91 }92 )93 await send({"type": "http.response.body", "body": b"Hello, world!"})949596async def slow_response(scope, receive, send):97 delay_ms_str: str = scope["path"].replace("/slow_response/", "")98 try:99 delay_ms = float(delay_ms_str)100 except ValueError:101 delay_ms = 100102 await asyncio.sleep(delay_ms / 1000.0)103 await send(104 {105 "type": "http.response.start",106 "status": 200,107 "headers": [[b"content-type", b"text/plain"]],108 }109 )110 await send({"type": "http.response.body", "body": b"Hello, world!"})111112113async def premature_close(scope, receive, send):114 await send(115 {116 "type": "http.response.start",117 "status": 200,118 "headers": [[b"content-type", b"text/plain"]],119 }120 )121122123async def status_code(scope, receive, send):124 status_code = int(scope["path"].replace("/status/", ""))125 await send(126 {127 "type": "http.response.start",128 "status": status_code,129 "headers": [[b"content-type", b"text/plain"]],130 }131 )132 await send({"type": "http.response.body", "body": b"Hello, world!"})133134135async def echo_body(scope, receive, send):136 body = b""137 more_body = True138139 while more_body:140 message = await receive()141 body += message.get("body", b"")142 more_body = message.get("more_body", False)143144 await send(145 {146 "type": "http.response.start",147 "status": 200,148 "headers": [[b"content-type", b"text/plain"]],149 }150 )151 await send({"type": "http.response.body", "body": body})152153154async def echo_headers(scope, receive, send):155 body = {}156 for name, value in scope.get("headers", []):157 body[name.capitalize().decode()] = value.decode()158159 await send(160 {161 "type": "http.response.start",162 "status": 200,163 "headers": [[b"content-type", b"application/json"]],164 }165 )166 await send({"type": "http.response.body", "body": json.dumps(body).encode()})167168169async def redirect_301(scope, receive, send):170 await send(171 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}172 )173 await send({"type": "http.response.body"})174175176SERVER_SCOPE = "session"177178179@pytest.fixture(scope=SERVER_SCOPE)180def cert_authority():181 return trustme.CA()182183184@pytest.fixture(scope=SERVER_SCOPE)185def ca_cert_pem_file(cert_authority):186 with cert_authority.cert_pem.tempfile() as tmp:187 yield tmp188189190@pytest.fixture(scope=SERVER_SCOPE)191def localhost_cert(cert_authority):192 return cert_authority.issue_cert("localhost")193194195@pytest.fixture(scope=SERVER_SCOPE)196def cert_pem_file(localhost_cert):197 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:198 yield tmp199200201@pytest.fixture(scope=SERVER_SCOPE)202def cert_private_key_file(localhost_cert):203 with localhost_cert.private_key_pem.tempfile() as tmp:204 yield tmp205206207@pytest.fixture(scope=SERVER_SCOPE)208def cert_encrypted_private_key_file(localhost_cert):209 # Deserialize the private key and then reserialize with a password210 private_key = load_pem_private_key(211 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()212 )213 encrypted_private_key_pem = trustme.Blob(214 private_key.private_bytes(215 Encoding.PEM,216 PrivateFormat.TraditionalOpenSSL,217 BestAvailableEncryption(password=b"password"),218 )219 )220 with encrypted_private_key_pem.tempfile() as tmp:221 yield tmp222223224class TestServer(Server):225 @property226 def url(self) -> URL:227 protocol = "https" if self.config.is_ssl else "http"228 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")229230 def install_signal_handlers(self) -> None:231 # Disable the default installation of handlers for signals such as SIGTERM,232 # because it can only be done in the main thread.233 pass234235 async def serve(self, sockets=None):236 self.restart_requested = asyncio.Event()237238 loop = asyncio.get_event_loop()239 tasks = {240 loop.create_task(super().serve(sockets=sockets)),241 loop.create_task(self.watch_restarts()),242 }243 await asyncio.wait(tasks)244245 async def restart(self) -> None:246 # Ensure we are in an asyncio environment.247 assert asyncio.get_event_loop() is not None248 # This may be called from a different thread than the one the server is249 # running on. For this reason, we use an event to coordinate with the server250 # instead of calling shutdown()/startup() directly.251 self.restart_requested.set()252 self.started = False253 while not self.started:254 await asyncio.sleep(0.5)255256 async def watch_restarts(self):257 while True:258 if self.should_exit:259 return260261 try:262 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)263 except asyncio.TimeoutError:264 continue265266 self.restart_requested.clear()267 await self.shutdown()268 await self.startup()269270271@pytest.fixture272def restart(backend):273 """Restart the running server from an async test function.274275 This fixture deals with possible differences between the environment of the276 test function and that of the server.277 """278 asyncio_backend = AsyncioBackend()279 backend_implementation = lookup_backend(backend)280281 async def restart(server):282 await backend_implementation.run_in_threadpool(283 asyncio_backend.run, server.restart284 )285286 return restart287288289def serve_in_thread(server: Server):290 thread = threading.Thread(target=server.run)291 thread.start()292 try:293 while not server.started:294 time.sleep(1e-3)295 yield server296 finally:297 server.should_exit = True298 thread.join()299300301@pytest.fixture(scope=SERVER_SCOPE)302def server():303 config = Config(app=app, lifespan="off", loop="asyncio")304 server = TestServer(config=config)305 yield from serve_in_thread(server)306307308@pytest.fixture(scope=SERVER_SCOPE)309def uds_server():310 uds = "test_server.sock"311 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)312 server = TestServer(config=config)313 yield from serve_in_thread(server)314 os.remove(uds)315316317@pytest.fixture(scope=SERVER_SCOPE)318def https_server(cert_pem_file, cert_private_key_file):319 config = Config(320 app=app,321 lifespan="off",322 ssl_certfile=cert_pem_file,323 ssl_keyfile=cert_private_key_file,324 host="localhost",325 port=8001,326 loop="asyncio",327 )328 server = TestServer(config=config)329 yield from serve_in_thread(server)330331332@pytest.fixture(scope=SERVER_SCOPE)333def https_uds_server(cert_pem_file, cert_private_key_file):334 uds = "https_test_server.sock"335 config = Config(336 app=app,337 lifespan="off",338 ssl_certfile=cert_pem_file,339 ssl_keyfile=cert_private_key_file,340 uds=uds,341 loop="asyncio",342 )343 server = TestServer(config=config)344 yield from serve_in_thread(server)345 os.remove(uds)