conftest.py
This file
Path
tests/conftest.py
249 lines · 6.6 KiB · Python
Last changed by
Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
History of this fileTake it
1import asyncio2import os3import threading4import time5import typing67import pytest8import trustme9from cryptography.hazmat.primitives.serialization import (10 BestAvailableEncryption,11 Encoding,12 PrivateFormat,13)14from uvicorn.config import Config15from uvicorn.main import Server1617from httpx import URL, AsyncioBackend1819ENVIRONMENT_VARIABLES = (20 "SSL_CERT_FILE",21 "REQUESTS_CA_BUNDLE",22 "CURL_CA_BUNDLE",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 for key in ENVIRONMENT_VARIABLES:36 os.environ.pop(key, None)37 yield38 os.environ.clear()39 os.environ.update(original_environ)404142@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])43def backend(request):44 backend_cls = request.param45 return backend_cls()464748async def app(scope, receive, send):49 assert scope["type"] == "http"50 if scope["path"] == "/slow_response":51 await slow_response(scope, receive, send)52 elif scope["path"].startswith("/status"):53 await status_code(scope, receive, send)54 elif scope["path"].startswith("/echo_body"):55 await echo_body(scope, receive, send)56 else:57 await hello_world(scope, receive, send)585960async def hello_world(scope, receive, send):61 await send(62 {63 "type": "http.response.start",64 "status": 200,65 "headers": [[b"content-type", b"text/plain"]],66 }67 )68 await send({"type": "http.response.body", "body": b"Hello, world!"})697071async def slow_response(scope, receive, send):72 await asyncio.sleep(0.1)73 await send(74 {75 "type": "http.response.start",76 "status": 200,77 "headers": [[b"content-type", b"text/plain"]],78 }79 )80 await send({"type": "http.response.body", "body": b"Hello, world!"})818283async def status_code(scope, receive, send):84 status_code = int(scope["path"].replace("/status/", ""))85 await send(86 {87 "type": "http.response.start",88 "status": status_code,89 "headers": [[b"content-type", b"text/plain"]],90 }91 )92 await send({"type": "http.response.body", "body": b"Hello, world!"})939495async def echo_body(scope, receive, send):96 body = b""97 more_body = True9899 while more_body:100 message = await receive()101 body += message.get("body", b"")102 more_body = message.get("more_body", False)103104 await send(105 {106 "type": "http.response.start",107 "status": 200,108 "headers": [[b"content-type", b"text/plain"]],109 }110 )111 await send({"type": "http.response.body", "body": body})112113114class CAWithPKEncryption(trustme.CA):115 """Implementation of trustme.CA() that can emit116 private keys that are encrypted with a password.117 """118119 @property120 def encrypted_private_key_pem(self):121 return trustme.Blob(122 self._private_key.private_bytes(123 Encoding.PEM,124 PrivateFormat.TraditionalOpenSSL,125 BestAvailableEncryption(password=b"password"),126 )127 )128129130SERVER_SCOPE = "session"131132133@pytest.fixture(scope=SERVER_SCOPE)134def example_cert():135 ca = CAWithPKEncryption()136 ca.issue_cert("example.org")137 return ca138139140@pytest.fixture(scope=SERVER_SCOPE)141def cert_pem_file(example_cert):142 with example_cert.cert_pem.tempfile() as tmp:143 yield tmp144145146@pytest.fixture(scope=SERVER_SCOPE)147def cert_private_key_file(example_cert):148 with example_cert.private_key_pem.tempfile() as tmp:149 yield tmp150151152@pytest.fixture(scope=SERVER_SCOPE)153def cert_encrypted_private_key_file(example_cert):154 with example_cert.encrypted_private_key_pem.tempfile() as tmp:155 yield tmp156157158class TestServer(Server):159 @property160 def url(self) -> URL:161 protocol = "https" if self.config.is_ssl else "http"162 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")163164 def install_signal_handlers(self) -> None:165 # Disable the default installation of handlers for signals such as SIGTERM,166 # because it can only be done in the main thread.167 pass168169 async def serve(self, sockets=None):170 self.restart_requested = asyncio.Event()171172 loop = asyncio.get_event_loop()173 tasks = {174 loop.create_task(super().serve(sockets=sockets)),175 loop.create_task(self.watch_restarts()),176 }177 await asyncio.wait(tasks)178179 async def restart(self) -> None:180 # Ensure we are in an asyncio environment.181 assert asyncio.get_event_loop() is not None182 # This may be called from a different thread than the one the server is183 # running on. For this reason, we use an event to coordinate with the server184 # instead of calling shutdown()/startup() directly.185 self.restart_requested.set()186 self.started = False187 while not self.started:188 await asyncio.sleep(0.5)189190 async def watch_restarts(self):191 while True:192 if self.should_exit:193 return194195 try:196 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)197 except asyncio.TimeoutError:198 continue199200 self.restart_requested.clear()201 await self.shutdown()202 await self.startup()203204205@pytest.fixture206def restart(backend):207 """Restart the running server from an async test function.208209 This fixture deals with possible differences between the environment of the210 test function and that of the server.211 """212213 async def restart(server):214 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)215216 return restart217218219def serve_in_thread(server: Server):220 thread = threading.Thread(target=server.run)221 thread.start()222 try:223 while not server.started:224 time.sleep(1e-3)225 yield server226 finally:227 server.should_exit = True228 thread.join()229230231@pytest.fixture(scope=SERVER_SCOPE)232def server():233 config = Config(app=app, lifespan="off", loop="asyncio")234 server = TestServer(config=config)235 yield from serve_in_thread(server)236237238@pytest.fixture(scope=SERVER_SCOPE)239def https_server(cert_pem_file, cert_private_key_file):240 config = Config(241 app=app,242 lifespan="off",243 ssl_certfile=cert_pem_file,244 ssl_keyfile=cert_private_key_file,245 port=8001,246 loop="asyncio",247 )248 server = TestServer(config=config)249 yield from serve_in_thread(server)