Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure
Seventeen pytest tests for the FastAPI blog. conftest.py builds a fresh test.db in tmp_path and swaps get_db with dependency_overrides, fixtures log in an admin and a reader, and the tests check pages, login, register, the admin-only write route and bcrypt's 72-byte limit. blog.db stays untouched.
What you will learn
- Give every test its own SQLite file with tmp_path and app.dependency_overrides[get_db]
- Build fixtures for users, a post and logged-in clients, and let pytest chain them
- Test pages, login, register and an admin-only route for 401, 403 and 303
- Read a pytest failure and decide whether the code or the test is wrong
Before you start
- pytest and FastAPI's TestClient on a small app
- FastAPI Depends and get_db
- How the blog's login and require_admin work
Until now we checked the FastAPI blog by clicking around in the browser. A test does that check in code, so you can run it again after every change, including the changes an AI agent makes.
You've seen pytest and FastAPI's test client on a small hello app. Now we point the same tools at the whole blog. The hard part is the database. The tests must not write into blog.db. So the first job is to give the tests their own database, and FastAPI has a clean way to do that: dependency overrides.
The email addresses and passwords in the test code below are placeholders. In the project, the admin fixtures and the admin-email test use the address set as ADMIN_EMAIL in .env; put your own test values there.
A drill in the training hall
Before a new boarding gate opens, airport staff run a drill in a training hall, away from the real passenger list. For each drill they set out a fresh practice list with only the passengers that drill needs. A practice passenger walks up, and the staff check what happens against the rule card. After the drill, the practice list is thrown away, and the real list was never touched.
That's testing in FastAPI. A test is the drill, a fixture sets out the practice list, and a dependency override points the gate at the practice list instead of the real one.
Setting up
requirements-dev.txt pulls in the blog's own packages and adds two:
-r requirements.txt
pytest==9.2.0
httpx==0.28.1
The test client is built on httpx, so it has to be installed. Install with uv pip install -r requirements-dev.txt. Then pytest.ini:
[pytest]
testpaths = tests
pythonpath = .
filterwarnings = ignore
testpaths says where to look. pythonpath = . puts the project folder on the path, so a test can write from app.main import app. filterwarnings = ignore keeps the report short. There's no plugin to add: the test client comes with FastAPI.
conftest.py: a test database through dependency overrides
pytest reads tests/conftest.py first, and every test in the folder can use its fixtures. Normally every route asks for Depends(get_db), which opens a session on blog.db. Here's how the tests swap it (the two passwords are placeholders):
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.auth import get_password_hash
from app.database import Base, get_db
from app.main import app
from app.models import Post, User
ADMIN_PASSWORD = "test-admin-password"
USER_PASSWORD = "test-reader-password"
ADMIN_HASH = get_password_hash(ADMIN_PASSWORD)
USER_HASH = get_password_hash(USER_PASSWORD)
@pytest.fixture
def SessionTest(tmp_path):
url = f"sqlite:///{tmp_path / 'test.db'}"
engine = create_engine(
url, connect_args={"check_same_thread": False}
)
Base.metadata.create_all(bind=engine)
yield sessionmaker(bind=engine)
engine.dispose()
@pytest.fixture
def client(SessionTest):
def override_get_db():
db = SessionTest()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
yield TestClient(app, follow_redirects=False)
app.dependency_overrides.clear()
@pytest.fixture
def db(SessionTest):
session = SessionTest()
yield session
session.close()
tmp_pathis a fixture from pytest itself: a fresh empty folder for each test. We createtest.dbin it, andBase.metadata.create_allbuilds the same tables the blog has.app.dependency_overrides[get_db] = override_get_dbis the swap. Whenever a route asks forget_db, FastAPI now hands it a session on the test file. The route code doesn't change at all. (The general pattern is in dependency injection with Depends and overrides.)follow_redirects=Falselets each test see the 303s itself instead of landing on the next page.dependency_overrides.clear()runs after the test and puts the app back.- The
dbfixture gives the test its own session on the same file, so it can check rows.
Fixtures for users, a post and a login
@pytest.fixture
def admin(db):
user = User(email="[email protected]", username="admin",
hashed_password=ADMIN_HASH, is_admin=True)
db.add(user)
db.commit()
return user
@pytest.fixture
def reader(db):
user = User(email="[email protected]", username="reader",
hashed_password=USER_HASH, is_admin=False)
db.add(user)
db.commit()
return user
@pytest.fixture
def post(db, admin):
row = Post(title="Hello World", content="<p>One two.</p>",
author_id=admin.id)
db.add(row)
db.commit()
return row
@pytest.fixture
def admin_client(client, admin):
client.post("/login", data={"email": "[email protected]",
"password": ADMIN_PASSWORD})
return client
@pytest.fixture
def reader_client(client, reader):
client.post("/login", data={"email": "[email protected]",
"password": USER_PASSWORD})
return client
The two hashes are made once at the top, because bcrypt is slow on purpose and we don't want to pay for it in every test. admin_client posts the login form, and the session cookie stays on the client. So a test just names what it needs, and pytest builds the chain.
The blog's data stays safe
To prove where the rows go, a small extra test with the post fixture printed its database, and the run checked blog.db afterwards:
test db file: test.db
posts in test db: 1
users in test db: 1
.
1 passed
blog.db: 5 posts, 2 users (file unchanged)
One post and the one admin it needs, in a file that disappears with its folder. blog.db still holds its five posts and two users. Run the tests as often as you like.
What pytest finds
pytest --collect-only -q
tests/test_admin.py::test_anonymous_cannot_open_the_write_page
tests/test_admin.py::test_reader_is_refused_on_the_write_route
tests/test_admin.py::test_admin_can_open_the_write_page
tests/test_admin.py::test_admin_can_publish_a_post
tests/test_auth.py::test_login_with_the_right_password
tests/test_auth.py::test_login_with_a_wrong_password
tests/test_auth.py::test_register_creates_a_user_and_logs_in
tests/test_auth.py::test_register_refuses_a_short_password
tests/test_pages.py::test_home_lists_a_post
tests/test_pages.py::test_post_page_shows_the_post
tests/test_pages.py::test_missing_post_is_not_found
tests/test_pages.py::test_login_and_register_pages_open
tests/test_passwords.py::test_the_hash_is_bcrypt_and_not_the_password
tests/test_passwords.py::test_the_same_password_gets_a_new_hash_each_time
tests/test_passwords.py::test_bcrypt_only_reads_the_first_72_bytes
tests/test_passwords.py::test_register_refuses_a_password_over_72_bytes
tests/test_passwords.py::test_registering_with_the_admin_email_makes_an_admin
17 tests collected
Each name reads like a sentence. When one fails, the name alone tells you what broke.
Testing the pages
def test_home_lists_a_post(client, post):
response = client.get("/")
assert response.status_code == 200
assert "Hello World" in response.text
def test_post_page_shows_the_post(client, post):
response = client.get(f"/post/{post.id}")
assert response.status_code == 200
assert "Hello World" in response.text
def test_missing_post_is_not_found(client):
response = client.get("/post/999")
assert response.status_code == 404
def test_login_and_register_pages_open(client):
assert client.get("/login").status_code == 200
assert client.get("/register").status_code == 200
client.get("/") takes the same trip as a browser request (traced in how a request and a login flow through the blog), with no server running. The router finds index, Depends(get_db) gets the test session because of the override, and the template turns the Hello World post into HTML.
The admin-only write route
from app.models import Post
def test_anonymous_cannot_open_the_write_page(client):
response = client.get("/admin/create")
assert response.status_code == 401
def test_reader_is_refused_on_the_write_route(reader_client, db):
response = reader_client.post(
"/admin/create", data={"title": "T", "content": "C"}
)
assert response.status_code == 403
assert db.query(Post).count() == 0
def test_admin_can_open_the_write_page(admin_client):
response = admin_client.get("/admin/create")
assert response.status_code == 200
def test_admin_can_publish_a_post(admin_client, db):
response = admin_client.post(
"/admin/create",
data={"title": "My First Post", "content": "<p>Hi</p>"},
)
assert response.status_code == 303
post = db.query(Post).one()
assert response.headers["location"] == f"/post/{post.id}"
assert post.title == "My First Post"
Both write routes depend on require_admin. With no user in the session, require_auth raises 401. The reader is logged in but not an admin, so require_admin raises 403, and the test also checks that the post table is still empty. The admin gets 200, then a 303 to the new post.
Reading a failure
Let's break one on purpose: in the first admin test, change the expected status to 403 and run pytest tests/test_admin.py:
============================= test session starts =============================
platform win32 -- Python 3.13.14, pytest-9.2.0, pluggy-1.7.0
rootdir: S01L06_2_BlogTests
configfile: pytest.ini
plugins: anyio-4.16.0
collected 4 items
tests/test_admin.py F... [100%]
================================== FAILURES ===================================
__________________ test_anonymous_cannot_open_the_write_page __________________
client = <starlette.testclient.TestClient object at 0x000001964B05FB60>
def test_anonymous_cannot_open_the_write_page(client):
response = client.get("/admin/create")
> assert response.status_code == 403
E assert 401 == 403
E + where 401 = <Response [401 Unauthorized]>.status_code
tests/test_admin.py:6: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_admin.py::test_anonymous_cannot_open_the_write_page - asser...
========================= 1 failed, 3 passed =========================
F...: one failed, three passed.client = ...: the fixture the test used.- The
>line is the assert that failed, and theElines show both values: the response was 401, the test expected 403. tests/test_admin.py:6is the exact line.
So who's wrong, the code or the test? 401 means the app doesn't know who you are. 403 means it knows you and says no. An anonymous visitor isn't logged in, so 401 is right, and the test expected the wrong thing. Put 401 back and the file shows .... and 4 passed. Read the report first and decide which side is wrong. Don't change a test just to make it pass, and watch for exactly that when an AI agent writes the fix.
Testing login and register
from app.models import User
def test_login_with_the_right_password(client, admin):
response = client.post(
"/login",
data={"email": "[email protected]",
"password": "test-admin-password"},
)
assert response.status_code == 303
assert response.headers["location"] == "/"
assert "session" in response.cookies
def test_login_with_a_wrong_password(client, admin):
response = client.post(
"/login",
data={"email": "[email protected]", "password": "nope"},
)
assert response.status_code == 200
assert "Invalid email or password" in response.text
assert "session" not in response.cookies
A good login is a 303 to / with a session cookie. A wrong password shows the login page again, so the status is 200, and no cookie comes back. Two more tests in the file register a new user (303, a cookie, and is_admin is False in the test database) and send a three-letter password, which is refused with "at least 6 characters" and leaves the user table empty.
Testing the passwords
from app.auth import get_password_hash, verify_password
from app.models import User
def test_the_hash_is_bcrypt_and_not_the_password():
hashed = get_password_hash("test-password-1")
assert hashed.startswith("$2b$12$")
assert "test-password-1" not in hashed
assert verify_password("test-password-1", hashed)
assert not verify_password("secret-pass-2", hashed)
def test_the_same_password_gets_a_new_hash_each_time():
first = get_password_hash("test-password-1")
second = get_password_hash("test-password-1")
assert first != second
def test_bcrypt_only_reads_the_first_72_bytes():
hashed = get_password_hash("a" * 72)
assert verify_password("a" * 72 + "extra", hashed)
These check the bcrypt hash and the 72-byte limit behind the login crash we fixed when the design went in. One more test sends 73 bytes to register and expects "max 72 bytes". The last test pins down a review finding: registering with the address the project's .env sets as ADMIN_EMAIL makes you an admin, because the app only compares the email text (routes/auth.py, line 62). The test passes, so the hole is real. When someone fixes the app, they change this test on purpose to expect False.
Running the whole suite
pytest
collected 17 items
tests/test_admin.py .... [ 23%]
tests/test_auth.py .... [ 47%]
tests/test_pages.py .... [ 70%]
tests/test_passwords.py ..... [100%]
============================= 17 passed =============================
pytest --durations=3 lists the three slowest steps: two password tests and the setup of an admin client test, where the login checks the password. bcrypt again, slow on purpose. The same idea for the other two blogs: Django with pytest-django and Flask with pytest.
Common mistakes
- Testing against the real database. Without the override, every test writes into
blog.db. - Forgetting
dependency_overrides.clear(). The override leaks into the next test. - Leaving redirects on. You'd assert on the home page instead of the 303 the route really sent.
- Hashing in every fixture call. bcrypt is slow; hash the test passwords once.
- "Fixing" the test when the code is right. Read 401 versus 403 before you touch either side.
Quick recap
| Piece | Job |
|---|---|
pytest.ini | testpaths, pythonpath, quiet warnings |
SessionTest | fresh test.db in tmp_path, all tables |
client | dependency_overrides[get_db], no redirects, cleared after |
admin, reader, post | the rows a test needs, nothing more |
admin_client, reader_client | logged-in clients with a session cookie |
| 17 tests in 4 files | pages, auth, admin route, passwords |
Try it yourself
Write a test that logs the admin out with GET /logout and checks that the write page answers 401 again. Then break the logout route once and watch the test fail. If you ask an AI agent for more tests (editing, deleting, comments, a reader trying to edit the admin's post), tell it to use the existing fixtures, and run each new test against broken code once to be sure it can fail.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)