Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

307 lines · 8.4 KiB · Python

Last changed by

Drop unecessary host="localhost" in https_server fixture to fix CI build (#1367)Florimond Mancabefore adoption2f54548

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("/slow_stream_response"):80        await slow_stream_response(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 slow_stream_response(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    )124125    await sleep(1)126    await send({"type": "http.response.body", "body": b"", "more_body": False})127128129async def status_code(scope, receive, send):130    status_code = int(scope["path"].replace("/status/", ""))131    await send(132        {133            "type": "http.response.start",134            "status": status_code,135            "headers": [[b"content-type", b"text/plain"]],136        }137    )138    await send({"type": "http.response.body", "body": b"Hello, world!"})139140141async def echo_body(scope, receive, send):142    body = b""143    more_body = True144145    while more_body:146        message = await receive()147        body += message.get("body", b"")148        more_body = message.get("more_body", False)149150    await send(151        {152            "type": "http.response.start",153            "status": 200,154            "headers": [[b"content-type", b"text/plain"]],155        }156    )157    await send({"type": "http.response.body", "body": body})158159160async def echo_headers(scope, receive, send):161    body = {}162    for name, value in scope.get("headers", []):163        body[name.capitalize().decode()] = value.decode()164165    await send(166        {167            "type": "http.response.start",168            "status": 200,169            "headers": [[b"content-type", b"application/json"]],170        }171    )172    await send({"type": "http.response.body", "body": json.dumps(body).encode()})173174175async def redirect_301(scope, receive, send):176    await send(177        {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}178    )179    await send({"type": "http.response.body"})180181182SERVER_SCOPE = "session"183184185@pytest.fixture(scope=SERVER_SCOPE)186def cert_authority():187    return trustme.CA()188189190@pytest.fixture(scope=SERVER_SCOPE)191def ca_cert_pem_file(cert_authority):192    with cert_authority.cert_pem.tempfile() as tmp:193        yield tmp194195196@pytest.fixture(scope=SERVER_SCOPE)197def localhost_cert(cert_authority):198    return cert_authority.issue_cert("localhost")199200201@pytest.fixture(scope=SERVER_SCOPE)202def cert_pem_file(localhost_cert):203    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:204        yield tmp205206207@pytest.fixture(scope=SERVER_SCOPE)208def cert_private_key_file(localhost_cert):209    with localhost_cert.private_key_pem.tempfile() as tmp:210        yield tmp211212213@pytest.fixture(scope=SERVER_SCOPE)214def cert_encrypted_private_key_file(localhost_cert):215    # Deserialize the private key and then reserialize with a password216    private_key = load_pem_private_key(217        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()218    )219    encrypted_private_key_pem = trustme.Blob(220        private_key.private_bytes(221            Encoding.PEM,222            PrivateFormat.TraditionalOpenSSL,223            BestAvailableEncryption(password=b"password"),224        )225    )226    with encrypted_private_key_pem.tempfile() as tmp:227        yield tmp228229230class TestServer(Server):231    @property232    def url(self) -> URL:233        protocol = "https" if self.config.is_ssl else "http"234        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")235236    def install_signal_handlers(self) -> None:237        # Disable the default installation of handlers for signals such as SIGTERM,238        # because it can only be done in the main thread.239        pass240241    async def serve(self, sockets=None):242        self.restart_requested = asyncio.Event()243244        loop = asyncio.get_event_loop()245        tasks = {246            loop.create_task(super().serve(sockets=sockets)),247            loop.create_task(self.watch_restarts()),248        }249        await asyncio.wait(tasks)250251    async def restart(self) -> None:  # pragma: nocover252        # This coroutine may be called from a different thread than the one the253        # server is running on, and from an async environment that's not asyncio.254        # For this reason, we use an event to coordinate with the server255        # instead of calling shutdown()/startup() directly, and should not make256        # any asyncio-specific operations.257        self.started = False258        self.restart_requested.set()259        while not self.started:260            await sleep(0.2)261262    async def watch_restarts(self):  # pragma: nocover263        while True:264            if self.should_exit:265                return266267            try:268                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)269            except asyncio.TimeoutError:270                continue271272            self.restart_requested.clear()273            await self.shutdown()274            await self.startup()275276277def serve_in_thread(server: Server):278    thread = threading.Thread(target=server.run)279    thread.start()280    try:281        while not server.started:282            time.sleep(1e-3)283        yield server284    finally:285        server.should_exit = True286        thread.join()287288289@pytest.fixture(scope=SERVER_SCOPE)290def server():291    config = Config(app=app, lifespan="off", loop="asyncio")292    server = TestServer(config=config)293    yield from serve_in_thread(server)294295296@pytest.fixture(scope=SERVER_SCOPE)297def https_server(cert_pem_file, cert_private_key_file):298    config = Config(299        app=app,300        lifespan="off",301        ssl_certfile=cert_pem_file,302        ssl_keyfile=cert_private_key_file,303        port=8001,304        loop="asyncio",305    )306    server = TestServer(config=config)307    yield from serve_in_thread(server)