Python / FastAPI Basics Interview Questions
How do you test async FastAPI endpoints and async dependencies?
Use httpx.AsyncClient with ASGITransport for async tests, and pytest-asyncio to run async test functions. Combine with app.dependency_overrides to mock async dependencies.
# pip install pytest pytest-asyncio httpx # conftest.py import pytest from httpx import AsyncClient, ASGITransport from app.main import app, get_db from app.database import AsyncSessionLocal, Base, engine @pytest.fixture(scope="function") async def async_client(): # Use a test database async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async def override_db(): async with AsyncSessionLocal() as session: yield session app.dependency_overrides[get_db] = override_db async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test", ) as client: yield client app.dependency_overrides.clear() async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all)
# tests/test_users.py import pytest @pytest.mark.asyncio async def test_create_user(async_client): response = await async_client.post( "/users", json={"username": "alice", "email": "alice@example.com"}, ) assert response.status_code == 201 data = response.json() assert data["username"] == "alice" assert "password" not in data # response_model excludes it @pytest.mark.asyncio async def test_list_users_empty(async_client): response = await async_client.get("/users") assert response.status_code == 200 assert response.json() == [] @pytest.mark.asyncio async def test_validation_error(async_client): response = await async_client.post("/users", json={"username": "ab"}) # too short assert response.status_code == 422 errors = response.json()["detail"] assert any("username" in str(e) for e in errors)
# pytest.ini [pytest] asyncio_mode = auto # or use @pytest.mark.asyncio on each test
More Related questions...