Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

89 lines · 2.3 KiB · Python

Last changed by

Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635

History of this file

Take it

1import asyncio2import os34import pytest5import trustme6from uvicorn.config import Config7from uvicorn.main import Server8910async def app(scope, receive, send):11    assert scope["type"] == "http"12    if scope["path"] == "/slow_response":13        await slow_response(scope, receive, send)14    elif scope["path"].startswith("/status"):15        await status_code(scope, receive, send)16    else:17        await hello_world(scope, receive, send)181920async def hello_world(scope, receive, send):21    await send(22        {23            "type": "http.response.start",24            "status": 200,25            "headers": [[b"content-type", b"text/plain"]],26        }27    )28    await send({"type": "http.response.body", "body": b"Hello, world!"})293031async def slow_response(scope, receive, send):32    await asyncio.sleep(0.01)33    await send(34        {35            "type": "http.response.start",36            "status": 200,37            "headers": [[b"content-type", b"text/plain"]],38        }39    )40    await send({"type": "http.response.body", "body": b"Hello, world!"})414243async def status_code(scope, receive, send):44    status_code = int(scope["path"].replace("/status/", ""))45    await send(46        {47            "type": "http.response.start",48            "status": status_code,49            "headers": [[b"content-type", b"text/plain"]],50        }51    )52    await send({"type": "http.response.body", "body": b"Hello, world!"})535455@pytest.fixture56async def server():57    config = Config(app=app, lifespan="off")58    server = Server(config=config)59    task = asyncio.ensure_future(server.serve())60    try:61        while not server.started:62            await asyncio.sleep(0.0001)63        yield server64    finally:65        server.should_exit = True66        await task676869@pytest.fixture70async def https_server():71    ca = trustme.CA()72    server_cert = ca.issue_cert("example.org")73    with ca.cert_pem.tempfile() as cert_temp_path, ca.private_key_pem.tempfile() as key_temp_path:74        config = Config(75            app=app,76            lifespan="off",77            ssl_certfile=cert_temp_path,78            ssl_keyfile=key_temp_path,79            port=8001,80        )81    server = Server(config=config)82    task = asyncio.ensure_future(server.serve())83    try:84        while not server.started:85            await asyncio.sleep(0.0001)86        yield server87    finally:88        server.should_exit = True89        await task