conftest.py
This file
Path
tests/conftest.py
303 lines · 8.2 KiB · Python
Last changed by
Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
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 URL, AsyncioBackend21from httpx.concurrency.trio import TrioBackend2223ENVIRONMENT_VARIABLES = {24 "SSL_CERT_FILE",25 "SSL_CERT_DIR",26 "HTTP_PROXY",27 "HTTPS_PROXY",28 "ALL_PROXY",29 "NO_PROXY",30 "SSLKEYLOGFILE",31}323334@pytest.fixture(scope="function", autouse=True)35def clean_environ() -> typing.Dict[str, typing.Any]:36 """Keeps os.environ clean for every test without having to mock os.environ"""37 original_environ = os.environ.copy()38 os.environ.clear()39 os.environ.update(40 {41 k: v42 for k, v in original_environ.items()43 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES44 }45 )46 yield47 os.environ.clear()48 os.environ.update(original_environ)495051@pytest.fixture(52 params=[53 pytest.param(AsyncioBackend, marks=pytest.mark.asyncio),54 pytest.param(TrioBackend, marks=pytest.mark.trio),55 ]56)57def backend(request):58 backend_cls = request.param59 return backend_cls()606162async def app(scope, receive, send):63 assert scope["type"] == "http"64 if scope["path"].startswith("/slow_response"):65 await slow_response(scope, receive, send)66 elif scope["path"].startswith("/status"):67 await status_code(scope, receive, send)68 elif scope["path"].startswith("/echo_body"):69 await echo_body(scope, receive, send)70 elif scope["path"].startswith("/echo_headers"):71 await echo_headers(scope, receive, send)72 elif scope["path"].startswith("/redirect_301"):73 await redirect_301(scope, receive, send)74 else:75 await hello_world(scope, receive, send)767778async def hello_world(scope, receive, send):79 await send(80 {81 "type": "http.response.start",82 "status": 200,83 "headers": [[b"content-type", b"text/plain"]],84 }85 )86 await send({"type": "http.response.body", "body": b"Hello, world!"})878889async def slow_response(scope, receive, send):90 delay_ms_str: str = scope["path"].replace("/slow_response/", "")91 try:92 delay_ms = float(delay_ms_str)93 except ValueError:94 delay_ms = 10095 await asyncio.sleep(delay_ms / 1000.0)96 await send(97 {98 "type": "http.response.start",99 "status": 200,100 "headers": [[b"content-type", b"text/plain"]],101 }102 )103 await send({"type": "http.response.body", "body": b"Hello, world!"})104105106async def status_code(scope, receive, send):107 status_code = int(scope["path"].replace("/status/", ""))108 await send(109 {110 "type": "http.response.start",111 "status": status_code,112 "headers": [[b"content-type", b"text/plain"]],113 }114 )115 await send({"type": "http.response.body", "body": b"Hello, world!"})116117118async def echo_body(scope, receive, send):119 body = b""120 more_body = True121122 while more_body:123 message = await receive()124 body += message.get("body", b"")125 more_body = message.get("more_body", False)126127 await send(128 {129 "type": "http.response.start",130 "status": 200,131 "headers": [[b"content-type", b"text/plain"]],132 }133 )134 await send({"type": "http.response.body", "body": body})135136137async def echo_headers(scope, receive, send):138 body = {}139 for name, value in scope.get("headers", []):140 body[name.capitalize().decode()] = value.decode()141142 await send(143 {144 "type": "http.response.start",145 "status": 200,146 "headers": [[b"content-type", b"application/json"]],147 }148 )149 await send({"type": "http.response.body", "body": json.dumps(body).encode()})150151152async def redirect_301(scope, receive, send):153 await send(154 {155 "type": "http.response.start",156 "status": 301,157 "headers": [[b"location", b"/"]],158 }159 )160 await send({"type": "http.response.body"})161162163SERVER_SCOPE = "session"164165166@pytest.fixture(scope=SERVER_SCOPE)167def cert_authority():168 return trustme.CA()169170171@pytest.fixture(scope=SERVER_SCOPE)172def ca_cert_pem_file(cert_authority):173 with cert_authority.cert_pem.tempfile() as tmp:174 yield tmp175176177@pytest.fixture(scope=SERVER_SCOPE)178def localhost_cert(cert_authority):179 return cert_authority.issue_cert("localhost")180181182@pytest.fixture(scope=SERVER_SCOPE)183def cert_pem_file(localhost_cert):184 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:185 yield tmp186187188@pytest.fixture(scope=SERVER_SCOPE)189def cert_private_key_file(localhost_cert):190 with localhost_cert.private_key_pem.tempfile() as tmp:191 yield tmp192193194@pytest.fixture(scope=SERVER_SCOPE)195def cert_encrypted_private_key_file(localhost_cert):196 # Deserialize the private key and then reserialize with a password197 private_key = load_pem_private_key(198 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()199 )200 encrypted_private_key_pem = trustme.Blob(201 private_key.private_bytes(202 Encoding.PEM,203 PrivateFormat.TraditionalOpenSSL,204 BestAvailableEncryption(password=b"password"),205 )206 )207 with encrypted_private_key_pem.tempfile() as tmp:208 yield tmp209210211class TestServer(Server):212 @property213 def url(self) -> URL:214 protocol = "https" if self.config.is_ssl else "http"215 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")216217 def install_signal_handlers(self) -> None:218 # Disable the default installation of handlers for signals such as SIGTERM,219 # because it can only be done in the main thread.220 pass221222 async def serve(self, sockets=None):223 self.restart_requested = asyncio.Event()224225 loop = asyncio.get_event_loop()226 tasks = {227 loop.create_task(super().serve(sockets=sockets)),228 loop.create_task(self.watch_restarts()),229 }230 await asyncio.wait(tasks)231232 async def restart(self) -> None:233 # Ensure we are in an asyncio environment.234 assert asyncio.get_event_loop() is not None235 # This may be called from a different thread than the one the server is236 # running on. For this reason, we use an event to coordinate with the server237 # instead of calling shutdown()/startup() directly.238 self.restart_requested.set()239 self.started = False240 while not self.started:241 await asyncio.sleep(0.5)242243 async def watch_restarts(self):244 while True:245 if self.should_exit:246 return247248 try:249 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)250 except asyncio.TimeoutError:251 continue252253 self.restart_requested.clear()254 await self.shutdown()255 await self.startup()256257258@pytest.fixture259def restart(backend):260 """Restart the running server from an async test function.261262 This fixture deals with possible differences between the environment of the263 test function and that of the server.264 """265266 async def restart(server):267 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)268269 return restart270271272def serve_in_thread(server: Server):273 thread = threading.Thread(target=server.run)274 thread.start()275 try:276 while not server.started:277 time.sleep(1e-3)278 yield server279 finally:280 server.should_exit = True281 thread.join()282283284@pytest.fixture(scope=SERVER_SCOPE)285def server():286 config = Config(app=app, lifespan="off", loop="asyncio")287 server = TestServer(config=config)288 yield from serve_in_thread(server)289290291@pytest.fixture(scope=SERVER_SCOPE)292def https_server(cert_pem_file, cert_private_key_file):293 config = Config(294 app=app,295 lifespan="off",296 ssl_certfile=cert_pem_file,297 ssl_keyfile=cert_private_key_file,298 host="localhost",299 port=8001,300 loop="asyncio",301 )302 server = TestServer(config=config)303 yield from serve_in_thread(server)