Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

90 lines · 2.4 KiB · Python

Last changed by

Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8

History of this file

Take it

1import asyncio23import pytest4import trustme5from uvicorn.config import Config6from uvicorn.main import Server789async def app(scope, receive, send):10    assert scope["type"] == "http"11    if scope["path"] == "/slow_response":12        await slow_response(scope, receive, send)13    elif scope["path"].startswith("/status"):14        await status_code(scope, receive, send)15    else:16        await hello_world(scope, receive, send)171819async def hello_world(scope, receive, send):20    await send(21        {22            "type": "http.response.start",23            "status": 200,24            "headers": [[b"content-type", b"text/plain"]],25        }26    )27    await send({"type": "http.response.body", "body": b"Hello, world!"})282930async def slow_response(scope, receive, send):31    await asyncio.sleep(0.01)32    await send(33        {34            "type": "http.response.start",35            "status": 200,36            "headers": [[b"content-type", b"text/plain"]],37        }38    )39    await send({"type": "http.response.body", "body": b"Hello, world!"})404142async def status_code(scope, receive, send):43    status_code = int(scope["path"].replace("/status/", ""))44    await send(45        {46            "type": "http.response.start",47            "status": status_code,48            "headers": [[b"content-type", b"text/plain"]],49        }50    )51    await send({"type": "http.response.body", "body": b"Hello, world!"})525354@pytest.fixture55def cert_and_key_paths():56    ca = trustme.CA()57    ca.issue_cert("example.org")58    with ca.cert_pem.tempfile() as cert_temp_path, ca.private_key_pem.tempfile() as key_temp_path:59        yield cert_temp_path, key_temp_path606162@pytest.fixture63async def server():64    config = Config(app=app, lifespan="off")65    server = Server(config=config)66    task = asyncio.ensure_future(server.serve())67    try:68        while not server.started:69            await asyncio.sleep(0.0001)70        yield server71    finally:72        server.should_exit = True73        await task747576@pytest.fixture77async def https_server(cert_and_key_paths):78    cert_path, key_path = cert_and_key_paths79    config = Config(80        app=app, lifespan="off", ssl_certfile=cert_path, ssl_keyfile=key_path, port=800181    )82    server = Server(config=config)83    task = asyncio.ensure_future(server.serve())84    try:85        while not server.started:86            await asyncio.sleep(0.0001)87        yield server88    finally:89        server.should_exit = True90        await task