Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • File Upload and Download in FastAPI: multipart, UploadFile and FileResponse
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  • A Layered FastAPI Project: Controllers, Services, Schemas and One Folder per Concern
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider
  • Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask
  • How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak
  • AWS Cognito vs Keycloak: User Pools, App Clients and When a Managed Identity Provider Wins
  • Migrating FastAPI from Keycloak to AWS Cognito: The Four Values, the JWKS Address and Every Check on an Access Token
  • Testing a Cognito Login End to End: Allow the Password Flow, Confirm the Email Code, and Reset a Forgotten Password
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  • Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure
  • Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Testing

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Testing

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_path is a fixture from pytest itself: a fresh empty folder for each test. We create test.db in it, and Base.metadata.create_all builds the same tables the blog has.
  • app.dependency_overrides[get_db] = override_get_db is the swap. Whenever a route asks for get_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=False lets 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 db fixture 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.

Fixture chain. tmp_path feeds SessionTest, which builds test.db. SessionTest feeds client, which overrides get_db, and db. db feeds admin and reader. admin feeds post. client plus admin feed admin_client, which logs in. The real blog.db is never touched. tmp_path SessionTest test.db client overrides get_db db admin or reader post admin_client client + admin, logged in blog.db is never opened by a test
A test asks for admin_client, and pytest builds everything to its left first.

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 the E lines show both values: the response was 401, the test expected 403.
  • tests/test_admin.py:6 is 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

PieceJob
pytest.initestpaths, pythonpath, quiet warnings
SessionTestfresh test.db in tmp_path, all tables
clientdependency_overrides[get_db], no redirects, cleared after
admin, reader, postthe rows a test needs, nothing more
admin_client, reader_clientlogged-in clients with a session cookie
17 tests in 4 filespages, 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 38 of 39

Previous
Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
Next post
Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why

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)

Related posts

Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why

There's no test suite yet, so test the running Gemma chat app by hand in a fixed order: weights staged, images built, backend answers (and refuses with a reason), pages load, logs clean. Add a global exception handler so a dead Supabase shows 'ConnectError: connection refused', and end with a list of what still fails.

On this page

  • A drill in the training hall
  • Setting up
  • conftest.py: a test database through dependency overrides
  • Fixtures for users, a post and a login
  • The blog's data stays safe
  • What pytest finds
  • Testing the pages
  • The admin-only write route
  • Reading a failure
  • Testing login and register
  • Testing the passwords
  • Running the whole suite
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.