Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

307 lines · 8.9 KiB · Python

Last changed by

Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d

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 ca_cert_pem_file(cert_authority):192    with cert_authority.cert_pem.tempfile() as tmp:193        yield tmp194195196@pytest.fixture(scope="session")197def localhost_cert(cert_authority):198    return cert_authority.issue_cert("localhost")199200201@pytest.fixture(scope="session")202def cert_pem_file(localhost_cert):203    with localhost_cert.cert_chain_pems[0].tempfile() as tmp:204        yield tmp205206207@pytest.fixture(scope="session")208def cert_private_key_file(localhost_cert):209    with localhost_cert.private_key_pem.tempfile() as tmp:210        yield tmp211212213@pytest.fixture(scope="session")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) -> httpx.URL:233        protocol = "https" if self.config.is_ssl else "http"234        return httpx.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: no cover252        # 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) -> None:  # pragma: no cover263        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: TestServer) -> typing.Iterator[TestServer]: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="session")290def server() -> typing.Iterator[TestServer]: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="session")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)