Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

287 lines · 8.4 KiB · Python

Last changed by

Introduce new `SSLContext` API & escalate deprecations. (#3319)Tom Christiebefore adoption8e36f2b

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 Server1920import httpx21from 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(scope="function", autouse=True)35def clean_environ():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)495051Message = typing.Dict[str, typing.Any]52Receive = typing.Callable[[], typing.Awaitable[Message]]53Send = typing.Callable[54    [typing.Dict[str, typing.Any]], typing.Coroutine[None, None, None]55]56Scope = typing.Dict[str, typing.Any]575859async def app(scope: Scope, receive: Receive, send: Send) -> None:60    assert scope["type"] == "http"61    if scope["path"].startswith("/slow_response"):62        await slow_response(scope, receive, send)63    elif scope["path"].startswith("/status"):64        await status_code(scope, receive, send)65    elif scope["path"].startswith("/echo_body"):66        await echo_body(scope, receive, send)67    elif scope["path"].startswith("/echo_binary"):68        await echo_binary(scope, receive, send)69    elif scope["path"].startswith("/echo_headers"):70        await echo_headers(scope, receive, send)71    elif scope["path"].startswith("/redirect_301"):72        await redirect_301(scope, receive, send)73    elif scope["path"].startswith("/json"):74        await hello_world_json(scope, receive, send)75    else:76        await hello_world(scope, receive, send)777879async def hello_world(scope: Scope, receive: Receive, send: Send) -> None:80    await send(81        {82            "type": "http.response.start",83            "status": 200,84            "headers": [[b"content-type", b"text/plain"]],85        }86    )87    await send({"type": "http.response.body", "body": b"Hello, world!"})888990async def hello_world_json(scope: Scope, receive: Receive, send: Send) -> None:91    await send(92        {93            "type": "http.response.start",94            "status": 200,95            "headers": [[b"content-type", b"application/json"]],96        }97    )98    await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'})99100101async def slow_response(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 sleep(1.0)  # Allow triggering a read timeout.110    await send({"type": "http.response.body", "body": b"Hello, world!"})111112113async def status_code(scope: Scope, receive: Receive, send: Send) -> None:114    status_code = int(scope["path"].replace("/status/", ""))115    await send(116        {117            "type": "http.response.start",118            "status": status_code,119            "headers": [[b"content-type", b"text/plain"]],120        }121    )122    await send({"type": "http.response.body", "body": b"Hello, world!"})123124125async def echo_body(scope: Scope, receive: Receive, send: Send) -> None:126    body = b""127    more_body = True128129    while more_body:130        message = await receive()131        body += message.get("body", b"")132        more_body = message.get("more_body", False)133134    await send(135        {136            "type": "http.response.start",137            "status": 200,138            "headers": [[b"content-type", b"text/plain"]],139        }140    )141    await send({"type": "http.response.body", "body": body})142143144async def echo_binary(scope: Scope, receive: Receive, send: Send) -> None:145    body = b""146    more_body = True147148    while more_body:149        message = await receive()150        body += message.get("body", b"")151        more_body = message.get("more_body", False)152153    await send(154        {155            "type": "http.response.start",156            "status": 200,157            "headers": [[b"content-type", b"application/octet-stream"]],158        }159    )160    await send({"type": "http.response.body", "body": body})161162163async def echo_headers(scope: Scope, receive: Receive, send: Send) -> None:164    body = {165        name.capitalize().decode(): value.decode()166        for name, value in scope.get("headers", [])167    }168    await send(169        {170            "type": "http.response.start",171            "status": 200,172            "headers": [[b"content-type", b"application/json"]],173        }174    )175    await send({"type": "http.response.body", "body": json.dumps(body).encode()})176177178async def redirect_301(scope: Scope, receive: Receive, send: Send) -> None:179    await send(180        {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}181    )182    await send({"type": "http.response.body"})183184185@pytest.fixture(scope="session")186def cert_authority():187    return trustme.CA()188189190@pytest.fixture(scope="session")191def localhost_cert(cert_authority):192    return cert_authority.issue_cert("localhost")193194195@pytest.fixture(scope="session")196def cert_pem_file(localhost_cert):197    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:198        yield tmp199200201@pytest.fixture(scope="session")202def cert_private_key_file(localhost_cert):203    with localhost_cert.private_key_pem.tempfile() as tmp:204        yield tmp205206207@pytest.fixture(scope="session")208def cert_encrypted_private_key_file(localhost_cert):209    # Deserialize the private key and then reserialize with a password210    private_key = load_pem_private_key(211        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()212    )213    encrypted_private_key_pem = trustme.Blob(214        private_key.private_bytes(215            Encoding.PEM,216            PrivateFormat.TraditionalOpenSSL,217            BestAvailableEncryption(password=b"password"),218        )219    )220    with encrypted_private_key_pem.tempfile() as tmp:221        yield tmp222223224class TestServer(Server):225    @property226    def url(self) -> httpx.URL:227        protocol = "https" if self.config.is_ssl else "http"228        return httpx.URL(f"{protocol}://{self.config.host}:{self.config.port}/")229230    def install_signal_handlers(self) -> None:231        # Disable the default installation of handlers for signals such as SIGTERM,232        # because it can only be done in the main thread.233        pass  # pragma: nocover234235    async def serve(self, sockets=None):236        self.restart_requested = asyncio.Event()237238        loop = asyncio.get_event_loop()239        tasks = {240            loop.create_task(super().serve(sockets=sockets)),241            loop.create_task(self.watch_restarts()),242        }243        await asyncio.wait(tasks)244245    async def restart(self) -> None:  # pragma: no cover246        # This coroutine may be called from a different thread than the one the247        # server is running on, and from an async environment that's not asyncio.248        # For this reason, we use an event to coordinate with the server249        # instead of calling shutdown()/startup() directly, and should not make250        # any asyncio-specific operations.251        self.started = False252        self.restart_requested.set()253        while not self.started:254            await sleep(0.2)255256    async def watch_restarts(self) -> None:  # pragma: no cover257        while True:258            if self.should_exit:259                return260261            try:262                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)263            except asyncio.TimeoutError:264                continue265266            self.restart_requested.clear()267            await self.shutdown()268            await self.startup()269270271def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:272    thread = threading.Thread(target=server.run)273    thread.start()274    try:275        while not server.started:276            time.sleep(1e-3)277        yield server278    finally:279        server.should_exit = True280        thread.join()281282283@pytest.fixture(scope="session")284def server() -> typing.Iterator[TestServer]:285    config = Config(app=app, lifespan="off", loop="asyncio")286    server = TestServer(config=config)287    yield from serve_in_thread(server)