Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

329 lines · 9.4 KiB · Python

Last changed by

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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.server import Server1920from httpx import URL21from tests.concurrency import sleep2223if typing.TYPE_CHECKING:  # pragma: no cover24    from httpx._transports.asgi import _Receive, _Send2526ENVIRONMENT_VARIABLES = {27    "SSL_CERT_FILE",28    "SSL_CERT_DIR",29    "HTTP_PROXY",30    "HTTPS_PROXY",31    "ALL_PROXY",32    "NO_PROXY",33    "SSLKEYLOGFILE",34}353637@pytest.fixture(38    params=[39        pytest.param("asyncio", marks=pytest.mark.asyncio),40        pytest.param("trio", marks=pytest.mark.trio),41    ]42)43def async_environment(request: typing.Any) -> str:44    """45    Mark a test function to be run on both asyncio and trio.4647    Equivalent to having a pair of tests, each respectively marked with48    '@pytest.mark.asyncio' and '@pytest.mark.trio'.4950    Intended usage:5152    ```53    @pytest.mark.usefixtures("async_environment")54    async def my_async_test():55        ...56    ```57    """58    return typing.cast(str, request.param)596061@pytest.fixture(scope="function", autouse=True)62def clean_environ():63    """Keeps os.environ clean for every test without having to mock os.environ"""64    original_environ = os.environ.copy()65    os.environ.clear()66    os.environ.update(67        {68            k: v69            for k, v in original_environ.items()70            if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES71        }72    )73    yield74    os.environ.clear()75    os.environ.update(original_environ)767778_Scope = typing.Dict[str, typing.Any]798081async def app(scope: _Scope, receive: "_Receive", send: "_Send") -> None:82    assert scope["type"] == "http"83    if scope["path"].startswith("/slow_response"):84        await slow_response(scope, receive, send)85    elif scope["path"].startswith("/status"):86        await status_code(scope, receive, send)87    elif scope["path"].startswith("/echo_body"):88        await echo_body(scope, receive, send)89    elif scope["path"].startswith("/echo_binary"):90        await echo_binary(scope, receive, send)91    elif scope["path"].startswith("/echo_headers"):92        await echo_headers(scope, receive, send)93    elif scope["path"].startswith("/redirect_301"):94        await redirect_301(scope, receive, send)95    elif scope["path"].startswith("/json"):96        await hello_world_json(scope, receive, send)97    else:98        await hello_world(scope, receive, send)99100101async def hello_world(scope: _Scope, receive: "_Receive", send: "_Send") -> None:102    await send(103        {104            "type": "http.response.start",105            "status": 200,106            "headers": [[b"content-type", b"text/plain"]],107        }108    )109    await send({"type": "http.response.body", "body": b"Hello, world!"})110111112async def hello_world_json(scope: _Scope, receive: "_Receive", send: "_Send") -> None:113    await send(114        {115            "type": "http.response.start",116            "status": 200,117            "headers": [[b"content-type", b"application/json"]],118        }119    )120    await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'})121122123async def slow_response(scope: _Scope, receive: "_Receive", send: "_Send") -> None:124    await sleep(1.0)125    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": b"Hello, world!"})133134135async def status_code(scope: _Scope, receive: "_Receive", send: "_Send") -> None:136    status_code = int(scope["path"].replace("/status/", ""))137    await send(138        {139            "type": "http.response.start",140            "status": status_code,141            "headers": [[b"content-type", b"text/plain"]],142        }143    )144    await send({"type": "http.response.body", "body": b"Hello, world!"})145146147async def echo_body(scope: _Scope, receive: "_Receive", send: "_Send") -> None:148    body = b""149    more_body = True150151    while more_body:152        message = await receive()153        body += message.get("body", b"")154        more_body = message.get("more_body", False)155156    await send(157        {158            "type": "http.response.start",159            "status": 200,160            "headers": [[b"content-type", b"text/plain"]],161        }162    )163    await send({"type": "http.response.body", "body": body})164165166async def echo_binary(scope: _Scope, receive: "_Receive", send: "_Send") -> None:167    body = b""168    more_body = True169170    while more_body:171        message = await receive()172        body += message.get("body", b"")173        more_body = message.get("more_body", False)174175    await send(176        {177            "type": "http.response.start",178            "status": 200,179            "headers": [[b"content-type", b"application/octet-stream"]],180        }181    )182    await send({"type": "http.response.body", "body": body})183184185async def echo_headers(scope: _Scope, receive: "_Receive", send: "_Send") -> None:186    body = {187        name.capitalize().decode(): value.decode()188        for name, value in scope.get("headers", [])189    }190    await send(191        {192            "type": "http.response.start",193            "status": 200,194            "headers": [[b"content-type", b"application/json"]],195        }196    )197    await send({"type": "http.response.body", "body": json.dumps(body).encode()})198199200async def redirect_301(scope: _Scope, receive: "_Receive", send: "_Send") -> None:201    await send(202        {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}203    )204    await send({"type": "http.response.body"})205206207@pytest.fixture(scope="session")208def cert_authority():209    return trustme.CA()210211212@pytest.fixture(scope="session")213def ca_cert_pem_file(cert_authority):214    with cert_authority.cert_pem.tempfile() as tmp:215        yield tmp216217218@pytest.fixture(scope="session")219def localhost_cert(cert_authority):220    return cert_authority.issue_cert("localhost")221222223@pytest.fixture(scope="session")224def cert_pem_file(localhost_cert):225    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:226        yield tmp227228229@pytest.fixture(scope="session")230def cert_private_key_file(localhost_cert):231    with localhost_cert.private_key_pem.tempfile() as tmp:232        yield tmp233234235@pytest.fixture(scope="session")236def cert_encrypted_private_key_file(localhost_cert):237    # Deserialize the private key and then reserialize with a password238    private_key = load_pem_private_key(239        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()240    )241    encrypted_private_key_pem = trustme.Blob(242        private_key.private_bytes(243            Encoding.PEM,244            PrivateFormat.TraditionalOpenSSL,245            BestAvailableEncryption(password=b"password"),246        )247    )248    with encrypted_private_key_pem.tempfile() as tmp:249        yield tmp250251252class TestServer(Server):253    @property254    def url(self) -> URL:255        protocol = "https" if self.config.is_ssl else "http"256        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")257258    def install_signal_handlers(self) -> None:259        # Disable the default installation of handlers for signals such as SIGTERM,260        # because it can only be done in the main thread.261        pass262263    async def serve(self, sockets=None):264        self.restart_requested = asyncio.Event()265266        loop = asyncio.get_event_loop()267        tasks = {268            loop.create_task(super().serve(sockets=sockets)),269            loop.create_task(self.watch_restarts()),270        }271        await asyncio.wait(tasks)272273    async def restart(self) -> None:  # pragma: no cover274        # This coroutine may be called from a different thread than the one the275        # server is running on, and from an async environment that's not asyncio.276        # For this reason, we use an event to coordinate with the server277        # instead of calling shutdown()/startup() directly, and should not make278        # any asyncio-specific operations.279        self.started = False280        self.restart_requested.set()281        while not self.started:282            await sleep(0.2)283284    async def watch_restarts(self) -> None:  # pragma: no cover285        while True:286            if self.should_exit:287                return288289            try:290                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)291            except asyncio.TimeoutError:292                continue293294            self.restart_requested.clear()295            await self.shutdown()296            await self.startup()297298299def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:300    thread = threading.Thread(target=server.run)301    thread.start()302    try:303        while not server.started:304            time.sleep(1e-3)305        yield server306    finally:307        server.should_exit = True308        thread.join()309310311@pytest.fixture(scope="session")312def server() -> typing.Iterator[TestServer]:313    config = Config(app=app, lifespan="off", loop="asyncio")314    server = TestServer(config=config)315    yield from serve_in_thread(server)316317318@pytest.fixture(scope="session")319def https_server(cert_pem_file, cert_private_key_file):320    config = Config(321        app=app,322        lifespan="off",323        ssl_certfile=cert_pem_file,324        ssl_keyfile=cert_private_key_file,325        port=8001,326        loop="asyncio",327    )328    server = TestServer(config=config)329    yield from serve_in_thread(server)