Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

302 lines · 8.3 KiB · Python

Last changed by

Add cli support (#1855)Tom Christiebefore adoptionee9250d

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    elif scope["path"].startswith("/json"):88        await hello_world_json(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 hello_world_json(scope, receive, send):105    await send(106        {107            "type": "http.response.start",108            "status": 200,109            "headers": [[b"content-type", b"application/json"]],110        }111    )112    await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'})113114115async def slow_response(scope, receive, send):116    await sleep(1.0)117    await send(118        {119            "type": "http.response.start",120            "status": 200,121            "headers": [[b"content-type", b"text/plain"]],122        }123    )124    await send({"type": "http.response.body", "body": b"Hello, world!"})125126127async def status_code(scope, receive, send):128    status_code = int(scope["path"].replace("/status/", ""))129    await send(130        {131            "type": "http.response.start",132            "status": status_code,133            "headers": [[b"content-type", b"text/plain"]],134        }135    )136    await send({"type": "http.response.body", "body": b"Hello, world!"})137138139async def echo_body(scope, receive, send):140    body = b""141    more_body = True142143    while more_body:144        message = await receive()145        body += message.get("body", b"")146        more_body = message.get("more_body", False)147148    await send(149        {150            "type": "http.response.start",151            "status": 200,152            "headers": [[b"content-type", b"text/plain"]],153        }154    )155    await send({"type": "http.response.body", "body": body})156157158async def echo_headers(scope, receive, send):159    body = {160        name.capitalize().decode(): value.decode()161        for name, value in scope.get("headers", [])162    }163    await send(164        {165            "type": "http.response.start",166            "status": 200,167            "headers": [[b"content-type", b"application/json"]],168        }169    )170    await send({"type": "http.response.body", "body": json.dumps(body).encode()})171172173async def redirect_301(scope, receive, send):174    await send(175        {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}176    )177    await send({"type": "http.response.body"})178179180@pytest.fixture(scope="session")181def cert_authority():182    return trustme.CA()183184185@pytest.fixture(scope="session")186def ca_cert_pem_file(cert_authority):187    with cert_authority.cert_pem.tempfile() as tmp:188        yield tmp189190191@pytest.fixture(scope="session")192def localhost_cert(cert_authority):193    return cert_authority.issue_cert("localhost")194195196@pytest.fixture(scope="session")197def cert_pem_file(localhost_cert):198    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:199        yield tmp200201202@pytest.fixture(scope="session")203def cert_private_key_file(localhost_cert):204    with localhost_cert.private_key_pem.tempfile() as tmp:205        yield tmp206207208@pytest.fixture(scope="session")209def cert_encrypted_private_key_file(localhost_cert):210    # Deserialize the private key and then reserialize with a password211    private_key = load_pem_private_key(212        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()213    )214    encrypted_private_key_pem = trustme.Blob(215        private_key.private_bytes(216            Encoding.PEM,217            PrivateFormat.TraditionalOpenSSL,218            BestAvailableEncryption(password=b"password"),219        )220    )221    with encrypted_private_key_pem.tempfile() as tmp:222        yield tmp223224225class TestServer(Server):226    @property227    def url(self) -> URL:228        protocol = "https" if self.config.is_ssl else "http"229        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")230231    def install_signal_handlers(self) -> None:232        # Disable the default installation of handlers for signals such as SIGTERM,233        # because it can only be done in the main thread.234        pass235236    async def serve(self, sockets=None):237        self.restart_requested = asyncio.Event()238239        loop = asyncio.get_event_loop()240        tasks = {241            loop.create_task(super().serve(sockets=sockets)),242            loop.create_task(self.watch_restarts()),243        }244        await asyncio.wait(tasks)245246    async def restart(self) -> None:  # pragma: nocover247        # This coroutine may be called from a different thread than the one the248        # server is running on, and from an async environment that's not asyncio.249        # For this reason, we use an event to coordinate with the server250        # instead of calling shutdown()/startup() directly, and should not make251        # any asyncio-specific operations.252        self.started = False253        self.restart_requested.set()254        while not self.started:255            await sleep(0.2)256257    async def watch_restarts(self):  # pragma: nocover258        while True:259            if self.should_exit:260                return261262            try:263                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)264            except asyncio.TimeoutError:265                continue266267            self.restart_requested.clear()268            await self.shutdown()269            await self.startup()270271272def serve_in_thread(server: Server):273    thread = threading.Thread(target=server.run)274    thread.start()275    try:276        while not server.started:277            time.sleep(1e-3)278        yield server279    finally:280        server.should_exit = True281        thread.join()282283284@pytest.fixture(scope="session")285def server():286    config = Config(app=app, lifespan="off", loop="asyncio")287    server = TestServer(config=config)288    yield from serve_in_thread(server)289290291@pytest.fixture(scope="session")292def https_server(cert_pem_file, cert_private_key_file):293    config = Config(294        app=app,295        lifespan="off",296        ssl_certfile=cert_pem_file,297        ssl_keyfile=cert_private_key_file,298        port=8001,299        loop="asyncio",300    )301    server = TestServer(config=config)302    yield from serve_in_thread(server)