Test endpoints with TestClient, override dependencies with app.dependency_overrides.
Testing FastAPI
from fastapi.testclient import TestClient
import pytest
@pytest.fixture
def client():
from main import app
with TestClient(app) as c:
yield c
@pytest.fixture
def auth_client(client):
resp = client.post("/auth/token", data={"username":"test@test.com","password":"pass"})
token = resp.json()["access_token"]
client.headers.update({"Authorization": "Bearer " + token})
return client
def test_get_users(client):
resp = client.get("/users")
assert resp.status_code == 200
assert isinstance(resp.json(), list)
def test_create_user(auth_client):
resp = auth_client.post("/users", json={"name":"Alice","email":"alice@test.com","password":"Secret1!"})
assert resp.status_code == 201
data = resp.json()
assert data["email"] == "alice@test.com"
assert "password" not in data # never expose passwords
def test_get_nonexistent_user(client):
resp = client.get("/users/99999")
assert resp.status_code == 404