3 Hours

19. API Testing with Pytest

Quality Assurance

Testing is not optional in professional engineering. Automated tests ensure your API works correctly, prevent regressions, and serve as living documentation. Pytest is the most popular testing framework for Python, and FastAPI provides TestClient for easy API testing. To test these examples, install pytest and run pytest in your terminal.

Setting Up Pytest

Bash
pip install pytest pytest-asyncio httpx
Python 3
# tests/test_main.py
from fastapi.testclient import TestClient
from app.main import app

client = TestClient(app)

def test_read_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello World"}

def test_get_user():
    response = client.get("/users/1")
    assert response.status_code == 200
    assert response.json()["id"] == 1

def test_create_user():
    user_data = {"email": "test@example.com", "name": "Test User"}
    response = client.post("/users", json=user_data)
    assert response.status_code == 201
    assert response.json()["email"] == "test@example.com"

def test_not_found():
    response = client.get("/users/99999")
    assert response.status_code == 404
    assert "not found" in response.json()["detail"].lower()

Testing with Database

Use a test database to avoid affecting development data.

Python 3
# tests/conftest.py
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.database import Base, get_db
from app.main import app

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

@pytest.fixture
def db_session():
    Base.metadata.create_all(bind=engine)
    db = TestingSessionLocal()
    try:
        yield db
    finally:
        db.close()
    Base.metadata.drop_all(bind=engine)

@pytest.fixture
def client(db_session):
    def override_get_db():
        try:
            yield db_session
        finally:
            pass

    app.dependency_overrides[get_db] = override_get_db
    with TestClient(app) as test_client:
        yield test_client
    app.dependency_overrides.clear()

# tests/test_users.py
def test_create_user(client):
    response = client.post("/users", json={"email": "test@test.com", "name": "Tester"})
    assert response.status_code == 201

def test_get_users(client):
    response = client.get("/users")
    assert response.status_code == 200
    assert isinstance(response.json(), list)

Testing Authentication

Python 3
def test_login(client):
    client.post("/users", json={"email": "auth@test.com", "password": "secret123"})

    response = client.post("/token", data={"username": "auth@test.com", "password": "secret123"})
    assert response.status_code == 200
    assert "access_token" in response.json()

    token = response.json()["access_token"]

    protected_response = client.get("/users/me", headers={"Authorization": f"Bearer {token}"})
    assert protected_response.status_code == 200

def test_protected_route_no_token(client):
    response = client.get("/users/me")
    assert response.status_code == 401

Testing Async Endpoints

Python 3
import pytest
from httpx import AsyncClient
from app.main import app

@pytest.mark.asyncio
async def test_async_endpoint():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/async-data")
    assert response.status_code == 200

@pytest.mark.asyncio
async def test_websocket():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        async with ac.websocket_connect("/ws/test") as websocket:
            await websocket.send_text("Hello")
            response = await websocket.receive_text()
            assert response == "Server received: Hello"

Parametrized Tests

Test multiple cases with a single test function using parametrize.

Python 3
import pytest

@pytest.mark.parametrize("user_id,expected_status", [
    (1, 200),
    (2, 200),
    (999, 404),
    (-1, 422),
])
def test_get_user_by_id(client, user_id, expected_status):
    response = client.get(f"/users/{user_id}")
    assert response.status_code == expected_status

@pytest.mark.parametrize("email,password,expected_status", [
    ("valid@test.com", "pass123", 200),
    ("invalid", "pass123", 422),
    ("valid@test.com", "wrong", 401),
    ("", "pass123", 422),
])
def test_login_variations(client, email, password, expected_status):
    response = client.post("/token", data={"username": email, "password": password})
    assert response.status_code == expected_status

Mocking External Dependencies

Use pytest-mock to mock external services like email providers.

Python 3
def test_send_email(mocker):
    mock_send = mocker.patch("app.services.email.send_email")
    mock_send.return_value = {"status": "sent"}

    response = client.post("/send-email", json={"to": "test@test.com", "subject": "Hello"})

    assert response.status_code == 200
    mock_send.assert_called_once()
    mock_send.assert_called_with(to="test@test.com", subject="Hello")
Local Testing: Run pytest -v to see all tests run. Add --cov=app to see coverage reports.

Knowledge Check

Ready to test your understanding of 19. API Testing with Pytest?

Back