End-to-End API Tests with Factories
Build reliable test data with factories, exercise full HTTP request cycles with TestClient, and verify authentication, persistence, and ownership boundaries.
Contentsand lesson path
On this page
- Why it matters
- The problem with static JSON fixtures
- Building test data with factories
- End-to-end flows: sign-up, create, list, and permissions
- Check your understanding
- Apply it
- Review prompt
Lessons of API Integration & Contract Testing
- Why Mocks Lie About Databases Concept · 15 min
- Lab: A Disposable PostgreSQL for Every Test Run Lab · 30 min
- End-to-End API Tests with Factories Worked example · 25 min
- Contract Tests Generated from an OpenAPI Document Worked example · 25 min
- Fast, Deterministic, Not Flaky Concept · 15 min
- Check: Diagnose the Failing Suite Knowledge check · 8 questions
What you will learn
- Write end-to-end API tests that exercise authentication, persistence and error paths through the HTTP layer, building test data with factories.
Prerequisites: Software Testing Fundamentals, Data Access with SQLAlchemy
01. Why it matters
Testing internal services through direct Python function calls or repository methods proves only that individual functions work in isolation. Real users and frontend clients interact with your service across the HTTP boundary: sending serialised JSON payloads, passing bearer authentication headers, and expecting structured HTTP error status codes like 401 Unauthorized, 403 Forbidden, or 409 Conflict.
End-to-end API tests exercise the entire request lifecycle. A request enters FastAPI router middleware, executes dependency injection pipelines, validates schemas through Pydantic models, reads or writes through SQLAlchemy to PostgreSQL, and returns formatted JSON. To keep these tests expressive and maintainable, you need a disciplined strategy for generating test data without creating brittle dependencies on static database fixtures.
02. The problem with static JSON fixtures
Many engineering teams start testing by creating static JSON or SQL fixture files (such as seed_data.json or initial_users.sql). These files seed the database with dozens of predefined users, books, and permissions. They are convenient at first, but they become hard to maintain as the application evolves.
Static fixtures introduce three major failure modes:
- Invisible coupling. Test 12 relies on user ID 3 having an active subscription created in row 45 of
seed_data.json. If a developer later edits user 3 to test an expired subscription for Test 50, Test 12 suddenly breaks with no obvious link between the files. - Cluttered intent. When a test asserts that an admin can delete a reading list, reader comprehension suffers. Did the test pass because of the user's role, their account age, or their email domain? The test setup does not make the essential preconditions obvious.
- Rigid schema. Adding a single required non-null column (
email_verified: bool) requires updating hundreds of lines of static JSON across dozens of obsolete fixture files.
03. Building test data with factories
The factory pattern solves static fixture fragility by providing generator functions with sensible, valid defaults. A factory generates a complete, valid database entity using sequential or random values. The calling test specifies only the exact fields relevant to the specific scenario under test.
Here is the factory implementation for our reading list application in tests/factories.py:
import itertools
from sqlalchemy.orm import Session
from app.main import make_slug
from app.models import Book, User
from app.security import hash_password, hash_token, new_token
_user_seq = itertools.count(1)
_book_seq = itertools.count(1)
def make_user(
session: Session,
email: str | None = None,
password: str = "correct horse battery",
) -> User:
"""Build and persist a user; only a hash of the API token is stored."""
if email is None:
email = f"user{next(_user_seq)}@example.org"
raw_token = new_token()
user = User(email=email, password_hash=hash_password(password),
token_hash=hash_token(raw_token))
session.add(user)
session.flush()
user.raw_token = raw_token # test-only attribute, never written to the DB
return user
def make_book(
session: Session,
owner: User | None = None,
title: str | None = None,
year: int = 1999,
) -> Book:
"""Build and persist a book owned by the given user (or a new user)."""
if owner is None:
owner = make_user(session)
if title is None:
title = f"Book number {next(_book_seq)}"
book = Book(owner_id=owner.id, title=title, slug=make_slug(title), year=year)
session.add(book)
session.flush()
return bookThe reference app stores only token_hash, a SHA-256 hash of each API token, and looks tokens up by that hash, as the sessions and tokens lesson teaches. The factory keeps the raw token on a plain Python attribute so tests can build the header; no column holds a usable credential. If your copy of the sample app still has a plaintext token column, treat it as a teaching shortcut and change it, because a database leak would then hand out working credentials.
itertools.count(1) hands each call the next number, so default email addresses and book titles never repeat within one pytest run, with no random values that could collide. Each factory method calls session.flush() rather than session.commit(). This forces PostgreSQL to assign primary keys (user.id) and validate database constraints immediately while keeping all inserted rows inside the current test's rollback transaction boundary.
Factories also help when you build related rows. In make_book, if the caller does not supply an owner, the factory automatically invokes make_user(session) to build and persist an owning user on the fly. As your domain model grows to include categories, comments, reviews, and payment records, nested factories construct complete valid dependency graphs automatically. Individual tests specify only the attributes they are evaluating, which keeps repetitive set-up code out of them.
04. End-to-end flows: sign-up, create, list, and permissions
With factories in place, writing expressive end-to-end tests becomes straightforward. Instead of assembling complicated mock hierarchies or deciphering cryptic database fixtures, your tests read like user stories: registering accounts, exchanging tokens, creating resources, and asserting HTTP responses.
Here are four requirements that often break in production systems:
- Complete flow. A user signs up over HTTP, receives an API authentication token, posts a new book to
/booksusing a Bearer token header, and retrieves their book list. - Tenant isolation. User A can view only their own books; books belonging to User B must never leak into User A's book listing.
- Hidden resources. Attempting to retrieve User B's private book directly via
/books/{id}must return a 404 Not Found error rather than 403 Forbidden to prevent resource enumeration attacks. - Conflicts. Attempting to sign up with an existing email address or creating a duplicate book title must return an HTTP 409 Conflict response with a structured JSON error body.
The first three become new tests in tests/test_flows.py. The fourth is already covered for book titles by test_duplicate_title_answers_409 from the lab, and the Apply task adds the duplicate-email case:
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app.models import Book, User
from tests.factories import make_book, make_user
def auth(user: User) -> dict[str, str]:
return {"Authorization": f"Bearer {user.raw_token}"}
def test_sign_up_then_create_and_list_over_http(client: TestClient) -> None:
payload = {"email": "[email protected]", "password": "correct horse battery"}
signed_up = client.post("/users", json=payload)
assert signed_up.status_code == 201
token = signed_up.json()["token"]
created = client.post(
"/books",
json={"title": "Designing Data-Intensive Applications", "year": 2017},
headers={"Authorization": f"Bearer {token}"},
)
assert created.status_code == 201
listed = client.get("/books", headers={"Authorization": f"Bearer {token}"})
assert listed.status_code == 200
assert [b["title"] for b in listed.json()] == [
"Designing Data-Intensive Applications"
]
def test_listing_shows_only_my_books(
client: TestClient, session: Session
) -> None:
anna = make_user(session, email="[email protected]")
ben = make_user(session, email="[email protected]")
make_book(session, owner=anna, title="Anna's book")
make_book(session, owner=ben, title="Ben's book")
response = client.get("/books", headers=auth(anna))
assert response.status_code == 200
assert [b["title"] for b in response.json()] == ["Anna's book"]
def test_another_users_book_is_not_visible(
client: TestClient, session: Session
) -> None:
anna = make_user(session, email="[email protected]")
ben = make_user(session, email="[email protected]")
hidden = make_book(session, owner=ben, title="Ben's book")
response = client.get(f"/books/{hidden.id}", headers=auth(anna))
assert response.status_code == 404
assert response.json() == {"detail": "book not found"}Notice the clarity of test_listing_shows_only_my_books: in four lines of setup, we create two distinct users and give each one a book. The test author does not need to specify password hashes, slugs, or creation timestamps because the factory provides sensible defaults. When reading the test, the intention is immediately obvious: only the relationship between users and book ownership matters.
Furthermore, test_another_users_book_is_not_visible verifies authorisation. Instead of returning 403 Forbidden, which would leak the existence of a private book ID to an attacker, the API returns 404 Not Found. Testing through TestClient proves that both the HTTP status code and response payload match production expectations.
Driving tests through the HTTP layer also exercises response serialisation. FastAPI validates each return value against the route's response_model or return type, but the routes in this app return a plain dict, so only your assertions on the JSON catch fields that are missing or renamed. TestClient itself checks nothing against a schema, though; a field that no test asserts on can disappear unnoticed. To check every response against the published schema, use the contract tests in the next lesson.
pytest -v --no-header tests/test_flows.py============================= test session starts ==============================
collecting ... collected 3 items
tests/test_flows.py::test_sign_up_then_create_and_list_over_http PASSED [ 33%]
tests/test_flows.py::test_listing_shows_only_my_books PASSED [ 66%]
tests/test_flows.py::test_another_users_book_is_not_visible PASSED [100%]
============================== 3 passed in 0.58s ===============================05. Check your understanding
06. Apply it
Add two tests to tests/test_flows.py. In the first, create Anna with make_user, then sign up again with her email over HTTP and assert 409 with {"detail": "email already registered"}. Call session.commit() after the factory and before the request: the route's db.rollback() returns to the latest savepoint, and without that commit the savepoint also holds Anna, so she disappears too. In the second, post a book whose year is a word and assert 422. In the next lesson, you will automatically generate contract tests from your OpenAPI schema.
07. Review prompt
Contrast the factory pattern with static JSON fixtures across test readability, refactoring flexibility, and maintenance overhead. Explain why testing authorisation by invoking repository methods directly is insufficient compared to issuing HTTP requests through TestClient.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.