conftest.py
This file
Path
tests/conftest.py
225 lines · 6.0 KiB · Python
Last changed by
Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
History of this fileTake it
1import asyncio2import threading3import time45import pytest6import trustme7from cryptography.hazmat.primitives.serialization import (8 BestAvailableEncryption,9 Encoding,10 PrivateFormat,11)12from uvicorn.config import Config13from uvicorn.main import Server1415from httpx import URL, AsyncioBackend161718@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])19def backend(request):20 backend_cls = request.param21 return backend_cls()222324async def app(scope, receive, send):25 assert scope["type"] == "http"26 if scope["path"] == "/slow_response":27 await slow_response(scope, receive, send)28 elif scope["path"].startswith("/status"):29 await status_code(scope, receive, send)30 elif scope["path"].startswith("/echo_body"):31 await echo_body(scope, receive, send)32 else:33 await hello_world(scope, receive, send)343536async def hello_world(scope, receive, send):37 await send(38 {39 "type": "http.response.start",40 "status": 200,41 "headers": [[b"content-type", b"text/plain"]],42 }43 )44 await send({"type": "http.response.body", "body": b"Hello, world!"})454647async def slow_response(scope, receive, send):48 await asyncio.sleep(0.1)49 await send(50 {51 "type": "http.response.start",52 "status": 200,53 "headers": [[b"content-type", b"text/plain"]],54 }55 )56 await send({"type": "http.response.body", "body": b"Hello, world!"})575859async def status_code(scope, receive, send):60 status_code = int(scope["path"].replace("/status/", ""))61 await send(62 {63 "type": "http.response.start",64 "status": status_code,65 "headers": [[b"content-type", b"text/plain"]],66 }67 )68 await send({"type": "http.response.body", "body": b"Hello, world!"})697071async def echo_body(scope, receive, send):72 body = b""73 more_body = True7475 while more_body:76 message = await receive()77 body += message.get("body", b"")78 more_body = message.get("more_body", False)7980 await send(81 {82 "type": "http.response.start",83 "status": 200,84 "headers": [[b"content-type", b"text/plain"]],85 }86 )87 await send({"type": "http.response.body", "body": body})888990class CAWithPKEncryption(trustme.CA):91 """Implementation of trustme.CA() that can emit92 private keys that are encrypted with a password.93 """9495 @property96 def encrypted_private_key_pem(self):97 return trustme.Blob(98 self._private_key.private_bytes(99 Encoding.PEM,100 PrivateFormat.TraditionalOpenSSL,101 BestAvailableEncryption(password=b"password"),102 )103 )104105106SERVER_SCOPE = "session"107108109@pytest.fixture(scope=SERVER_SCOPE)110def example_cert():111 ca = CAWithPKEncryption()112 ca.issue_cert("example.org")113 return ca114115116@pytest.fixture(scope=SERVER_SCOPE)117def cert_pem_file(example_cert):118 with example_cert.cert_pem.tempfile() as tmp:119 yield tmp120121122@pytest.fixture(scope=SERVER_SCOPE)123def cert_private_key_file(example_cert):124 with example_cert.private_key_pem.tempfile() as tmp:125 yield tmp126127128@pytest.fixture(scope=SERVER_SCOPE)129def cert_encrypted_private_key_file(example_cert):130 with example_cert.encrypted_private_key_pem.tempfile() as tmp:131 yield tmp132133134class TestServer(Server):135 @property136 def url(self) -> URL:137 protocol = "https" if self.config.is_ssl else "http"138 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")139140 def install_signal_handlers(self) -> None:141 # Disable the default installation of handlers for signals such as SIGTERM,142 # because it can only be done in the main thread.143 pass144145 async def serve(self, sockets=None):146 self.restart_requested = asyncio.Event()147148 loop = asyncio.get_event_loop()149 tasks = {150 loop.create_task(super().serve(sockets=sockets)),151 loop.create_task(self.watch_restarts()),152 }153 await asyncio.wait(tasks)154155 async def restart(self) -> None:156 # Ensure we are in an asyncio environment.157 assert asyncio.get_event_loop() is not None158 # This may be called from a different thread than the one the server is159 # running on. For this reason, we use an event to coordinate with the server160 # instead of calling shutdown()/startup() directly.161 self.restart_requested.set()162 self.started = False163 while not self.started:164 await asyncio.sleep(0.5)165166 async def watch_restarts(self):167 while True:168 if self.should_exit:169 return170171 try:172 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)173 except asyncio.TimeoutError:174 continue175176 self.restart_requested.clear()177 await self.shutdown()178 await self.startup()179180181@pytest.fixture182def restart(backend):183 """Restart the running server from an async test function.184185 This fixture deals with possible differences between the environment of the186 test function and that of the server.187 """188189 async def restart(server):190 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)191192 return restart193194195def serve_in_thread(server: Server):196 thread = threading.Thread(target=server.run)197 thread.start()198 try:199 while not server.started:200 time.sleep(1e-3)201 yield server202 finally:203 server.should_exit = True204 thread.join()205206207@pytest.fixture(scope=SERVER_SCOPE)208def server():209 config = Config(app=app, lifespan="off", loop="asyncio")210 server = TestServer(config=config)211 yield from serve_in_thread(server)212213214@pytest.fixture(scope=SERVER_SCOPE)215def https_server(cert_pem_file, cert_private_key_file):216 config = Config(217 app=app,218 lifespan="off",219 ssl_certfile=cert_pem_file,220 ssl_keyfile=cert_private_key_file,221 port=8001,222 loop="asyncio",223 )224 server = TestServer(config=config)225 yield from serve_in_thread(server)