Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

294 lines · 8.0 KiB · Python

Last changed by

Add trio concurrency backend (#276)Florimond Mancabefore adoption08355c6

History of this file

Take 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, AsyncioBackend2122ENVIRONMENT_VARIABLES = {23    "SSL_CERT_FILE",24    "SSL_CERT_DIR",25    "HTTP_PROXY",26    "HTTPS_PROXY",27    "ALL_PROXY",28    "NO_PROXY",29    "SSLKEYLOGFILE",30}313233@pytest.fixture(scope="function", autouse=True)34def clean_environ() -> typing.Dict[str, typing.Any]:35    """Keeps os.environ clean for every test without having to mock os.environ"""36    original_environ = os.environ.copy()37    os.environ.clear()38    os.environ.update(39        {40            k: v41            for k, v in original_environ.items()42            if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES43        }44    )45    yield46    os.environ.clear()47    os.environ.update(original_environ)484950backend_params = [pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)]5152try:53    from httpx.concurrency.trio import TrioBackend54except ImportError:  # pragma: no cover55    pass56else:57    backend_params.append(pytest.param(TrioBackend, marks=pytest.mark.trio))585960@pytest.fixture(params=backend_params)61def backend(request):62    backend_cls = request.param63    return backend_cls()646566async def app(scope, receive, send):67    assert scope["type"] == "http"68    if scope["path"].startswith("/slow_response"):69        await slow_response(scope, receive, send)70    elif scope["path"].startswith("/status"):71        await status_code(scope, receive, send)72    elif scope["path"].startswith("/echo_body"):73        await echo_body(scope, receive, send)74    elif scope["path"].startswith("/echo_headers"):75        await echo_headers(scope, receive, send)76    else:77        await hello_world(scope, receive, send)787980async def hello_world(scope, receive, send):81    await send(82        {83            "type": "http.response.start",84            "status": 200,85            "headers": [[b"content-type", b"text/plain"]],86        }87    )88    await send({"type": "http.response.body", "body": b"Hello, world!"})899091async def slow_response(scope, receive, send):92    delay_ms_str: str = scope["path"].replace("/slow_response/", "")93    try:94        delay_ms = float(delay_ms_str)95    except ValueError:96        delay_ms = 10097    await asyncio.sleep(delay_ms / 1000.0)98    await send(99        {100            "type": "http.response.start",101            "status": 200,102            "headers": [[b"content-type", b"text/plain"]],103        }104    )105    await send({"type": "http.response.body", "body": b"Hello, world!"})106107108async def status_code(scope, receive, send):109    status_code = int(scope["path"].replace("/status/", ""))110    await send(111        {112            "type": "http.response.start",113            "status": status_code,114            "headers": [[b"content-type", b"text/plain"]],115        }116    )117    await send({"type": "http.response.body", "body": b"Hello, world!"})118119120async def echo_body(scope, receive, send):121    body = b""122    more_body = True123124    while more_body:125        message = await receive()126        body += message.get("body", b"")127        more_body = message.get("more_body", False)128129    await send(130        {131            "type": "http.response.start",132            "status": 200,133            "headers": [[b"content-type", b"text/plain"]],134        }135    )136    await send({"type": "http.response.body", "body": body})137138139async def echo_headers(scope, receive, send):140    body = {}141    for name, value in scope.get("headers", []):142        body[name.capitalize().decode()] = value.decode()143144    await send(145        {146            "type": "http.response.start",147            "status": 200,148            "headers": [[b"content-type", b"application/json"]],149        }150    )151    await send({"type": "http.response.body", "body": json.dumps(body).encode()})152153154SERVER_SCOPE = "session"155156157@pytest.fixture(scope=SERVER_SCOPE)158def cert_authority():159    return trustme.CA()160161162@pytest.fixture(scope=SERVER_SCOPE)163def ca_cert_pem_file(cert_authority):164    with cert_authority.cert_pem.tempfile() as tmp:165        yield tmp166167168@pytest.fixture(scope=SERVER_SCOPE)169def localhost_cert(cert_authority):170    return cert_authority.issue_cert("localhost")171172173@pytest.fixture(scope=SERVER_SCOPE)174def cert_pem_file(localhost_cert):175    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:176        yield tmp177178179@pytest.fixture(scope=SERVER_SCOPE)180def cert_private_key_file(localhost_cert):181    with localhost_cert.private_key_pem.tempfile() as tmp:182        yield tmp183184185@pytest.fixture(scope=SERVER_SCOPE)186def cert_encrypted_private_key_file(localhost_cert):187    # Deserialize the private key and then reserialize with a password188    private_key = load_pem_private_key(189        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()190    )191    encrypted_private_key_pem = trustme.Blob(192        private_key.private_bytes(193            Encoding.PEM,194            PrivateFormat.TraditionalOpenSSL,195            BestAvailableEncryption(password=b"password"),196        )197    )198    with encrypted_private_key_pem.tempfile() as tmp:199        yield tmp200201202class TestServer(Server):203    @property204    def url(self) -> URL:205        protocol = "https" if self.config.is_ssl else "http"206        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")207208    def install_signal_handlers(self) -> None:209        # Disable the default installation of handlers for signals such as SIGTERM,210        # because it can only be done in the main thread.211        pass212213    async def serve(self, sockets=None):214        self.restart_requested = asyncio.Event()215216        loop = asyncio.get_event_loop()217        tasks = {218            loop.create_task(super().serve(sockets=sockets)),219            loop.create_task(self.watch_restarts()),220        }221        await asyncio.wait(tasks)222223    async def restart(self) -> None:224        # Ensure we are in an asyncio environment.225        assert asyncio.get_event_loop() is not None226        # This may be called from a different thread than the one the server is227        # running on. For this reason, we use an event to coordinate with the server228        # instead of calling shutdown()/startup() directly.229        self.restart_requested.set()230        self.started = False231        while not self.started:232            await asyncio.sleep(0.5)233234    async def watch_restarts(self):235        while True:236            if self.should_exit:237                return238239            try:240                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)241            except asyncio.TimeoutError:242                continue243244            self.restart_requested.clear()245            await self.shutdown()246            await self.startup()247248249@pytest.fixture250def restart(backend):251    """Restart the running server from an async test function.252253    This fixture deals with possible differences between the environment of the254    test function and that of the server.255    """256257    async def restart(server):258        await backend.run_in_threadpool(AsyncioBackend().run, server.restart)259260    return restart261262263def serve_in_thread(server: Server):264    thread = threading.Thread(target=server.run)265    thread.start()266    try:267        while not server.started:268            time.sleep(1e-3)269        yield server270    finally:271        server.should_exit = True272        thread.join()273274275@pytest.fixture(scope=SERVER_SCOPE)276def server():277    config = Config(app=app, lifespan="off", loop="asyncio")278    server = TestServer(config=config)279    yield from serve_in_thread(server)280281282@pytest.fixture(scope=SERVER_SCOPE)283def https_server(cert_pem_file, cert_private_key_file):284    config = Config(285        app=app,286        lifespan="off",287        ssl_certfile=cert_pem_file,288        ssl_keyfile=cert_private_key_file,289        host="localhost",290        port=8001,291        loop="asyncio",292    )293    server = TestServer(config=config)294    yield from serve_in_thread(server)