Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

336 lines · 9.2 KiB · Python

Last changed by

Drop sync (#544)Tom Christiebefore adoption206c537

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("/premature_close"):67        await premature_close(scope, receive, send)68    elif scope["path"].startswith("/status"):69        await status_code(scope, receive, send)70    elif scope["path"].startswith("/echo_body"):71        await echo_body(scope, receive, send)72    elif scope["path"].startswith("/echo_headers"):73        await echo_headers(scope, receive, send)74    elif scope["path"].startswith("/redirect_301"):75        await redirect_301(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 premature_close(scope, receive, send):109    await send(110        {111            "type": "http.response.start",112            "status": 200,113            "headers": [[b"content-type", b"text/plain"]],114        }115    )116117118async def status_code(scope, receive, send):119    status_code = int(scope["path"].replace("/status/", ""))120    await send(121        {122            "type": "http.response.start",123            "status": status_code,124            "headers": [[b"content-type", b"text/plain"]],125        }126    )127    await send({"type": "http.response.body", "body": b"Hello, world!"})128129130async def echo_body(scope, receive, send):131    body = b""132    more_body = True133134    while more_body:135        message = await receive()136        body += message.get("body", b"")137        more_body = message.get("more_body", False)138139    await send(140        {141            "type": "http.response.start",142            "status": 200,143            "headers": [[b"content-type", b"text/plain"]],144        }145    )146    await send({"type": "http.response.body", "body": body})147148149async def echo_headers(scope, receive, send):150    body = {}151    for name, value in scope.get("headers", []):152        body[name.capitalize().decode()] = value.decode()153154    await send(155        {156            "type": "http.response.start",157            "status": 200,158            "headers": [[b"content-type", b"application/json"]],159        }160    )161    await send({"type": "http.response.body", "body": json.dumps(body).encode()})162163164async def redirect_301(scope, receive, send):165    await send(166        {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}167    )168    await send({"type": "http.response.body"})169170171SERVER_SCOPE = "session"172173174@pytest.fixture(scope=SERVER_SCOPE)175def cert_authority():176    return trustme.CA()177178179@pytest.fixture(scope=SERVER_SCOPE)180def ca_cert_pem_file(cert_authority):181    with cert_authority.cert_pem.tempfile() as tmp:182        yield tmp183184185@pytest.fixture(scope=SERVER_SCOPE)186def localhost_cert(cert_authority):187    return cert_authority.issue_cert("localhost")188189190@pytest.fixture(scope=SERVER_SCOPE)191def cert_pem_file(localhost_cert):192    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:193        yield tmp194195196@pytest.fixture(scope=SERVER_SCOPE)197def cert_private_key_file(localhost_cert):198    with localhost_cert.private_key_pem.tempfile() as tmp:199        yield tmp200201202@pytest.fixture(scope=SERVER_SCOPE)203def cert_encrypted_private_key_file(localhost_cert):204    # Deserialize the private key and then reserialize with a password205    private_key = load_pem_private_key(206        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()207    )208    encrypted_private_key_pem = trustme.Blob(209        private_key.private_bytes(210            Encoding.PEM,211            PrivateFormat.TraditionalOpenSSL,212            BestAvailableEncryption(password=b"password"),213        )214    )215    with encrypted_private_key_pem.tempfile() as tmp:216        yield tmp217218219class TestServer(Server):220    @property221    def url(self) -> URL:222        protocol = "https" if self.config.is_ssl else "http"223        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")224225    def install_signal_handlers(self) -> None:226        # Disable the default installation of handlers for signals such as SIGTERM,227        # because it can only be done in the main thread.228        pass229230    async def serve(self, sockets=None):231        self.restart_requested = asyncio.Event()232233        loop = asyncio.get_event_loop()234        tasks = {235            loop.create_task(super().serve(sockets=sockets)),236            loop.create_task(self.watch_restarts()),237        }238        await asyncio.wait(tasks)239240    async def restart(self) -> None:241        # Ensure we are in an asyncio environment.242        assert asyncio.get_event_loop() is not None243        # This may be called from a different thread than the one the server is244        # running on. For this reason, we use an event to coordinate with the server245        # instead of calling shutdown()/startup() directly.246        self.restart_requested.set()247        self.started = False248        while not self.started:249            await asyncio.sleep(0.5)250251    async def watch_restarts(self):252        while True:253            if self.should_exit:254                return255256            try:257                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)258            except asyncio.TimeoutError:259                continue260261            self.restart_requested.clear()262            await self.shutdown()263            await self.startup()264265266@pytest.fixture267def restart(backend):268    """Restart the running server from an async test function.269270    This fixture deals with possible differences between the environment of the271    test function and that of the server.272    """273274    async def restart(server):275        await backend.run_in_threadpool(AsyncioBackend().run, server.restart)276277    return restart278279280def serve_in_thread(server: Server):281    thread = threading.Thread(target=server.run)282    thread.start()283    try:284        while not server.started:285            time.sleep(1e-3)286        yield server287    finally:288        server.should_exit = True289        thread.join()290291292@pytest.fixture(scope=SERVER_SCOPE)293def server():294    config = Config(app=app, lifespan="off", loop="asyncio")295    server = TestServer(config=config)296    yield from serve_in_thread(server)297298299@pytest.fixture(scope=SERVER_SCOPE)300def uds_server():301    uds = "test_server.sock"302    config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)303    server = TestServer(config=config)304    yield from serve_in_thread(server)305    os.remove(uds)306307308@pytest.fixture(scope=SERVER_SCOPE)309def https_server(cert_pem_file, cert_private_key_file):310    config = Config(311        app=app,312        lifespan="off",313        ssl_certfile=cert_pem_file,314        ssl_keyfile=cert_private_key_file,315        host="localhost",316        port=8001,317        loop="asyncio",318    )319    server = TestServer(config=config)320    yield from serve_in_thread(server)321322323@pytest.fixture(scope=SERVER_SCOPE)324def https_uds_server(cert_pem_file, cert_private_key_file):325    uds = "https_test_server.sock"326    config = Config(327        app=app,328        lifespan="off",329        ssl_certfile=cert_pem_file,330        ssl_keyfile=cert_private_key_file,331        uds=uds,332        loop="asyncio",333    )334    server = TestServer(config=config)335    yield from serve_in_thread(server)336    os.remove(uds)