Testing a Django Blog with pytest-django: Fixtures, the Test Database and the Client
Fourteen pytest tests for a Django blog: pytest.ini, fixtures in conftest.py, a test database that leaves db.sqlite3 alone, the client fixture for pages and login, and how to read a failure before you fix it.
What you will learn
- Set up pytest-django with pytest.ini and a dev requirements file
- Write fixtures in conftest.py that build users, posts and a logged-in client
- Explain how the test database keeps the real db.sqlite3 untouched
- Test models, pages, login and a login_required view, and read a failing test
Before you start
- pytest basics: test functions and assert
- Django models, views and URLs
- How a Django login works
Until now you probably checked your 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 of a restaurant kitchen. Before a dish goes on the menu, the chef cooks it in a practice kitchen, away from the main pantry. For each try there's a fresh tray with only the ingredients that dish needs. The chef tastes it against the recipe card. If it doesn't match, the note says exactly what's different. After each try the tray is cleared, and the main pantry is never touched. In Django testing, a test is the tasting, a fixture sets out the tray, and the test database is the practice kitchen.
Setting up pytest-django
If plain pytest is new to you, start with testing with pytest. The same blog tests exist for the other tracks too: FastAPI and Flask. For Django you add one plugin, pytest-django. The test tools go in requirements-dev.txt, so they stay out of the main requirements:
-r requirements.txt
pytest
pytest-django
uv pip install -r requirements-dev.txt
Among the 23 installed packages are pytest==9.2.0 and pytest-django==4.14.0. Then pytest.ini at the project root:
[pytest]
DJANGO_SETTINGS_MODULE = blogproject.settings
python_files = test_*.py
The first line tells pytest which Django settings to load before any test runs. python_files means pytest only collects files whose names start with test_. The tests sit in a tests folder next to manage.py; the empty tests.py Django made inside the app isn't collected.
Fixtures in conftest.py
pytest reads tests/conftest.py first, and every test in the folder can use its fixtures. (The project uses its own test password and user name; both are replaced with placeholders here.)
import pytest
from django.contrib.auth.models import User
from blog.models import Post
PASSWORD = "test-password-change-me"
@pytest.fixture
def author(db):
return User.objects.create_user(
"tester", password=PASSWORD
)
@pytest.fixture
def post(author):
return Post.objects.create(
title="Hello World",
content="One two three four five.",
author=author,
status="published",
)
@pytest.fixture
def draft(author):
return Post.objects.create(
title="Work in Progress",
content="Not ready yet.",
author=author,
)
@pytest.fixture
def logged_in(client, author):
client.login(username="tester", password=PASSWORD)
return client
authorasks fordb, a fixture from pytest-django that gives the test access to the database. Without it, a database query inside a test raises an error.postasks forauthorand creates a published post titled Hello World.draftcreates Work in Progress. There's no status, so it's saved as a draft.logged_intakes theclientfixture, logs the test user in and hands the client back.
The test database
These rows don't go into the blog's own database. When the run starts, pytest-django creates a separate test database and runs every migration on it. On SQLite, Django keeps it in memory. Each test starts empty, the fixtures add only what that test needs, and everything is rolled back at the end of the test.
To prove it, the lecture ran a small extra test that counts the posts, then counted the real database:
posts in test db: 1
.
1 passed in 1.52s
db.sqlite3 posts: 6 (file unchanged)
One post in the test (the fixture's Hello World), and the blog's six posts untouched. Run the tests as often as you like.
What pytest finds
pytest --collect-only -q
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_write_page_opens_when_logged_in
tests/test_auth.py::test_logged_in_user_can_publish
tests/test_models.py::test_slug_comes_from_the_title
tests/test_models.py::test_same_title_gets_a_counter
tests/test_models.py::test_str_is_the_title
tests/test_models.py::test_short_post_reads_in_one_minute
tests/test_models.py::test_new_post_starts_as_a_draft
tests/test_pages.py::test_home_lists_a_published_post
tests/test_pages.py::test_home_hides_a_draft
tests/test_pages.py::test_post_page_shows_the_post
tests/test_pages.py::test_draft_page_is_not_found
tests/test_auth.py::test_write_page_needs_a_login
14 tests collected in 0.21s
Five tests in test_auth.py, five in test_models.py, four in test_pages.py. Each name reads like a sentence, so when one fails, the name alone tells you what broke.
Testing the model
from blog.models import Post
def test_slug_comes_from_the_title(post):
assert post.slug == "hello-world"
def test_same_title_gets_a_counter(author, post):
second = Post.objects.create(
title="Hello World",
content="Again.",
author=author,
)
assert second.slug == "hello-world-1"
def test_str_is_the_title(post):
assert str(post) == "Hello World"
def test_short_post_reads_in_one_minute(post):
assert post.get_read_time() == "1 min read"
def test_new_post_starts_as_a_draft(draft):
assert draft.status == "draft"
Each test takes a fixture and checks one behaviour. The slug tests check the model's save method:
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
# Ensure unique slug
original_slug = self.slug
counter = 1
while Post.objects.filter(slug=self.slug).exists():
self.slug = f"{original_slug}-{counter}"
counter += 1
super().save(*args, **kwargs)
Hello World becomes hello-world. A second post with the same title finds that slug taken and gets hello-world-1. The content has five words, so get_read_time (word count divided by 200, at least 1) returns 1 min read.
Reading a failure
Break one on purpose: change the first test to expect "hello_world" and run pytest tests/test_models.py.
============================= test session starts =============================
platform win32 -- Python 3.13.14, pytest-9.2.0, pluggy-1.7.0
django: version: 6.1.3, settings: blogproject.settings (from ini)
rootdir: S01L06_2_BlogTests
configfile: pytest.ini
plugins: django-4.14.0
collected 5 items
tests/test_models.py F.... [100%]
================================== FAILURES ===================================
_______________________ test_slug_comes_from_the_title ________________________
post = <Post: Hello World>
def test_slug_comes_from_the_title(post):
> assert post.slug == "hello_world"
E AssertionError: assert 'hello-world' == 'hello_world'
E
E - hello_world
E ? ^
E + hello-world
E ? ^
tests/test_models.py:5: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_models.py::test_slug_comes_from_the_title - AssertionError:...
========================= 1 failed, 4 passed in 4.32s =========================
- The
django:line in the header shows pytest-django loadedblogproject.settingsfrom the ini file. F....means one failed and four passed.- The line with
>is the assert that failed. TheElines show both values, and the^marks point at the one character that differs. tests/test_models.py:5tells you exactly where.
So who's wrong, the code or the test? slugify turns spaces into dashes, and the blog's post addresses use that slug. The code is right and the test expected the wrong thing. Put hello-world back and the run says 5 passed in 3.97s. When a test fails, read the report and decide which side is wrong. Don't change a test just to make it pass, especially when an AI agent writes the fix.
Testing pages with the client
client is a test browser from pytest-django. It sends requests straight into Django with no server running.
def test_home_lists_a_published_post(client, post):
response = client.get("/")
assert response.status_code == 200
assert "Hello World" in response.content.decode()
def test_home_hides_a_draft(client, post, draft):
html = client.get("/").content.decode()
assert "Work in Progress" not in html
def test_post_page_shows_the_post(client, post):
response = client.get("/post/hello-world/")
assert response.status_code == 200
assert response.context["post"] == post
def test_draft_page_is_not_found(client, draft):
response = client.get("/post/work-in-progress/")
assert response.status_code == 404
client.get("/") goes through the URLs to the home view, which asks for published posts only, so Hello World is on the page and Work in Progress isn't. The test client also gives you response.context, the values the view handed to the template, so you can check the post in it is the fixture's post. The draft's address returns 404, because post_detail uses get_object_or_404 on published posts. Nobody can open a draft by guessing its address.
Testing the login and the write page
The login flow itself is explained in how a request and a login flow through Django. Here we test it:
from blog.models import Post
def test_login_with_the_right_password(client, author):
response = client.post(
"/login/",
{"username": "tester", "password": "test-password-change-me"},
)
assert response.status_code == 302
assert response.url == "/"
assert "_auth_user_id" in client.session
def test_login_with_a_wrong_password(client, author):
response = client.post(
"/login/",
{"username": "tester", "password": "wrong"},
)
assert response.status_code == 200
assert "_auth_user_id" not in client.session
def test_write_page_needs_a_login(client):
response = client.get("/post/create/")
assert response.status_code == 302
assert response.url == "/login/?next=/post/create/"
def test_write_page_opens_when_logged_in(logged_in):
response = logged_in.get("/post/create/")
assert response.status_code == 200
def test_logged_in_user_can_publish(logged_in, author):
response = logged_in.post(
"/post/create/",
{
"title": "My First Post",
"content": "Some words here.",
"category": "Other",
"status": "published",
},
)
assert response.status_code == 302
post = Post.objects.get(author=author)
assert post.slug == "my-first-post"
The test client skips the CSRF check by default, so the login POST only sends the two fields. With the right password, the view redirects (302) and the session holds _auth_user_id. With a wrong one, the login page shows again (200) and there's no user id. The write page is tested from both sides: anonymous gets a 302 to the login page with next, the logged-in client gets 200, and a publish creates a post with the slug my-first-post.
Running the whole suite
pytest -v
The test lines and the summary (session header trimmed):
tests/test_auth.py::test_login_with_the_right_password PASSED [ 7%]
tests/test_auth.py::test_login_with_a_wrong_password PASSED [ 14%]
tests/test_auth.py::test_write_page_opens_when_logged_in PASSED [ 21%]
tests/test_auth.py::test_logged_in_user_can_publish PASSED [ 28%]
tests/test_models.py::test_slug_comes_from_the_title PASSED [ 35%]
tests/test_models.py::test_same_title_gets_a_counter PASSED [ 42%]
tests/test_models.py::test_str_is_the_title PASSED [ 50%]
tests/test_models.py::test_short_post_reads_in_one_minute PASSED [ 57%]
tests/test_models.py::test_new_post_starts_as_a_draft PASSED [ 64%]
tests/test_pages.py::test_home_lists_a_published_post PASSED [ 71%]
tests/test_pages.py::test_home_hides_a_draft PASSED [ 78%]
tests/test_pages.py::test_post_page_shows_the_post PASSED [ 85%]
tests/test_pages.py::test_draft_page_is_not_found PASSED [ 92%]
tests/test_auth.py::test_write_page_needs_a_login PASSED [100%]
============================= 14 passed in 17.28s =============================
test_write_page_needs_a_login runs last. It doesn't touch the database, and pytest-django runs the database tests first. To see where the time goes:
pytest --durations=3
The end of the output:
============================= slowest 3 durations =============================
1.94s setup tests/test_auth.py::test_logged_in_user_can_publish
1.94s setup tests/test_auth.py::test_write_page_opens_when_logged_in
1.74s call tests/test_auth.py::test_login_with_the_right_password
14 passed in 18.95s
All three are login tests. Creating the user and logging in both hash the password, and password hashing is slow on purpose.
Asking an AI agent for more tests
A sample prompt in Role, Context, Task, Format: Role: a Django developer who writes pytest tests. Context: our blog, with pytest.ini, conftest.py and the existing fixtures. Task: tests for editing and deleting a post, including another user trying to edit the author's post. Format: one new file, short tests that check one behaviour each, using the existing fixtures. Then review the diff: read each test, run it, and break the code once to make sure the test can fail.
Common mistakes
- Forgetting
db. A test (or fixture) that queries the database without it raises an error. - No
DJANGO_SETTINGS_MODULEinpytest.ini. pytest doesn't know which project to start. - Fixing the test instead of reading the failure. Decide first whether the code or the expectation is wrong.
- Expecting a CSRF 403 from the test client. It skips the CSRF check by default.
Quick recap
| Piece | Job |
|---|---|
pytest.ini | points pytest at blogproject.settings, collects test_*.py |
conftest.py | fixtures: author, post, draft, logged_in |
db fixture | database access, in a separate test database rolled back after each test |
client fixture | requests without a server; response.context for the template values |
pytest -v, --durations=3 | 14 passed; the slowest are the login tests |
Try it yourself
Write a test that logs the user out and checks the write page is locked again. Then break the code once and watch the test 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
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.
Getting Started with Django: Models, Views, Templates, the ORM and the Admin
A tiny Django menu app with one model, one view, one URL, one template and the admin. What each file does, how one request travels through them, and the real output of a run.
Your First Django Project and App: uv, startproject, startapp and a First View
Set up a Django project called blogproject with uv, add an app called blog, write one view that returns Hello blog, give it the empty path and run the server. Every command with its real output.
The Django Project Folder Structure, File by File: Reading a Blog an AI Agent Built
A tour of a finished Django blog: manage.py, the project package, the blog app with its models, views, templates, forms and admin, a custom command, the REST API and Swagger docs, plus the review points check --deploy found.
