Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

293 lines 路 8.0 KiB 路 Python

Last changed by

馃懛 Add Python 3.10 beta to the CI (#1682)Marcelo Trylesinskibefore adoption3231211

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 typing_extensions import Literal18from uvicorn.config import Config19from uvicorn.main import Server2021from httpx import URL22from tests.concurrency import sleep2324ENVIRONMENT_VARIABLES = {25    "SSL_CERT_FILE",26    "SSL_CERT_DIR",27    "HTTP_PROXY",28    "HTTPS_PROXY",29    "ALL_PROXY",30    "NO_PROXY",31    "SSLKEYLOGFILE",32}333435@pytest.fixture(36    params=[37        pytest.param("asyncio", marks=pytest.mark.asyncio),38        pytest.param("trio", marks=pytest.mark.trio),39    ]40)41def async_environment(request: typing.Any) -> str:42    """43    Mark a test function to be run on both asyncio and trio.4445    Equivalent to having a pair of tests, each respectively marked with46    '@pytest.mark.asyncio' and '@pytest.mark.trio'.4748    Intended usage:4950    ```51    @pytest.mark.usefixtures("async_environment")52    async def my_async_test():53        ...54    ```55    """56    return request.param575859@pytest.fixture(scope="function", autouse=True)60def clean_environ():61    """Keeps os.environ clean for every test without having to mock os.environ"""62    original_environ = os.environ.copy()63    os.environ.clear()64    os.environ.update(65        {66            k: v67            for k, v in original_environ.items()68            if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES69        }70    )71    yield72    os.environ.clear()73    os.environ.update(original_environ)747576async def app(scope, receive, send):77    assert scope["type"] == "http"78    if scope["path"].startswith("/slow_response"):79        await slow_response(scope, receive, send)80    elif scope["path"].startswith("/status"):81        await status_code(scope, receive, send)82    elif scope["path"].startswith("/echo_body"):83        await echo_body(scope, receive, send)84    elif scope["path"].startswith("/echo_headers"):85        await echo_headers(scope, receive, send)86    elif scope["path"].startswith("/redirect_301"):87        await redirect_301(scope, receive, send)88    else:89        await hello_world(scope, receive, send)909192async def hello_world(scope, receive, send):93    await send(94        {95            "type": "http.response.start",96            "status": 200,97            "headers": [[b"content-type", b"text/plain"]],98        }99    )100    await send({"type": "http.response.body", "body": b"Hello, world!"})101102103async def slow_response(scope, receive, send):104    await sleep(1.0)105    await send(106        {107            "type": "http.response.start",108            "status": 200,109            "headers": [[b"content-type", b"text/plain"]],110        }111    )112    await send({"type": "http.response.body", "body": b"Hello, world!"})113114115async def status_code(scope, receive, send):116    status_code = int(scope["path"].replace("/status/", ""))117    await send(118        {119            "type": "http.response.start",120            "status": status_code,121            "headers": [[b"content-type", b"text/plain"]],122        }123    )124    await send({"type": "http.response.body", "body": b"Hello, world!"})125126127async def echo_body(scope, receive, send):128    body = b""129    more_body = True130131    while more_body:132        message = await receive()133        body += message.get("body", b"")134        more_body = message.get("more_body", False)135136    await send(137        {138            "type": "http.response.start",139            "status": 200,140            "headers": [[b"content-type", b"text/plain"]],141        }142    )143    await send({"type": "http.response.body", "body": body})144145146async def echo_headers(scope, receive, send):147    body = {}148    for name, value in scope.get("headers", []):149        body[name.capitalize().decode()] = value.decode()150151    await send(152        {153            "type": "http.response.start",154            "status": 200,155            "headers": [[b"content-type", b"application/json"]],156        }157    )158    await send({"type": "http.response.body", "body": json.dumps(body).encode()})159160161async def redirect_301(scope, receive, send):162    await send(163        {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}164    )165    await send({"type": "http.response.body"})166167168SERVER_SCOPE: Literal["session"] = "session"169170171@pytest.fixture(scope=SERVER_SCOPE)172def cert_authority():173    return trustme.CA()174175176@pytest.fixture(scope=SERVER_SCOPE)177def ca_cert_pem_file(cert_authority):178    with cert_authority.cert_pem.tempfile() as tmp:179        yield tmp180181182@pytest.fixture(scope=SERVER_SCOPE)183def localhost_cert(cert_authority):184    return cert_authority.issue_cert("localhost")185186187@pytest.fixture(scope=SERVER_SCOPE)188def cert_pem_file(localhost_cert):189    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:190        yield tmp191192193@pytest.fixture(scope=SERVER_SCOPE)194def cert_private_key_file(localhost_cert):195    with localhost_cert.private_key_pem.tempfile() as tmp:196        yield tmp197198199@pytest.fixture(scope=SERVER_SCOPE)200def cert_encrypted_private_key_file(localhost_cert):201    # Deserialize the private key and then reserialize with a password202    private_key = load_pem_private_key(203        localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()204    )205    encrypted_private_key_pem = trustme.Blob(206        private_key.private_bytes(207            Encoding.PEM,208            PrivateFormat.TraditionalOpenSSL,209            BestAvailableEncryption(password=b"password"),210        )211    )212    with encrypted_private_key_pem.tempfile() as tmp:213        yield tmp214215216class TestServer(Server):217    @property218    def url(self) -> URL:219        protocol = "https" if self.config.is_ssl else "http"220        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")221222    def install_signal_handlers(self) -> None:223        # Disable the default installation of handlers for signals such as SIGTERM,224        # because it can only be done in the main thread.225        pass226227    async def serve(self, sockets=None):228        self.restart_requested = asyncio.Event()229230        loop = asyncio.get_event_loop()231        tasks = {232            loop.create_task(super().serve(sockets=sockets)),233            loop.create_task(self.watch_restarts()),234        }235        await asyncio.wait(tasks)236237    async def restart(self) -> None:  # pragma: nocover238        # This coroutine may be called from a different thread than the one the239        # server is running on, and from an async environment that's not asyncio.240        # For this reason, we use an event to coordinate with the server241        # instead of calling shutdown()/startup() directly, and should not make242        # any asyncio-specific operations.243        self.started = False244        self.restart_requested.set()245        while not self.started:246            await sleep(0.2)247248    async def watch_restarts(self):  # pragma: nocover249        while True:250            if self.should_exit:251                return252253            try:254                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)255            except asyncio.TimeoutError:256                continue257258            self.restart_requested.clear()259            await self.shutdown()260            await self.startup()261262263def serve_in_thread(server: Server):264    thread = threading.Thread(target=server.run)265    thread.start()266    try:267        while not server.started:268            time.sleep(1e-3)269        yield server270    finally:271        server.should_exit = True272        thread.join()273274275@pytest.fixture(scope=SERVER_SCOPE)276def server():277    config = Config(app=app, lifespan="off", loop="asyncio")278    server = TestServer(config=config)279    yield from serve_in_thread(server)280281282@pytest.fixture(scope=SERVER_SCOPE)283def https_server(cert_pem_file, cert_private_key_file):284    config = Config(285        app=app,286        lifespan="off",287        ssl_certfile=cert_pem_file,288        ssl_keyfile=cert_private_key_file,289        port=8001,290        loop="asyncio",291    )292    server = TestServer(config=config)293    yield from serve_in_thread(server)