Test the app
On this page you run the tests of the layered shop project from Extend, read how they are built and write one of your own. You learn how FastAPI's TestClient calls your application without a server, how pytest fixtures prepare each test, how app.dependency_overrides swaps a dependency for a test version, and how to check validation and error responses. You also see which tests fastkit ships and how the Coverage testing option measures them.
Run the tests
Every fastkit level ships tests, and fastkit addroute writes tests for each resource it adds. In shop, run them with pytest:
$ uv run pytest -q
...
tests/test_config.py ...................................... [ 41%]
tests/test_item_store.py ..... [ 47%]
tests/test_items.py ......................... [ 74%]
tests/test_main.py ...... [ 81%]
tests/test_users.py ................. [100%]
============================= 91 passed in 10.42s ==============================
pytest collects every test_*.py file under tests/ and runs each function whose name starts with test_. Each dot is a passing test. test_config.py checks the settings rules (for example the SECRET_KEY checks outside development), test_item_store.py the file-based item store, test_items.py and test_main.py the HTTP endpoints, and test_users.py is the file fastkit addroute users wrote.
How the test client is built
A TestClient sends requests straight to the application object, without starting uvicorn. You call client.get(...) or client.post(..., json=...) and get a response with status_code, headers and json(). A pytest fixture is a function marked with @pytest.fixture. A test that names a fixture as an argument receives its value; when the fixture uses yield, the code after yield runs once the test has finished. tests/conftest.py holds the fixtures that every test file shares:
@pytest.fixture
def store(tmp_path: Path) -> ItemStore:
"""Item store on a temporary file, so tests never touch src/mocks."""
path = tmp_path / "items.json"
path.write_text(json.dumps(SEED_ITEMS), encoding="utf-8")
return ItemStore(path)
@pytest.fixture
def client(store: ItemStore) -> Generator[TestClient, None, None]:
app.dependency_overrides[get_item_store] = lambda: store
# TestClient sends requests straight to the app, without starting a server.
# https://fastapi.tiangolo.com/tutorial/testing/
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
The endpoints get their item store from the dependency get_item_store (see Extend). app.dependency_overrides is a dictionary on the application: its keys are dependency functions, its values the functions FastAPI calls instead. Here every request of a test gets a store on a temporary file with two seed items, so the tests never change src/mocks/mock_items.json. tmp_path is a fixture built into pytest: a new temporary directory for each test. After the test, clear() removes the override. The FastAPI guide Testing dependencies with overrides explains the technique.
Read one test
A test sends one request and checks the response with assert. This one from tests/test_items.py checks the 404 answer for an unknown id:
def test_get_item_not_found(client: TestClient) -> None:
response = client.get(f"{ITEMS_URL}/999")
assert response.status_code == 404
assert response.json() == {"detail": "Item not found"}
ITEMS_URL is /api/v1/items, built from the settings in conftest.py. The other tests follow the same pattern: test_create_item_returns_201_and_location checks the 201 status and that the Location header leads back to the new item, and test_create_item_validates_input sends invalid bodies (an empty name, a negative price, no price) and expects 422, which FastAPI answers before the endpoint runs because the body does not match the ItemCreate model.
Write a test
The users resource that fastkit addroute added keeps its records in memory, in a UserRepository that the endpoints get from the dependency get_user_repository (in src/crud/users.py; src/api/deps.py wraps it as UserRepositoryDep). Create tests/test_users_override.py; its fixture gives the endpoints a repository that already holds one user:
from collections.abc import Iterator
import pytest
from fastapi.testclient import TestClient
from src.crud.users import UserRepository, get_user_repository
from src.main import app
USERS_URL = app.url_path_for("list_users")
@pytest.fixture
def client() -> Iterator[TestClient]:
repository = UserRepository()
repository.add({"name": "Ada"})
app.dependency_overrides[get_user_repository] = lambda: repository
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
def test_lists_the_users_of_the_test_repository(client: TestClient) -> None:
response = client.get(USERS_URL)
assert response.status_code == 200
assert response.json()["items"] == [{"id": 1, "name": "Ada", "description": None}]
def test_rejects_an_empty_name(client: TestClient) -> None:
response = client.post(USERS_URL, json={"name": ""})
assert response.status_code == 422
assert response.json()["detail"][0]["loc"] == ["body", "name"]
app.url_path_for("list_users") looks up the path of the endpoint function list_users, so the test keeps working if the prefix changes. The second test reads the body of a 422 response: detail is a list of errors, and loc says where the invalid value was (the name field of the request body). Run the tests again; the two new ones bring the total to 93:
$ uv run pytest -q
...
============================== 93 passed in 0.90s ==============================
Measure coverage
Coverage tells you which lines of your code the tests ran. Every level after hello ships pytest-cov, and pyproject.toml sets what to measure ([tool.coverage.run], source = ["src"]). In shop:
$ uv run pytest --cov
...
Name Stmts Miss Cover Missing
----------------------------------------------------------
...
src/api/deps.py 8 1 88% 14
...
src/main.py 11 1 91% 24
...
----------------------------------------------------------
TOTAL 350 4 99%
============================== 93 passed in 1.25s ==============================
Miss counts the lines no test ran, and Missing names them: line 14 of src/api/deps.py is the body of get_item_store, which the tests always replace with an override.
FastAPI documentation
Next
Move to a domain layout and a database carries shop to the domain level, where the items live in a SQL database.