Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

289 lines · 7.9 KiB · Python

Last changed by

Inline SERVER_SCOPE and remove typing_extensions requirement (#1773)Michał Górnybefore adoption8c64e0c

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():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("/status"):80        await status_code(scope, receive, send)81    elif scope["path"].startswith("/echo_body"):82        await echo_body(scope, receive, send)83    elif scope["path"].startswith("/echo_headers"):84        await echo_headers(scope, receive, send)85    elif scope["path"].startswith("/redirect_301"):86        await redirect_301(scope, receive, send)87    else:88        await hello_world(scope, receive, send)899091async def hello_world(scope, receive, send):92    await send(93        {94            "type": "http.response.start",95            "status": 200,96            "headers": [[b"content-type", b"text/plain"]],97        }98    )99    await send({"type": "http.response.body", "body": b"Hello, world!"})100101102async def slow_response(scope, receive, send):103    await sleep(1.0)104    await send(105        {106            "type": "http.response.start",107            "status": 200,108            "headers": [[b"content-type", b"text/plain"]],109        }110    )111    await send({"type": "http.response.body", "body": b"Hello, world!"})112113114async def status_code(scope, receive, send):115    status_code = int(scope["path"].replace("/status/", ""))116    await send(117        {118            "type": "http.response.start",119            "status": status_code,120            "headers": [[b"content-type", b"text/plain"]],121        }122    )123    await send({"type": "http.response.body", "body": b"Hello, world!"})124125126async def echo_body(scope, receive, send):127    body = b""128    more_body = True129130    while more_body:131        message = await receive()132        body += message.get("body", b"")133        more_body = message.get("more_body", False)134135    await send(136        {137            "type": "http.response.start",138            "status": 200,139            "headers": [[b"content-type", b"text/plain"]],140        }141    )142    await send({"type": "http.response.body", "body": body})143144145async def echo_headers(scope, receive, send):146    body = {147        name.capitalize().decode(): value.decode()148        for name, value in scope.get("headers", [])149    }150    await send(151        {152            "type": "http.response.start",153            "status": 200,154            "headers": [[b"content-type", b"application/json"]],155        }156    )157    await send({"type": "http.response.body", "body": json.dumps(body).encode()})158159160async def redirect_301(scope, receive, send):161    await send(162        {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}163    )164    await send({"type": "http.response.body"})165166167@pytest.fixture(scope="session")168def cert_authority():169    return trustme.CA()170171172@pytest.fixture(scope="session")173def ca_cert_pem_file(cert_authority):174    with cert_authority.cert_pem.tempfile() as tmp:175        yield tmp176177178@pytest.fixture(scope="session")179def localhost_cert(cert_authority):180    return cert_authority.issue_cert("localhost")181182183@pytest.fixture(scope="session")184def cert_pem_file(localhost_cert):185    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:186        yield tmp187188189@pytest.fixture(scope="session")190def cert_private_key_file(localhost_cert):191    with localhost_cert.private_key_pem.tempfile() as tmp:192        yield tmp193194195@pytest.fixture(scope="session")196def cert_encrypted_private_key_file(localhost_cert):197    # Deserialize the private key and then reserialize with a password198    private_key = load_pem_private_key(199        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()200    )201    encrypted_private_key_pem = trustme.Blob(202        private_key.private_bytes(203            Encoding.PEM,204            PrivateFormat.TraditionalOpenSSL,205            BestAvailableEncryption(password=b"password"),206        )207    )208    with encrypted_private_key_pem.tempfile() as tmp:209        yield tmp210211212class TestServer(Server):213    @property214    def url(self) -> URL:215        protocol = "https" if self.config.is_ssl else "http"216        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")217218    def install_signal_handlers(self) -> None:219        # Disable the default installation of handlers for signals such as SIGTERM,220        # because it can only be done in the main thread.221        pass222223    async def serve(self, sockets=None):224        self.restart_requested = asyncio.Event()225226        loop = asyncio.get_event_loop()227        tasks = {228            loop.create_task(super().serve(sockets=sockets)),229            loop.create_task(self.watch_restarts()),230        }231        await asyncio.wait(tasks)232233    async def restart(self) -> None:  # pragma: nocover234        # This coroutine may be called from a different thread than the one the235        # server is running on, and from an async environment that's not asyncio.236        # For this reason, we use an event to coordinate with the server237        # instead of calling shutdown()/startup() directly, and should not make238        # any asyncio-specific operations.239        self.started = False240        self.restart_requested.set()241        while not self.started:242            await sleep(0.2)243244    async def watch_restarts(self):  # pragma: nocover245        while True:246            if self.should_exit:247                return248249            try:250                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)251            except asyncio.TimeoutError:252                continue253254            self.restart_requested.clear()255            await self.shutdown()256            await self.startup()257258259def 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="session")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="session")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        port=8001,286        loop="asyncio",287    )288    server = TestServer(config=config)289    yield from serve_in_thread(server)