Django testing with pytest
last modified November 21, 2026 Python 3.15
pytest is a popular alternative to the unittest-based test runner of Django. Tests are plain functions with plain
assert statements, the data they need comes from fixtures, functions that pytest calls and passes in by name, and a
failing assertion shows the values that were compared. The plugin pytest-django connects pytest to Django: it configures the settings,
creates the test database, blocks database access in tests that did not ask for it, and provides fixtures such as a test client. In this
article we test a small library application with pytest-django and create test data with factory_boy. The basics of Django tests, such
as the test client, are explained in Django testing. The examples use Django 6.1, pytest 9.2,
pytest-django 4.14, and Python 3.15.
The example project
The project is created with uv; the steps are explained in Django introduction. The commands below create a
project directory, install Django, install pytest and pytest-django as development dependencies, generate the project with the
configuration package config, start the app books, and create the folder tests for the tests.
Development dependencies are stored in the group dev of pyproject.toml; uv run installs them,
but a production install can leave them out.
$ mkdir library $ cd library $ uv init --bare $ uv add django $ uv add --dev pytest pytest-django $ uv run django-admin startproject config . $ uv run python manage.py startapp books $ mkdir tests
The trailing dot in startproject config . creates manage.py and the config package in the current
directory instead of one level deeper. The new app is added to INSTALLED_APPS in config/settings.py; the other
entries are generated by startproject.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'books',
]
The library has authors and books. The method reading_time() estimates the hours needed to read a book; it contains a bug
that the tests will find.
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
year = models.PositiveSmallIntegerField()
pages = models.PositiveIntegerField()
class Meta:
ordering = ['title']
def __str__(self):
return self.title
def reading_time(self, pages_per_hour=40):
return self.pages // pages_per_hour + 1
We create the migration. The tests do not need the development database: pytest-django creates a test database from the migrations.
$ uv run python manage.py makemigrations books
Migrations for 'books':
books/migrations/0001_initial.py
+ Create model Author
+ Create model Book
Configuring pytest
pytest-django must know the settings module before any test imports a model. We put it into the table [tool.pytest] at
the end of pyproject.toml; the file pytest.ini or the option --ds would work as well. The option
testpaths tells pytest where to look for tests when no path is given. The group dev was added by
uv add --dev.
[project]
name = "library"
version = "0.1.0"
requires-python = ">=3.15"
dependencies = [
"django>=6.1.3",
]
[dependency-groups]
dev = [
"pytest>=9.2.0",
"pytest-django>=4.14.0",
]
[tool.pytest]
DJANGO_SETTINGS_MODULE = "config.settings"
testpaths = ["tests"]
The header of the run shows the Django version and where the settings come from. There are no tests yet. pytest-django also adds
the directory of manage.py to the import path, so the tests can import books and config.
$ uv run pytest ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml testpaths: tests plugins: django-4.14.0 collected 0 items ====================================== no tests ran in 0.04s =======================================
A first test
pytest collects the functions whose names start with test from the modules named test_*.py. A test needs no
class and no special assertion methods: an assert statement is enough. These two tests create a book in memory without
saving it, so they need no database.
from books.models import Book
def test_reading_time():
book = Book(title='Dune', year=1965, pages=412)
assert book.reading_time() == 11
def test_str():
assert str(Book(title='Dune')) == 'Dune'
Each passed test prints a dot after the name of its module.
$ uv run pytest ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml testpaths: tests plugins: django-4.14.0 collected 2 items tests/test_models.py .. [100%] ======================================== 2 passed in 0.02s =========================================
Parametrized tests
One test of reading_time() checks one case. The decorator @pytest.mark.parametrize runs the same test function
with several sets of arguments; every set becomes a separate test with an id built from the values, such as [40-1].
Boundary cases are the interesting ones: exactly 40 pages should take one hour, 41 pages two hours.
import pytest
from books.models import Book
@pytest.mark.parametrize('pages, hours', [
(1, 1),
(40, 1),
(41, 2),
(412, 11),
])
def test_reading_time(pages, hours):
book = Book(title='Dune', year=1965, pages=pages)
assert book.reading_time() == hours
def test_reading_time_with_speed():
book = Book(title='Dune', year=1965, pages=412)
assert book.reading_time(pages_per_hour=100) == 5
def test_str():
assert str(Book(title='Dune')) == 'Dune'
The case with 40 pages fails. pytest rewrites the assert statements, so the report shows both values, and the
where lines show where the left one came from. The other cases pass, so the bug is in the exact multiples of the speed.
$ uv run pytest
======================================= test session starts ========================================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
django: version: 6.1.3, settings: config.settings (from ini)
rootdir: .
configfile: pyproject.toml
testpaths: tests
plugins: django-4.14.0
collected 6 items
tests/test_models.py .F.... [100%]
============================================= FAILURES =============================================
_____________________________________ test_reading_time[40-1] ______________________________________
pages = 40, hours = 1
@pytest.mark.parametrize('pages, hours', [
(1, 1),
(40, 1),
(41, 2),
(412, 11),
])
def test_reading_time(pages, hours):
book = Book(title='Dune', year=1965, pages=pages)
> assert book.reading_time() == hours
E assert 2 == 1
E + where 2 = reading_time()
E + where reading_time = <Book: Dune>.reading_time
tests/test_models.py:14: AssertionError
===================================== short test summary info ======================================
FAILED tests/test_models.py::test_reading_time[40-1] - assert 2 == 1
=================================== 1 failed, 5 passed in 0.05s ====================================
Fixing the bug
Integer division plus one adds an hour too many when the pages divide evenly. We round up with math.ceil() instead. This is
the final version of the model.
import math
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
year = models.PositiveSmallIntegerField()
pages = models.PositiveIntegerField()
class Meta:
ordering = ['title']
def __str__(self):
return self.title
def reading_time(self, pages_per_hour=40):
return math.ceil(self.pages / pages_per_hour)
With -v, pytest prints every test with its id.
$ uv run pytest -v ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python cachedir: .pytest_cache django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml testpaths: tests plugins: django-4.14.0 collecting ... collected 6 items tests/test_models.py::test_reading_time[1-1] PASSED [ 16%] tests/test_models.py::test_reading_time[40-1] PASSED [ 33%] tests/test_models.py::test_reading_time[41-2] PASSED [ 50%] tests/test_models.py::test_reading_time[412-11] PASSED [ 66%] tests/test_models.py::test_reading_time_with_speed PASSED [ 83%] tests/test_models.py::test_str PASSED [100%] ======================================== 6 passed in 0.02s =========================================
Database access
pytest-django blocks the database by default. A test that needs it must say so with the mark @pytest.mark.django_db. Each
such test runs in a transaction that is rolled back at the end, like a test of Django's TestCase, so the next test starts
with an empty database. The first test of this module forgets the mark.
import pytest
from books.models import Author, Book
def test_without_mark():
assert Author.objects.count() == 0
@pytest.mark.django_db
def test_create_books():
author = Author.objects.create(name='Frank Herbert')
Book.objects.create(title='Dune', author=author, year=1965, pages=412)
Book.objects.create(title='Children of Dune', author=author, year=1976, pages=444)
assert [book.title for book in author.books.all()] == ['Children of Dune', 'Dune']
@pytest.mark.django_db
def test_database_is_empty_again():
assert Book.objects.count() == 0
The test without the mark fails with a clear message. It is reported last, because pytest-django reorders the tests: the tests that use the database run first, the others after them, so that the test database is set up only once.
$ uv run pytest tests/test_db.py
======================================= test session starts ========================================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
django: version: 6.1.3, settings: config.settings (from ini)
rootdir: .
configfile: pyproject.toml
plugins: django-4.14.0
collected 3 items
tests/test_db.py ..F [100%]
============================================= FAILURES =============================================
________________________________________ test_without_mark _________________________________________
def test_without_mark():
> assert Author.objects.count() == 0
^^^^^^^^^^^^^^^^^^^^^^
tests/test_db.py:7:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
.venv/lib/python3.15/site-packages/django/db/models/manager.py:87: in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.15/site-packages/django/db/models/query.py:693: in count
return self.query.get_count(using=self.db)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.15/site-packages/django/db/models/sql/query.py:656: in get_count
return obj.get_aggregation(using, {"__count": Count("*")})["__count"]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.15/site-packages/django/db/models/sql/query.py:638: in get_aggregation
result = compiler.execute_sql(SINGLE)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.15/site-packages/django/db/models/sql/compiler.py:1641: in execute_sql
cursor = self.connection.cursor()
^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.15/site-packages/django/utils/asyncio.py:26: in inner
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.15/site-packages/django/db/backends/base/base.py:320: in cursor
return self._cursor()
^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <DatabaseWrapper vendor='sqlite' alias='default'>, name = None
def _cursor(self, name=None):
self.close_if_health_check_failed()
> self.ensure_connection()
E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.
.venv/lib/python3.15/site-packages/django/db/backends/base/base.py:296: RuntimeError
===================================== short test summary info ======================================
FAILED tests/test_db.py::test_without_mark - RuntimeError: Database access not allowed, use the "...
=================================== 1 failed, 2 passed in 0.22s ====================================
The db fixture
Instead of the mark, a test can request the fixture db as an argument; the effect is the same. The fixture is handy when
other fixtures need the database, as we see in the next section. For tests that need real commits, for example of code that uses
transaction.on_commit(), there is the fixture transactional_db and the mark argument
transaction=True.
import pytest
from books.models import Author, Book
def test_with_db_fixture(db):
assert Author.objects.count() == 0
@pytest.mark.django_db
def test_create_books():
author = Author.objects.create(name='Frank Herbert')
Book.objects.create(title='Dune', author=author, year=1965, pages=412)
Book.objects.create(title='Children of Dune', author=author, year=1976, pages=444)
assert [book.title for book in author.books.all()] == ['Children of Dune', 'Dune']
@pytest.mark.django_db
def test_database_is_empty_again():
assert Book.objects.count() == 0
All three tests pass, and the last one confirms that the books of the previous test were rolled back.
$ uv run pytest tests/test_db.py -v ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python cachedir: .pytest_cache django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml plugins: django-4.14.0 collecting ... collected 3 items tests/test_db.py::test_with_db_fixture PASSED [ 33%] tests/test_db.py::test_create_books PASSED [ 66%] tests/test_db.py::test_database_is_empty_again PASSED [100%] ======================================== 3 passed in 0.10s =========================================
Fixtures in conftest.py
Most tests need the same objects. A fixture is a function decorated with @pytest.fixture; a test that names it as an
argument receives its return value. Fixtures in a file called conftest.py are available to all tests in its directory
without an import. A fixture can request other fixtures: herbert requests db, so every test that uses it gets
database access, and dune requests herbert.
import pytest
from books.models import Author, Book
@pytest.fixture
def herbert(db):
return Author.objects.create(name='Frank Herbert')
@pytest.fixture
def dune(herbert):
return Book.objects.create(title='Dune', author=herbert, year=1965, pages=412)
The tests request the fixtures they need. Fixtures have the scope function by default: they are created anew for each
test, which is why the last test may delete the book.
from books.models import Author, Book
def test_author_fixture(herbert):
assert Author.objects.get().name == 'Frank Herbert'
def test_book_fixture(dune, herbert):
assert dune.author == herbert
assert list(herbert.books.all()) == [dune]
def test_fixture_is_created_for_each_test(dune):
dune.delete()
assert not Book.objects.exists()
assert Author.objects.count() == 1
The option --setup-show prints the setup and teardown of every fixture. Its output also lists the many internal fixtures
of pytest-django, so we filter it with grep to our fixtures. There are three groups, one per test, and in each the fixtures
are torn down in the reverse order of their setup.
$ uv run pytest tests/test_fixtures.py -v
======================================= test session starts ========================================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python
cachedir: .pytest_cache
django: version: 6.1.3, settings: config.settings (from ini)
rootdir: .
configfile: pyproject.toml
plugins: django-4.14.0
collecting ... collected 3 items
tests/test_fixtures.py::test_author_fixture PASSED [ 33%]
tests/test_fixtures.py::test_book_fixture PASSED [ 66%]
tests/test_fixtures.py::test_fixture_is_created_for_each_test PASSED [100%]
======================================== 3 passed in 0.11s =========================================
$ uv run pytest tests/test_fixtures.py --setup-show | grep -E "^tests/|(SETUP|TEARDOWN) +F (db|herbert|dune)"
tests/test_fixtures.py
SETUP F db (fixtures used: _django_db_helper)
SETUP F herbert (fixtures used: db)
TEARDOWN F herbert
TEARDOWN F db
SETUP F db (fixtures used: _django_db_helper)
SETUP F herbert (fixtures used: db)
SETUP F dune (fixtures used: herbert)
TEARDOWN F dune
TEARDOWN F herbert
TEARDOWN F db
SETUP F db (fixtures used: _django_db_helper)
SETUP F herbert (fixtures used: db)
SETUP F dune (fixtures used: herbert)
TEARDOWN F dune
TEARDOWN F herbert
TEARDOWN F db
Factories with factory_boy
Fixtures with fixed data multiply quickly: one for a book, one for a book by another author, one for five books. The factory_boy package creates objects from a factory class with default values that every call can override. We install it as another development dependency.
$ uv add --dev factory-boy
A DjangoModelFactory names its model in Meta. Sequence gives each author a unique name, which the
unique constraint of the model requires; Faker generates random but realistic values with the Faker library, which
factory_boy installs; SubFactory creates the related author.
import factory
from books.models import Author, Book
class AuthorFactory(factory.django.DjangoModelFactory):
class Meta:
model = Author
name = factory.Sequence(lambda n: f'Author {n}')
class BookFactory(factory.django.DjangoModelFactory):
class Meta:
model = Book
title = factory.Faker('sentence', nb_words=3)
author = factory.SubFactory(AuthorFactory)
year = factory.Faker('random_int', min=1950, max=2026)
pages = 300
Calling the factory saves the object and its author. build() creates them in memory only, which needs no database.
create_batch() creates several objects; keyword arguments override the defaults for all of them, so the three books share
one author, while the other two get an author each. The tests import the factories as tests.factories, which works because
the project directory is on the import path.
from books.models import Author, Book
from tests.factories import AuthorFactory, BookFactory
def test_build_does_not_save():
book = BookFactory.build(pages=412)
assert book.pk is None
assert book.author.pk is None
assert book.reading_time() == 11
def test_create_saves_book_and_author(db):
book = BookFactory()
assert Book.objects.get() == book
assert Author.objects.get() == book.author
assert 1950 <= book.year <= 2026
def test_batch_with_shared_author(db):
herbert = AuthorFactory(name='Frank Herbert')
BookFactory.create_batch(3, author=herbert)
BookFactory.create_batch(2)
assert herbert.books.count() == 3
assert Author.objects.count() == 3
Faker brings its own pytest plugin, which the header now lists. The test without the database again runs last.
$ uv run pytest tests/test_factories.py -v ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python cachedir: .pytest_cache django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml plugins: Faker-40.63.0, django-4.14.0 collecting ... collected 3 items tests/test_factories.py::test_create_saves_book_and_author PASSED [ 33%] tests/test_factories.py::test_batch_with_shared_author PASSED [ 66%] tests/test_factories.py::test_build_does_not_save PASSED [100%] ======================================== 3 passed in 0.17s =========================================
The client fixture
pytest-django provides Django's test client as the fixture client. We add two views: the list of books and the detail of a
book.
from django.shortcuts import get_object_or_404, render
from .models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'books/book_list.html', {'books': books})
def book_detail(request, pk):
book = get_object_or_404(Book, pk=pk)
return render(request, 'books/book_detail.html', {'book': book})
The app's URLconf names the URLs.
from django.urls import path
from . import views
app_name = 'books'
urlpatterns = [
path('', views.book_list, name='list'),
path('<int:pk>/', views.book_detail, name='detail'),
]
The project includes them under /books/. The admin site is used later in the article.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('books/', include('books.urls')),
]
The list template shows each book with its author.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Books</title>
</head>
<body>
<h1>Books</h1>
<ul>
{% for book in books %}
<li><a href="{% url 'books:detail' book.pk %}">{{ book.title }}</a> by {{ book.author.name }}</li>
{% empty %}
<li>No books yet.</li>
{% endfor %}
</ul>
</body>
</html>
The detail template calls reading_time.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ book.title }}</title>
</head>
<body>
<h1>{{ book.title }}</h1>
<p>{{ book.author.name }}, {{ book.year }}</p>
<p>{{ book.pages }} pages, about {{ book.reading_time }} hours of reading</p>
</body>
</html>
The client does not give database access by itself, so the tests also request db or a fixture that depends on it, such as
dune. Django's assertion methods for responses belong to TestCase; the module
pytest_django.asserts offers them as functions, for example assertContains() and
assertTemplateUsed().
from django.urls import reverse
from pytest_django.asserts import assertContains, assertTemplateUsed
from tests.factories import BookFactory
def test_empty_list(client, db):
response = client.get(reverse('books:list'))
assertContains(response, 'No books yet.')
def test_list(client, dune):
response = client.get(reverse('books:list'))
assertTemplateUsed(response, 'books/book_list.html')
assertContains(response, 'Dune</a> by Frank Herbert')
def test_detail(client, db):
book = BookFactory(title='Dune', pages=412)
response = client.get(reverse('books:detail', args=[book.pk]))
assert response.context['book'] == book
assertContains(response, 'about 11 hours of reading')
def test_missing_book(client, db):
response = client.get(reverse('books:detail', args=[999]))
assert response.status_code == 404
The four tests pass.
$ uv run pytest tests/test_views.py -v ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python cachedir: .pytest_cache django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml plugins: Faker-40.63.0, django-4.14.0 collecting ... collected 4 items tests/test_views.py::test_empty_list PASSED [ 25%] tests/test_views.py::test_list PASSED [ 50%] tests/test_views.py::test_detail PASSED [ 75%] tests/test_views.py::test_missing_book PASSED [100%] ======================================== 4 passed in 0.16s =========================================
Users and admin_client
We register the models in the admin site to test pages that need a logged-in user.
from django.contrib import admin
from .models import Author, Book
admin.site.register(Author)
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'year']
The fixture admin_client is a client logged in as a superuser, which the fixture admin_user creates with
the user name admin. For other users, the fixture django_user_model returns the active user model, also a
custom one, and force_login() logs the user in. A user without staff status is redirected from the admin like an anonymous
one.
from django.urls import reverse
from pytest_django.asserts import assertContains, assertRedirects
def test_anonymous_user(client, db):
url = reverse('admin:books_book_changelist')
response = client.get(url)
assertRedirects(response, f"{reverse('admin:login')}?next={url}")
def test_superuser(admin_client, dune):
response = admin_client.get(reverse('admin:books_book_changelist'))
assertContains(response, 'Frank Herbert')
def test_user_without_staff_status(client, django_user_model):
user = django_user_model.objects.create_user('alice')
client.force_login(user)
response = client.get(reverse('admin:books_book_changelist'))
assert response.status_code == 302
def test_admin_user_fixture(admin_user):
assert admin_user.username == 'admin'
assert admin_user.is_superuser
The redirect of the anonymous user is checked together with the status of the login page.
$ uv run pytest tests/test_admin.py -v ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python cachedir: .pytest_cache django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml plugins: Faker-40.63.0, django-4.14.0 collecting ... collected 4 items tests/test_admin.py::test_anonymous_user PASSED [ 25%] tests/test_admin.py::test_superuser PASSED [ 50%] tests/test_admin.py::test_user_without_staff_status PASSED [ 75%] tests/test_admin.py::test_admin_user_fixture PASSED [100%] ======================================== 4 passed in 0.61s =========================================
Counting queries
The fixture django_assert_num_queries fails a test when the code in its with block runs a different number of
queries; django_assert_max_num_queries sets only an upper limit. Such tests protect a page against the N+1 problem,
explained in Django query performance. With factories, five books with five authors take one
line.
from django.urls import reverse
from tests.factories import BookFactory
def test_list_queries(client, db, django_assert_num_queries):
BookFactory.create_batch(5)
with django_assert_num_queries(1):
response = client.get(reverse('books:list'))
assert len(response.context['books']) == 5
def test_detail_queries(client, dune, django_assert_max_num_queries):
with django_assert_max_num_queries(2):
client.get(reverse('books:detail', args=[dune.pk]))
The list page fails: one query for the books and one more for the author of each book. With -v the message lists the
queries, and --tb=short shortens the traceback.
$ uv run pytest tests/test_queries.py -v --tb=short
======================================= test session starts ========================================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python
cachedir: .pytest_cache
django: version: 6.1.3, settings: config.settings (from ini)
rootdir: .
configfile: pyproject.toml
plugins: Faker-40.63.0, django-4.14.0
collecting ... collected 2 items
tests/test_queries.py::test_list_queries FAILED [ 50%]
tests/test_queries.py::test_detail_queries PASSED [100%]
============================================= FAILURES =============================================
________________________________________ test_list_queries _________________________________________
tests/test_queries.py:8: in test_list_queries
with django_assert_num_queries(1):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/home/user/.local/share/uv/python/cpython-3.15.2-linux-x86_64-gnu/lib/python3.15/contextlib.py:210: in __exit__
next(self.gen)
.venv/lib/python3.15/site-packages/pytest_django/fixtures.py:727: in _assert_num_queries
pytest.fail(msg)
E Failed: Expected to perform 1 queries but 6 were done
E
E Queries:
E ========
E
E SELECT "books_book"."id", "books_book"."title", "books_book"."author_id", "books_book"."year", "books_book"."pages" FROM "books_book" ORDER BY "books_book"."title" ASC
E
E SELECT "books_author"."id", "books_author"."name" FROM "books_author" WHERE "books_author"."id" = 1 LIMIT 21
E
E SELECT "books_author"."id", "books_author"."name" FROM "books_author" WHERE "books_author"."id" = 2 LIMIT 21
E
E SELECT "books_author"."id", "books_author"."name" FROM "books_author" WHERE "books_author"."id" = 5 LIMIT 21
E
E SELECT "books_author"."id", "books_author"."name" FROM "books_author" WHERE "books_author"."id" = 4 LIMIT 21
E
E SELECT "books_author"."id", "books_author"."name" FROM "books_author" WHERE "books_author"."id" = 3 LIMIT 21
-------------------------------------- Captured stderr setup ---------------------------------------
Creating test database for alias 'default'...
===================================== short test summary info ======================================
FAILED tests/test_queries.py::test_list_queries - Failed: Expected to perform 1 queries but 6 wer...
=================================== 1 failed, 1 passed in 0.19s ====================================
Fixing the N+1 problem
select_related('author') loads the authors with the books in one query with a join.
from django.shortcuts import get_object_or_404, render
from .models import Book
def book_list(request):
books = Book.objects.select_related('author')
return render(request, 'books/book_list.html', {'books': books})
def book_detail(request, pk):
book = get_object_or_404(Book, pk=pk)
return render(request, 'books/book_detail.html', {'book': book})
Both query tests pass.
$ uv run pytest tests/test_queries.py -v ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python cachedir: .pytest_cache django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml plugins: Faker-40.63.0, django-4.14.0 collecting ... collected 2 items tests/test_queries.py::test_list_queries PASSED [ 50%] tests/test_queries.py::test_detail_queries PASSED [100%] ======================================== 2 passed in 0.15s =========================================
Settings and mailoutbox
The fixture settings changes settings for one test and restores them afterwards, like Django's
override_settings. The test client sends the host testserver, which the test environment normally adds to
ALLOWED_HOSTS; once the test replaces the list, the request is refused with status 400 unless it sends an allowed
Host header. The test environment also turns DEBUG off. The fixture mailoutbox is the list of
messages sent during the test, the same as Django's mail.outbox.
from django.conf import settings
from django.core.mail import send_mail
from django.urls import reverse
def test_debug_is_off():
assert settings.DEBUG is False
def test_allowed_hosts(client, db, settings):
settings.ALLOWED_HOSTS = ['books.example.com']
url = reverse('books:list')
assert client.get(url).status_code == 400
assert client.get(url, headers={'host': 'books.example.com'}).status_code == 200
def test_original_settings_are_back(client, db):
assert client.get(reverse('books:list')).status_code == 200
def test_mailoutbox(mailoutbox):
send_mail('New book', 'Dune is in stock.', None, ['reader@example.com'])
assert len(mailoutbox) == 1
assert mailoutbox[0].subject == 'New book'
The second test sees the original ALLOWED_HOSTS again.
$ uv run pytest tests/test_settings.py -v ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python cachedir: .pytest_cache django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml plugins: Faker-40.63.0, django-4.14.0 collecting ... collected 4 items tests/test_settings.py::test_allowed_hosts PASSED [ 25%] tests/test_settings.py::test_original_settings_are_back PASSED [ 50%] tests/test_settings.py::test_debug_is_off PASSED [ 75%] tests/test_settings.py::test_mailoutbox PASSED [100%] ======================================== 4 passed in 0.14s =========================================
Django test classes
pytest also runs tests written for Django's runner, so a project can move to pytest without rewriting its old tests. The module
books/tests.py, generated by startapp, gets a TestCase.
from django.test import TestCase
from books.models import Author
class AuthorTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.author = Author.objects.create(name='Ursula K. Le Guin')
def test_str(self):
self.assertEqual(str(self.author), 'Ursula K. Le Guin')
def test_no_books(self):
self.assertEqual(self.author.books.count(), 0)
pytest does not collect tests.py by default, because the name does not match test_*.py. We add the pattern to
python_files and the app directory to testpaths.
[project]
name = "library"
version = "0.1.0"
requires-python = ">=3.15"
dependencies = [
"django>=6.1.3",
]
[dependency-groups]
dev = [
"factory-boy>=3.3.3",
"pytest>=9.2.0",
"pytest-django>=4.14.0",
]
[tool.pytest]
DJANGO_SETTINGS_MODULE = "config.settings"
testpaths = ["tests", "books"]
python_files = ["test_*.py", "tests.py"]
The methods of the class run as pytest tests, with setUpTestData() and the transactions of TestCase.
$ uv run pytest books/tests.py -v ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- ./.venv/bin/python cachedir: .pytest_cache django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml plugins: Faker-40.63.0, django-4.14.0 collecting ... collected 2 items books/tests.py::AuthorTests::test_no_books PASSED [ 50%] books/tests.py::AuthorTests::test_str PASSED [100%] ======================================== 2 passed in 0.12s =========================================
Selecting tests
The option -k selects tests by a part of the name, and a node id, a path with :: and the name of a function,
selects one test with all its parameter sets. Other useful options are -x, which stops at the first failure, and
--lf, which reruns only the tests that failed last time.
$ uv run pytest -k reading_time ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml testpaths: tests, books plugins: Faker-40.63.0, django-4.14.0 collected 31 items / 26 deselected / 5 selected tests/test_models.py ..... [100%] ================================= 5 passed, 26 deselected in 0.06s ================================= $ uv run pytest tests/test_models.py::test_reading_time ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml plugins: Faker-40.63.0, django-4.14.0 collected 4 items tests/test_models.py .... [100%] ======================================== 4 passed in 0.04s =========================================
Running the whole suite
The tests now live in two places. A plain pytest runs all 31 of them; the reordering puts the database tests first, so
some modules appear twice. --durations lists the slowest steps: the setup of the admin tests, because creating the
superuser hashes its password. Django's own runner, manage.py test, still works, but it finds only the two tests of the
TestCase class; plain test functions and fixtures exist only for pytest.
$ tree -I "__pycache__|migrations|db.sqlite3" --noreport books tests books ├── admin.py ├── apps.py ├── __init__.py ├── models.py ├── templates │ └── books │ ├── book_detail.html │ └── book_list.html ├── tests.py ├── urls.py └── views.py tests ├── conftest.py ├── factories.py ├── test_admin.py ├── test_db.py ├── test_factories.py ├── test_fixtures.py ├── test_models.py ├── test_queries.py ├── test_settings.py └── test_views.py $ uv run pytest ======================================= test session starts ======================================== platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 django: version: 6.1.3, settings: config.settings (from ini) rootdir: . configfile: pyproject.toml testpaths: tests, books plugins: Faker-40.63.0, django-4.14.0 collected 31 items tests/test_admin.py .... [ 12%] tests/test_db.py ... [ 22%] tests/test_factories.py .. [ 29%] tests/test_fixtures.py ... [ 38%] tests/test_queries.py .. [ 45%] tests/test_settings.py .. [ 51%] tests/test_views.py .... [ 64%] books/tests.py .. [ 70%] tests/test_factories.py . [ 74%] tests/test_models.py ...... [ 93%] tests/test_settings.py .. [100%] ======================================== 31 passed in 0.67s ======================================== $ uv run pytest --durations=3 -q ............................... [100%] ======================================= slowest 3 durations ======================================== 0.25s setup tests/test_admin.py::test_admin_user_fixture 0.23s setup tests/test_admin.py::test_superuser 0.10s setup tests/test_admin.py::test_anonymous_user 31 passed in 0.71s $ uv run python manage.py test Found 2 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). .. ---------------------------------------------------------------------- Ran 2 tests in 0.002s OK Destroying test database for alias 'default'...
Source
Django documentation: Testing in Django
In this article we have tested a Django project with pytest and pytest-django: we have configured the settings module in
pyproject.toml, written plain and parametrized tests, enabled the database with the django_db mark and the
db fixture, shared objects through fixtures in conftest.py, created test data with factory_boy, tested views
with the client and admin_client fixtures, counted queries, changed settings, checked email with
mailoutbox, and run Django's TestCase classes with pytest. Related articles are
Django testing, Django query performance, and
Django admin site.
Author
List all Django tutorials.