Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

221 lines · 5.9 KiB · Python

Last changed by

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

History of this file

Take 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 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    def install_signal_handlers(self) -> None:136        # Disable the default installation of handlers for signals such as SIGTERM,137        # because it can only be done in the main thread.138        pass139140    async def serve(self, sockets=None):141        self.restart_requested = asyncio.Event()142143        loop = asyncio.get_event_loop()144        tasks = {145            loop.create_task(super().serve(sockets=sockets)),146            loop.create_task(self.watch_restarts()),147        }148149        await asyncio.wait(tasks)150151    async def restart(self) -> None:152        # Ensure we are in an asyncio environment.153        assert asyncio.get_event_loop() is not None154        # This may be called from a different thread than the one the server is155        # running on. For this reason, we use an event to coordinate with the server156        # instead of calling shutdown()/startup() directly.157        self.restart_requested.set()158        self.started = False159        while not self.started:160            await asyncio.sleep(0.5)161162    async def watch_restarts(self):163        while True:164            if self.should_exit:165                return166167            try:168                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)169            except asyncio.TimeoutError:170                continue171172            self.restart_requested.clear()173            await self.shutdown()174            await self.startup()175176177@pytest.fixture178def restart(backend):179    """Restart the running server from an async test function.180181    This fixture deals with possible differences between the environment of the182    test function and that of the server.183    """184185    async def restart(server):186        await backend.run_in_threadpool(AsyncioBackend().run, server.restart)187188    return restart189190191def serve_in_thread(server: Server):192    thread = threading.Thread(target=server.run)193    thread.start()194    try:195        while not server.started:196            time.sleep(1e-3)197        yield server198    finally:199        server.should_exit = True200        thread.join()201202203@pytest.fixture(scope=SERVER_SCOPE)204def server():205    config = Config(app=app, lifespan="off", loop="asyncio")206    server = TestServer(config=config)207    yield from serve_in_thread(server)208209210@pytest.fixture(scope=SERVER_SCOPE)211def https_server(cert_pem_file, cert_private_key_file):212    config = Config(213        app=app,214        lifespan="off",215        ssl_certfile=cert_pem_file,216        ssl_keyfile=cert_private_key_file,217        port=8001,218        loop="asyncio",219    )220    server = TestServer(config=config)221    yield from serve_in_thread(server)