Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
Twenty pytest tests for the designed Flask blog: a TestConfig and tmp_path database so blog.db stays untouched, a fixture chain that logs in an admin, tests for pages, auth, the admin-only write view and password hashing, and one failure read line by line.
What you will learn
- Build a test app from create_app with its own SQLite file in tmp_path
- Write fixtures for users, a post and logged-in clients
- Test pages, login, register and an admin-only view with the Flask test client and session_transaction
- Read a pytest failure and decide whether the code or the test is wrong
Before you start
- How a request and a login flow through the Flask blog
- pytest basics
Until now we checked the Flask 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.
Think about a LEGO model you've already finished. Before you add a new piece to it, you try the idea on a spare baseplate first. For each try you put down only the bricks it needs, check the result against the picture, and clear the plate afterwards. The finished model is never touched. That's testing in Flask: a test is one try, fixtures put down the bricks, and the app factory gives every test its own spare baseplate with its own database.
The project is the designed blog from the request and login flow, frozen, plus a tests folder, pytest.ini and requirements-dev.txt.
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.
Setting up
requirements-dev.txt pulls in the blog's own requirements file (spelled the way the project has it) and adds pytest:
-r requirments.txt
pytest==9.2.0
uv pip install -r requirements-dev.txt
Resolved 26 packages in 23ms
Installed 26 packages in 868ms
pytest.ini:
[pytest]
testpaths = tests
pythonpath = .
filterwarnings = ignore
testpaths tells pytest where to look. pythonpath = . puts the project folder on the path, so a test can say from app import create_app. filterwarnings = ignore keeps the report short. There's no plugin to add: Flask's test client comes with Flask itself.
conftest.py: a test app from the factory
pytest reads tests/conftest.py first, and every test in the folder can use its fixtures. The test passwords below are placeholders; use any values you like.
import pytest
from app import create_app, db
from app.models import Post, User
from config import Config
ADMIN_EMAIL = "[email protected]"
ADMIN_PASSWORD = "test-admin-password"
READER_PASSWORD = "test-reader-password"
class TestConfig(Config):
TESTING = True
WTF_CSRF_ENABLED = False
SECRET_KEY = "change-me"
ADMIN_EMAIL = ADMIN_EMAIL
def make_app(tmp_path, csrf=False):
class Cfg(TestConfig):
WTF_CSRF_ENABLED = csrf
SQLALCHEMY_DATABASE_URI = (
f"sqlite:///{tmp_path / 'test.db'}")
return create_app(Cfg)
@pytest.fixture
def app(tmp_path):
app = make_app(tmp_path)
yield app
with app.app_context():
db.session.remove()
db.engine.dispose()
@pytest.fixture
def csrf_app(tmp_path):
app = make_app(tmp_path, csrf=True)
yield app
with app.app_context():
db.session.remove()
db.engine.dispose()
@pytest.fixture
def client(app):
return app.test_client()
create_app takes a config class. Normally that's Config, pointing at blog.db. In the tests, TestConfig sets TESTING, a test secret key, and WTF_CSRF_ENABLED = False so a test can post a form without the hidden token (one test turns it back on).
tmp_path is a fixture from pytest itself: a fresh empty folder for each test. The database address points at test.db inside it. create_app already runs db.create_all(), so every table is built in the test file. After the test, the fixture removes the session and closes the engine.
Fixtures for users, a post and a login
def add_user(app, name, email, password):
with app.app_context():
user = User(name=name, email=email)
user.set_password(password)
db.session.add(user)
db.session.commit()
return user.id
def log_in(client, email, password):
return client.post("/auth/login", data={
"email": email, "password": password})
@pytest.fixture
def admin(app):
return add_user(app, "Admin", ADMIN_EMAIL, ADMIN_PASSWORD)
@pytest.fixture
def reader(app):
return add_user(app, "Reader", "[email protected]",
READER_PASSWORD)
@pytest.fixture
def post(app, admin):
with app.app_context():
row = Post(title="Hello World", slug="hello-world",
content="One two.", author_id=admin)
db.session.add(row)
db.session.commit()
@pytest.fixture
def admin_client(client, admin):
log_in(client, ADMIN_EMAIL, ADMIN_PASSWORD)
return client
@pytest.fixture
def reader_client(client, reader):
log_in(client, "[email protected]", READER_PASSWORD)
return client
add_user sets the password with set_password, so it's hashed. admin_client posts the email and password to /auth/login, and the session cookie stays on the client for the rest of the test.
The blog's data stays safe
Where do these rows go? Not into blog.db. A small extra probe test with the post fixture printed:
test db file: test.db
posts in test db: 1
users in test db: 1
.
1 passed in X.XXs
blog.db: 10 posts, 5 users (file unchanged)
One post, and one user: the admin the post needs. When the test ends, the engine is closed, and the next test gets a new folder and an empty file. blog.db keeps its ten posts and five users, so you can 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_gets_403_on_the_write_page
tests/test_admin.py::test_reader_cannot_create_a_post
tests/test_admin.py::test_admin_opens_the_write_page
tests/test_admin.py::test_admin_creates_a_post
tests/test_admin.py::test_first_user_with_the_admin_email_is_admin
tests/test_admin.py::test_post_without_csrf_token_is_rejected
tests/test_auth.py::test_register_creates_a_user
tests/test_auth.py::test_register_rejects_a_used_email
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_logout_clears_the_session
tests/test_pages.py::test_home_page_lists_the_post
tests/test_pages.py::test_home_page_works_with_no_posts
tests/test_pages.py::test_post_page_opens_by_slug
tests/test_pages.py::test_unknown_slug_is_404
tests/test_pages.py::test_login_page_opens
tests/test_passwords.py::test_password_is_hashed
tests/test_passwords.py::test_right_and_wrong_password
tests/test_passwords.py::test_same_password_gives_two_hashes
20 tests collected in X.XXs
Each name reads like a sentence, so when one fails, the name alone tells you what broke.
Testing the pages
def test_home_page_lists_the_post(client, post):
response = client.get("/")
assert response.status_code == 200
assert b"Hello World" in response.data
def test_home_page_works_with_no_posts(client):
response = client.get("/")
assert response.status_code == 200
def test_post_page_opens_by_slug(client, post):
response = client.get("/post/hello-world")
assert response.status_code == 200
assert b"One two." in response.data
def test_unknown_slug_is_404(client):
response = client.get("/post/no-such-post")
assert response.status_code == 404
def test_login_page_opens(client):
response = client.get("/auth/login")
assert response.status_code == 200
assert b"Login" in response.data
No server is running. The test client hands the request straight to Flask: the URL map picks index, Flask-SQLAlchemy reads from test.db, Jinja2 builds the HTML. response.data is bytes, which is why the strings have a b in front.
The admin-only write view
from app.models import Post
from tests.conftest import ADMIN_EMAIL, add_user, log_in
NEW_POST = {"title": "Second Post", "slug": "second-post",
"content": "Written by a test."}
def count_posts(app):
with app.app_context():
return Post.query.count()
def test_reader_gets_403_on_the_write_page(reader_client):
response = reader_client.get("/admin/post/create")
assert response.status_code == 403
def test_reader_cannot_create_a_post(reader_client, app):
response = reader_client.post(
"/admin/post/create", data=NEW_POST)
assert response.status_code == 403
assert count_posts(app) == 0
def test_admin_opens_the_write_page(admin_client):
response = admin_client.get("/admin/post/create")
assert response.status_code == 200
def test_admin_creates_a_post(admin_client, app):
response = admin_client.post(
"/admin/post/create", data=NEW_POST)
assert response.status_code == 302
assert response.headers["Location"] == "/admin/"
assert count_posts(app) == 1
The reader is logged in but isn't the admin, so admin_required answers 403, and count_posts proves nothing was written. The admin gets 200, then a 302 to /admin/ and one post in the test database.
Reading a failure
The first admin test sends an anonymous client to the write page. Suppose you wrote it to expect 403:
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
collected 7 items
tests/test_admin.py F...... [100%]
================================== FAILURES ===================================
__________________ test_anonymous_cannot_open_the_write_page __________________
client = <FlaskClient <Flask 'app'>>
def test_anonymous_cannot_open_the_write_page(client):
response = client.get("/admin/post/create")
> assert response.status_code == 403
E assert 302 == 403
E + where 302 = <WrapperTestResponse streamed [302 FOUND]>.status_code
tests/test_admin.py:15: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_admin.py::test_anonymous_cannot_open_the_write_page - asser...
========================= 1 failed, 6 passed in X.XXs =========================
Read it top down: the header (platform, pytest 9.2, the root folder, pytest.ini as config), the progress line (one F, six dots), the fixture the test used, the > line that failed, the E lines with both values (302 came back, 403 was expected), and tests/test_admin.py:15, the exact place.
Fix the right side
So who's wrong, the code or the test? In the app factory, login_manager.login_view = 'auth.login'. Someone who isn't logged in and opens a protected page is sent to the login page with a 302. 403 is for someone the blog knows but who isn't allowed, like the reader. For a blog made of pages, sending a visitor to log in is right. The code is right; the test expected the wrong thing.
def test_anonymous_cannot_open_the_write_page(client):
response = client.get("/admin/post/create")
assert response.status_code == 302
assert "/auth/login" in response.headers["Location"]
tests/test_admin.py ....... [100%]
============================== 7 passed in X.XXs ==============================
When a test fails, read the report first and decide which side is wrong. Don't change a test just to make it pass. That matters even more when an AI agent writes the fix.
Testing login and register
from app.models import User
from tests.conftest import (
ADMIN_EMAIL, ADMIN_PASSWORD, log_in)
def test_register_creates_a_user(client, app):
response = client.post("/auth/register", data={
"name": "Ann", "email": "[email protected]",
"password": "test-password-2", "password2": "test-password-2"})
assert response.status_code == 302
assert response.headers["Location"] == "/auth/login"
with app.app_context():
user = User.query.filter_by(email="[email protected]").first()
assert user is not None
assert user.password_hash != "test-password-2"
def test_login_with_the_right_password(client, admin):
response = log_in(client, ADMIN_EMAIL, ADMIN_PASSWORD)
assert response.status_code == 302
assert response.headers["Location"] == "/"
with client.session_transaction() as session:
assert "_user_id" in session
def test_login_with_a_wrong_password(client, admin):
response = log_in(client, ADMIN_EMAIL, "wrong-pass")
assert response.status_code == 302
assert response.headers["Location"] == "/auth/login"
with client.session_transaction() as session:
assert "_user_id" not in session
def test_logout_clears_the_session(admin_client):
admin_client.get("/auth/logout")
with admin_client.session_transaction() as session:
assert "_user_id" not in session
session_transaction() opens the client's session so the test can look inside. After a good login, Flask-Login's _user_id is there; after a wrong password or a logout, it isn't. One more test in this file, test_register_rejects_a_used_email, registers with the admin's email again and gets 200 (the form again) with still only one user.
Two checks from the review
The last two admin tests check what we found when we traced the login:
def test_first_user_with_the_admin_email_is_admin(client):
client.post("/auth/register", data={
"name": "First", "email": ADMIN_EMAIL,
"password": "test-password-3", "password2": "test-password-3"})
log_in(client, ADMIN_EMAIL, "test-password-3")
assert client.get("/admin/post/create").status_code == 200
def test_post_without_csrf_token_is_rejected(csrf_app):
user_id = add_user(csrf_app, "Admin", ADMIN_EMAIL, "test-password-4")
client = csrf_app.test_client()
with client.session_transaction() as session:
session["_user_id"] = str(user_id)
session["_fresh"] = True
response = client.post("/admin/post/create", data=NEW_POST)
assert response.status_code == 200
assert count_posts(csrf_app) == 0
The CSRF test uses csrf_app, with the token check on. It can't log in through the form without a token, so it writes _user_id straight into the session. Then it posts without the token: the form comes back with 200 and there are still zero posts, so the protection really works.
The other test documents the admin-by-email finding. It passes, so the hole is real. When someone fixes the app, they change this test on purpose to expect the opposite.
Testing the passwords
from app.models import User
def test_password_is_hashed():
user = User(name="A", email="[email protected]")
user.set_password("secret-1")
assert user.password_hash != "secret-1"
assert user.password_hash.startswith("scrypt:")
def test_right_and_wrong_password():
user = User(name="A", email="[email protected]")
user.set_password("secret-1")
assert user.check_password("secret-1")
assert not user.check_password("secret-2")
def test_same_password_gives_two_hashes():
one, two = User(), User()
one.set_password("secret-1")
two.set_password("secret-1")
assert one.password_hash != two.password_hash
These don't even need the app or a database. They just make User objects. Werkzeug adds a new salt each time, so the same password gives two hashes.
Running the whole suite
pytest
collected 20 items
tests/test_admin.py ....... [ 35%]
tests/test_auth.py ..... [ 60%]
tests/test_pages.py ..... [ 85%]
tests/test_passwords.py ... [100%]
============================= 20 passed in X.XXs ==============================
pytest -v gives one PASSED line per test. pytest --durations=3 lists the three slowest steps, and in the run all three were setup steps for tests that need a logged-in client: building a test app, hashing a password and logging in. scrypt is slow on purpose.
Common mistakes
- Testing against the real database. Point the test config at
tmp_path, never atblog.db. - Leaving CSRF on for every test. Turn it off in
TestConfig, and keep one test with it on to prove it works. - Expecting 403 for anonymous users. With
login_viewset, Flask-Login answers 302 to the login page. - Comparing
response.datawith a str. It's bytes: useb"..."orget_data(as_text=True). - Editing a failing test until it passes. Decide first whether the code or the test is wrong.
Quick recap
| Piece | Job |
|---|---|
TestConfig + make_app(tmp_path) | a fresh app with its own test.db per test |
fixtures in conftest.py | users, a post, logged-in clients on demand |
app.test_client() | requests straight into Flask, no server |
session_transaction() | look inside, or write to, the client's session |
pytest, -v, --collect-only, --durations | run, list and time the 20 tests |
Testing a FastAPI app works the same way in spirit; compare with Testing FastAPI with pytest.
Try it yourself
Write a test that logs the admin out and checks that the write page sends you to the login page again. Then break the code once (remove @login_required, say) and watch the test fail. If you ask an AI agent for more tests, for editing and deleting posts or a reader trying to delete the admin's post, review the diff like any other change: read each test, run it, and break the code once to make sure the test 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)Related posts
Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.
Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.
Async Python: async def, await, asyncio.gather and the Blocking Trap
One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
