Python / FastAPI 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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
