Choose the appropriate testing approach based on your test requirements. For standard API endpoint testing, use `TestClient` with regular functions. For tests requiring async operations (like database queries), use `AsyncClient` with proper async test configuration.
Choose the appropriate testing approach based on your test requirements. For standard API endpoint testing, use TestClient
with regular functions. For tests requiring async operations (like database queries), use AsyncClient
with proper async test configuration.
For synchronous tests:
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}
For asynchronous tests:
import pytest
import httpx
from app.main import app
@pytest.mark.anyio
async def test_async_operations():
async with httpx.AsyncClient(app=app, base_url="http://test") as client:
response = await client.get("/")
assert response.status_code == 200
# Now you can use other async operations
# await database.fetch_one("SELECT * FROM items")
Remember that async tests require additional setup:
pytest-anyio
or pytest-asyncio
)async def
for the test functionAsyncClient
instead of TestClient
This approach ensures your tests can properly interact with both your FastAPI application and any external asynchronous dependencies without blocking or creating concurrency issues.
Enter the URL of a public GitHub repository