Testing¶
Install and import¶
- Talks to
appdirectly, in-process, overhttpx.ASGITransport— no socket, no running server, nouvicorn.base_urldefaults to"http://test"; override it if a controller cares about the host (absolute-URL generation,Hostheader checks, ...).
A pytest fixture¶
conftest.py
from httpx import AsyncClient
from typing import AsyncGenerator
import pytest_asyncio
from heavyswag import run_test
from my_service.delivery import app # HeavySwag app
@pytest_asyncio.fixture
async def client() -> AsyncGenerator[AsyncClient]:
async with run_test(app) as test_client:
yield test_client
Testing the CRUD example¶
Against the users_router from A typical CRUD,
wired into app in main.py:
test_users.py
@pytest.mark.asyncio
async def test_create_then_get_user(client: AsyncClient) -> None:
response = await client.post(
"/users",
json={"username": "pistachio17.2", "email": "pistachio@example.com"},
)
assert response.status_code == 201
user_id = response.text # the CRUD example returns the id as-is
check_response = await client.get(f"/users/{user_id}")
assert check_response.status_code == 200
assert "pistachio17.2" in check_response.text
@pytest.mark.asyncio
async def test_get_missing_user_returns_404(client: AsyncClient) -> None:
response = await client.get("/users/00000000-0000-0000-0000-000000000000")
assert response.status_code == 404
Fresh state per test
Monitor the state of your data to avoid unexpected behavior.