Python / FastAPI Basics Interview Questions
How do you write tests for a FastAPI application using pytest and TestClient?
FastAPI provides TestClient (wrapping httpx) for synchronous tests and AsyncClient for async tests. Dependencies can be overridden for testing to inject mocks instead of real databases or services.
# app/main.py from fastapi import FastAPI, Depends from pydantic import BaseModel app = FastAPI() def get_db(): return {"connection": "real_db"} class Item(BaseModel): name: str price: float @app.get("/") def root(): return {"message": "Hello"} @app.post("/items", status_code=201) def create_item(item: Item, db=Depends(get_db)): return {"created": item.name, "db": db["connection"]}
# tests/test_main.py import pytest from fastapi.testclient import TestClient from app.main import app, get_db # Override the real DB dependency with a mock def override_get_db(): return {"connection": "test_db"} app.dependency_overrides[get_db] = override_get_db client = TestClient(app) def test_root(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"message": "Hello"} def test_create_item(): response = client.post( "/items", json={"name": "Widget", "price": 9.99}, ) assert response.status_code == 201 data = response.json() assert data["created"] == "Widget" assert data["db"] == "test_db" # mock dependency used def test_create_item_invalid(): response = client.post("/items", json={"name": "Widget"}) # missing price assert response.status_code == 422 # validation error # Async test with httpx.AsyncClient import pytest from httpx import AsyncClient, ASGITransport @pytest.mark.asyncio async def test_root_async(): async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as ac: response = await ac.get("/") assert response.status_code == 200
More Related questions...