Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

267 lines · 7.1 KiB · Python

Last changed by

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

History of this file

Take it

1import asyncio2import json3import os4import threading5import time6import typing78import pytest9import trustme10from cryptography.hazmat.primitives.serialization import (11    BestAvailableEncryption,12    Encoding,13    PrivateFormat,14)15from uvicorn.config import Config16from uvicorn.main import Server1718from httpx import URL, AsyncioBackend1920ENVIRONMENT_VARIABLES = (21    "SSL_CERT_FILE",22    "REQUESTS_CA_BUNDLE",23    "CURL_CA_BUNDLE",24    "HTTP_PROXY",25    "HTTPS_PROXY",26    "ALL_PROXY",27    "NO_PROXY",28    "SSLKEYLOGFILE",29)303132@pytest.fixture(scope="function", autouse=True)33def clean_environ() -> typing.Dict[str, typing.Any]:34    """Keeps os.environ clean for every test without having to mock os.environ"""35    original_environ = os.environ.copy()36    for key in ENVIRONMENT_VARIABLES:37        os.environ.pop(key, None)38    yield39    os.environ.clear()40    os.environ.update(original_environ)414243@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])44def backend(request):45    backend_cls = request.param46    return backend_cls()474849async def app(scope, receive, send):50    assert scope["type"] == "http"51    if scope["path"] == "/slow_response":52        await slow_response(scope, receive, send)53    elif scope["path"].startswith("/status"):54        await status_code(scope, receive, send)55    elif scope["path"].startswith("/echo_body"):56        await echo_body(scope, receive, send)57    elif scope["path"].startswith("/echo_headers"):58        await echo_headers(scope, receive, send)59    else:60        await hello_world(scope, receive, send)616263async def hello_world(scope, receive, send):64    await send(65        {66            "type": "http.response.start",67            "status": 200,68            "headers": [[b"content-type", b"text/plain"]],69        }70    )71    await send({"type": "http.response.body", "body": b"Hello, world!"})727374async def slow_response(scope, receive, send):75    await asyncio.sleep(0.1)76    await send(77        {78            "type": "http.response.start",79            "status": 200,80            "headers": [[b"content-type", b"text/plain"]],81        }82    )83    await send({"type": "http.response.body", "body": b"Hello, world!"})848586async def status_code(scope, receive, send):87    status_code = int(scope["path"].replace("/status/", ""))88    await send(89        {90            "type": "http.response.start",91            "status": status_code,92            "headers": [[b"content-type", b"text/plain"]],93        }94    )95    await send({"type": "http.response.body", "body": b"Hello, world!"})969798async def echo_body(scope, receive, send):99    body = b""100    more_body = True101102    while more_body:103        message = await receive()104        body += message.get("body", b"")105        more_body = message.get("more_body", False)106107    await send(108        {109            "type": "http.response.start",110            "status": 200,111            "headers": [[b"content-type", b"text/plain"]],112        }113    )114    await send({"type": "http.response.body", "body": body})115116117async def echo_headers(scope, receive, send):118    body = {}119    for name, value in scope.get("headers", []):120        body[name.capitalize().decode()] = value.decode()121122    await send(123        {124            "type": "http.response.start",125            "status": 200,126            "headers": [[b"content-type", b"application/json"]],127        }128    )129    await send({"type": "http.response.body", "body": json.dumps(body).encode()})130131132class CAWithPKEncryption(trustme.CA):133    """Implementation of trustme.CA() that can emit134    private keys that are encrypted with a password.135    """136137    @property138    def encrypted_private_key_pem(self):139        return trustme.Blob(140            self._private_key.private_bytes(141                Encoding.PEM,142                PrivateFormat.TraditionalOpenSSL,143                BestAvailableEncryption(password=b"password"),144            )145        )146147148SERVER_SCOPE = "session"149150151@pytest.fixture(scope=SERVER_SCOPE)152def example_cert():153    ca = CAWithPKEncryption()154    ca.issue_cert("example.org")155    return ca156157158@pytest.fixture(scope=SERVER_SCOPE)159def cert_pem_file(example_cert):160    with example_cert.cert_pem.tempfile() as tmp:161        yield tmp162163164@pytest.fixture(scope=SERVER_SCOPE)165def cert_private_key_file(example_cert):166    with example_cert.private_key_pem.tempfile() as tmp:167        yield tmp168169170@pytest.fixture(scope=SERVER_SCOPE)171def cert_encrypted_private_key_file(example_cert):172    with example_cert.encrypted_private_key_pem.tempfile() as tmp:173        yield tmp174175176class TestServer(Server):177    @property178    def url(self) -> URL:179        protocol = "https" if self.config.is_ssl else "http"180        return URL(f"{protocol}://{self.config.host}:{self.config.port}/")181182    def install_signal_handlers(self) -> None:183        # Disable the default installation of handlers for signals such as SIGTERM,184        # because it can only be done in the main thread.185        pass186187    async def serve(self, sockets=None):188        self.restart_requested = asyncio.Event()189190        loop = asyncio.get_event_loop()191        tasks = {192            loop.create_task(super().serve(sockets=sockets)),193            loop.create_task(self.watch_restarts()),194        }195        await asyncio.wait(tasks)196197    async def restart(self) -> None:198        # Ensure we are in an asyncio environment.199        assert asyncio.get_event_loop() is not None200        # This may be called from a different thread than the one the server is201        # running on. For this reason, we use an event to coordinate with the server202        # instead of calling shutdown()/startup() directly.203        self.restart_requested.set()204        self.started = False205        while not self.started:206            await asyncio.sleep(0.5)207208    async def watch_restarts(self):209        while True:210            if self.should_exit:211                return212213            try:214                await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)215            except asyncio.TimeoutError:216                continue217218            self.restart_requested.clear()219            await self.shutdown()220            await self.startup()221222223@pytest.fixture224def restart(backend):225    """Restart the running server from an async test function.226227    This fixture deals with possible differences between the environment of the228    test function and that of the server.229    """230231    async def restart(server):232        await backend.run_in_threadpool(AsyncioBackend().run, server.restart)233234    return restart235236237def serve_in_thread(server: Server):238    thread = threading.Thread(target=server.run)239    thread.start()240    try:241        while not server.started:242            time.sleep(1e-3)243        yield server244    finally:245        server.should_exit = True246        thread.join()247248249@pytest.fixture(scope=SERVER_SCOPE)250def server():251    config = Config(app=app, lifespan="off", loop="asyncio")252    server = TestServer(config=config)253    yield from serve_in_thread(server)254255256@pytest.fixture(scope=SERVER_SCOPE)257def https_server(cert_pem_file, cert_private_key_file):258    config = Config(259        app=app,260        lifespan="off",261        ssl_certfile=cert_pem_file,262        ssl_keyfile=cert_private_key_file,263        port=8001,264        loop="asyncio",265    )266    server = TestServer(config=config)267    yield from serve_in_thread(server)