Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

305 lines · 8.3 KiB · Python

Last changed by

Attempt to resolve test flakiness (#946)Tom Christiebefore adoptiond6b3794

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 URL21from tests.concurrency import sleep2223ENVIRONMENT_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(35    params=[36        pytest.param("asyncio", marks=pytest.mark.asyncio),37        pytest.param("trio", marks=pytest.mark.trio),38    ]39)40def async_environment(request: typing.Any) -> str:41    """42    Mark a test function to be run on both asyncio and trio.4344    Equivalent to having a pair of tests, each respectively marked with45    '@pytest.mark.asyncio' and '@pytest.mark.trio'.4647    Intended usage:4849    ```50    @pytest.mark.usefixtures("async_environment")51    async def my_async_test():52        ...53    ```54    """55    return request.param565758@pytest.fixture(scope="function", autouse=True)59def clean_environ() -> typing.Dict[str, typing.Any]:60    """Keeps os.environ clean for every test without having to mock os.environ"""61    original_environ = os.environ.copy()62    os.environ.clear()63    os.environ.update(64        {65            k: v66            for k, v in original_environ.items()67            if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES68        }69    )70    yield71    os.environ.clear()72    os.environ.update(original_environ)737475async def app(scope, receive, send):76    assert scope["type"] == "http"77    if scope["path"].startswith("/slow_response"):78        await slow_response(scope, receive, send)79    elif scope["path"].startswith("/premature_close"):80        await premature_close(scope, receive, send)81    elif scope["path"].startswith("/status"):82        await status_code(scope, receive, send)83    elif scope["path"].startswith("/echo_body"):84        await echo_body(scope, receive, send)85    elif scope["path"].startswith("/echo_headers"):86        await echo_headers(scope, receive, send)87    elif scope["path"].startswith("/redirect_301"):88        await redirect_301(scope, receive, send)89    else:90        await hello_world(scope, receive, send)919293async def hello_world(scope, receive, send):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 slow_response(scope, receive, send):105    await sleep(1.0)106    await send(107        {108            "type": "http.response.start",109            "status": 200,110            "headers": [[b"content-type", b"text/plain"]],111        }112    )113    await send({"type": "http.response.body", "body": b"Hello, world!"})114115116async def premature_close(scope, receive, send):117    await send(118        {119            "type": "http.response.start",120            "status": 200,121            "headers": [[b"content-type", b"text/plain"]],122        }123    )124125126async def status_code(scope, receive, send):127    status_code = int(scope["path"].replace("/status/", ""))128    await send(129        {130            "type": "http.response.start",131            "status": status_code,132            "headers": [[b"content-type", b"text/plain"]],133        }134    )135    await send({"type": "http.response.body", "body": b"Hello, world!"})136137138async def echo_body(scope, receive, send):139    body = b""140    more_body = True141142    while more_body:143        message = await receive()144        body += message.get("body", b"")145        more_body = message.get("more_body", False)146147    await send(148        {149            "type": "http.response.start",150            "status": 200,151            "headers": [[b"content-type", b"text/plain"]],152        }153    )154    await send({"type": "http.response.body", "body": body})155156157async def echo_headers(scope, receive, send):158    body = {}159    for name, value in scope.get("headers", []):160        body[name.capitalize().decode()] = value.decode()161162    await send(163        {164            "type": "http.response.start",165            "status": 200,166            "headers": [[b"content-type", b"application/json"]],167        }168    )169    await send({"type": "http.response.body", "body": json.dumps(body).encode()})170171172async def redirect_301(scope, receive, send):173    await send(174        {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}175    )176    await send({"type": "http.response.body"})177178179SERVER_SCOPE = "session"180181182@pytest.fixture(scope=SERVER_SCOPE)183def cert_authority():184    return trustme.CA()185186187@pytest.fixture(scope=SERVER_SCOPE)188def ca_cert_pem_file(cert_authority):189    with cert_authority.cert_pem.tempfile() as tmp:190        yield tmp191192193@pytest.fixture(scope=SERVER_SCOPE)194def localhost_cert(cert_authority):195    return cert_authority.issue_cert("localhost")196197198@pytest.fixture(scope=SERVER_SCOPE)199def cert_pem_file(localhost_cert):200    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:201        yield tmp202203204@pytest.fixture(scope=SERVER_SCOPE)205def cert_private_key_file(localhost_cert):206    with localhost_cert.private_key_pem.tempfile() as tmp:207        yield tmp208209210@pytest.fixture(scope=SERVER_SCOPE)211def cert_encrypted_private_key_file(localhost_cert):212    # Deserialize the private key and then reserialize with a password213    private_key = load_pem_private_key(214        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()215    )216    encrypted_private_key_pem = trustme.Blob(217        private_key.private_bytes(218            Encoding.PEM,219            PrivateFormat.TraditionalOpenSSL,220            BestAvailableEncryption(password=b"password"),221        )222    )223    with encrypted_private_key_pem.tempfile() as tmp:224        yield tmp225226227class TestServer(Server):228    @property229    def url(self) -> URL:230        protocol = "https" if self.config.is_ssl else "http"231        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")232233    def install_signal_handlers(self) -> None:234        # Disable the default installation of handlers for signals such as SIGTERM,235        # because it can only be done in the main thread.236        pass237238    async def serve(self, sockets=None):239        self.restart_requested = asyncio.Event()240241        loop = asyncio.get_event_loop()242        tasks = {243            loop.create_task(super().serve(sockets=sockets)),244            loop.create_task(self.watch_restarts()),245        }246        await asyncio.wait(tasks)247248    async def restart(self) -> None:249        # This coroutine may be called from a different thread than the one the250        # server is running on, and from an async environment that's not asyncio.251        # For this reason, we use an event to coordinate with the server252        # instead of calling shutdown()/startup() directly, and should not make253        # any asyncio-specific operations.254        self.started = False255        self.restart_requested.set()256        while not self.started:257            await sleep(0.2)258259    async def watch_restarts(self):260        while True:261            if self.should_exit:262                return263264            try:265                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)266            except asyncio.TimeoutError:267                continue268269            self.restart_requested.clear()270            await self.shutdown()271            await self.startup()272273274def serve_in_thread(server: Server):275    thread = threading.Thread(target=server.run)276    thread.start()277    try:278        while not server.started:279            time.sleep(1e-3)280        yield server281    finally:282        server.should_exit = True283        thread.join()284285286@pytest.fixture(scope=SERVER_SCOPE)287def server():288    config = Config(app=app, lifespan="off", loop="asyncio")289    server = TestServer(config=config)290    yield from serve_in_thread(server)291292293@pytest.fixture(scope=SERVER_SCOPE)294def https_server(cert_pem_file, cert_private_key_file):295    config = Config(296        app=app,297        lifespan="off",298        ssl_certfile=cert_pem_file,299        ssl_keyfile=cert_private_key_file,300        host="localhost",301        port=8001,302        loop="asyncio",303    )304    server = TestServer(config=config)305    yield from serve_in_thread(server)