Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

88 lines · 2.3 KiB · Python

Last changed by

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

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.fixture55async def server():56    config = Config(app=app, lifespan="off")57    server = Server(config=config)58    task = asyncio.ensure_future(server.serve())59    try:60        while not server.started:61            await asyncio.sleep(0.0001)62        yield server63    finally:64        server.should_exit = True65        await task666768@pytest.fixture69async def https_server():70    ca = trustme.CA()71    server_cert = ca.issue_cert("example.org")72    with ca.cert_pem.tempfile() as cert_temp_path, ca.private_key_pem.tempfile() as key_temp_path:73        config = Config(74            app=app,75            lifespan="off",76            ssl_certfile=cert_temp_path,77            ssl_keyfile=key_temp_path,78            port=8001,79        )80    server = Server(config=config)81    task = asyncio.ensure_future(server.serve())82    try:83        while not server.started:84            await asyncio.sleep(0.0001)85        yield server86    finally:87        server.should_exit = True88        await task