Skip to main content

Example FastAPI App (main.py)

from fastapi import FastAPI, HTTPException

app = FastAPI()

fake_db = {"alice": "Engineer", "bob": "Designer"}

@app.get("/users/{username}")
def get_user(username: str):
if username not in fake_db:
raise HTTPException(status_code=404, detail="User not found")
return {"username": username, "job": fake_db[username]}

@app.post("/users")
def create_user(username: str, job: str):
if username in fake_db:
raise HTTPException(status_code=400, detail="User already exists")
fake_db[username] = job
return {"message": "User created", "username": username}

Unit Tests (test_main.py)

Requires:

pip install pytest pytest-asyncio httpx fastapi

1. Import and Setup

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

2. Test GET endpoint

def test_get_existing_user():
response = client.get("/users/alice")
assert response.status_code == 200
data = response.json()
assert data["username"] == "alice"
assert data["job"] == "Engineer"


def test_get_missing_user():
response = client.get("/users/unknown")
assert response.status_code == 404
assert response.json() == {"detail": "User not found"}

3. Test POST endpoint

def test_create_new_user():
response = client.post("/users", params={"username": "charlie", "job": "Manager"})
assert response.status_code == 200
assert response.json()["message"] == "User created"
assert response.json()["username"] == "charlie"


def test_create_existing_user():
response = client.post("/users", params={"username": "alice", "job": "Engineer"})
assert response.status_code == 400
assert response.json() == {"detail": "User already exists"}

Running Tests

Run tests with:

pytest -v