Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

290 lines · 7.9 KiB · Python

Last changed by

Don't check trio import in definition of backend fixture params (#447)Florimond Mancabefore adoptionfc3df51

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, 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    else:73        await hello_world(scope, receive, send)747576async def hello_world(scope, receive, send):77    await send(78        {79            "type": "http.response.start",80            "status": 200,81            "headers": [[b"content-type", b"text/plain"]],82        }83    )84    await send({"type": "http.response.body", "body": b"Hello, world!"})858687async def slow_response(scope, receive, send):88    delay_ms_str: str = scope["path"].replace("/slow_response/", "")89    try:90        delay_ms = float(delay_ms_str)91    except ValueError:92        delay_ms = 10093    await asyncio.sleep(delay_ms / 1000.0)94    await send(95        {96            "type": "http.response.start",97            "status": 200,98            "headers": [[b"content-type", b"text/plain"]],99        }100    )101    await send({"type": "http.response.body", "body": b"Hello, world!"})102103104async def status_code(scope, receive, send):105    status_code = int(scope["path"].replace("/status/", ""))106    await send(107        {108            "type": "http.response.start",109            "status": status_code,110            "headers": [[b"content-type", b"text/plain"]],111        }112    )113    await send({"type": "http.response.body", "body": b"Hello, world!"})114115116async def echo_body(scope, receive, send):117    body = b""118    more_body = True119120    while more_body:121        message = await receive()122        body += message.get("body", b"")123        more_body = message.get("more_body", False)124125    await send(126        {127            "type": "http.response.start",128            "status": 200,129            "headers": [[b"content-type", b"text/plain"]],130        }131    )132    await send({"type": "http.response.body", "body": body})133134135async def echo_headers(scope, receive, send):136    body = {}137    for name, value in scope.get("headers", []):138        body[name.capitalize().decode()] = value.decode()139140    await send(141        {142            "type": "http.response.start",143            "status": 200,144            "headers": [[b"content-type", b"application/json"]],145        }146    )147    await send({"type": "http.response.body", "body": json.dumps(body).encode()})148149150SERVER_SCOPE = "session"151152153@pytest.fixture(scope=SERVER_SCOPE)154def cert_authority():155    return trustme.CA()156157158@pytest.fixture(scope=SERVER_SCOPE)159def ca_cert_pem_file(cert_authority):160    with cert_authority.cert_pem.tempfile() as tmp:161        yield tmp162163164@pytest.fixture(scope=SERVER_SCOPE)165def localhost_cert(cert_authority):166    return cert_authority.issue_cert("localhost")167168169@pytest.fixture(scope=SERVER_SCOPE)170def cert_pem_file(localhost_cert):171    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:172        yield tmp173174175@pytest.fixture(scope=SERVER_SCOPE)176def cert_private_key_file(localhost_cert):177    with localhost_cert.private_key_pem.tempfile() as tmp:178        yield tmp179180181@pytest.fixture(scope=SERVER_SCOPE)182def cert_encrypted_private_key_file(localhost_cert):183    # Deserialize the private key and then reserialize with a password184    private_key = load_pem_private_key(185        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()186    )187    encrypted_private_key_pem = trustme.Blob(188        private_key.private_bytes(189            Encoding.PEM,190            PrivateFormat.TraditionalOpenSSL,191            BestAvailableEncryption(password=b"password"),192        )193    )194    with encrypted_private_key_pem.tempfile() as tmp:195        yield tmp196197198class TestServer(Server):199    @property200    def url(self) -> URL:201        protocol = "https" if self.config.is_ssl else "http"202        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")203204    def install_signal_handlers(self) -> None:205        # Disable the default installation of handlers for signals such as SIGTERM,206        # because it can only be done in the main thread.207        pass208209    async def serve(self, sockets=None):210        self.restart_requested = asyncio.Event()211212        loop = asyncio.get_event_loop()213        tasks = {214            loop.create_task(super().serve(sockets=sockets)),215            loop.create_task(self.watch_restarts()),216        }217        await asyncio.wait(tasks)218219    async def restart(self) -> None:220        # Ensure we are in an asyncio environment.221        assert asyncio.get_event_loop() is not None222        # This may be called from a different thread than the one the server is223        # running on. For this reason, we use an event to coordinate with the server224        # instead of calling shutdown()/startup() directly.225        self.restart_requested.set()226        self.started = False227        while not self.started:228            await asyncio.sleep(0.5)229230    async def watch_restarts(self):231        while True:232            if self.should_exit:233                return234235            try:236                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)237            except asyncio.TimeoutError:238                continue239240            self.restart_requested.clear()241            await self.shutdown()242            await self.startup()243244245@pytest.fixture246def restart(backend):247    """Restart the running server from an async test function.248249    This fixture deals with possible differences between the environment of the250    test function and that of the server.251    """252253    async def restart(server):254        await backend.run_in_threadpool(AsyncioBackend().run, server.restart)255256    return restart257258259def serve_in_thread(server: Server):260    thread = threading.Thread(target=server.run)261    thread.start()262    try:263        while not server.started:264            time.sleep(1e-3)265        yield server266    finally:267        server.should_exit = True268        thread.join()269270271@pytest.fixture(scope=SERVER_SCOPE)272def server():273    config = Config(app=app, lifespan="off", loop="asyncio")274    server = TestServer(config=config)275    yield from serve_in_thread(server)276277278@pytest.fixture(scope=SERVER_SCOPE)279def https_server(cert_pem_file, cert_private_key_file):280    config = Config(281        app=app,282        lifespan="off",283        ssl_certfile=cert_pem_file,284        ssl_keyfile=cert_private_key_file,285        host="localhost",286        port=8001,287        loop="asyncio",288    )289    server = TestServer(config=config)290    yield from serve_in_thread(server)