Test driven development in Django: pytest, factories and a real workflow
TL;DR
Difficulty: Intermediate
Write the fastest test that can fail for the right reason, and read every red message before you write code.
- Django's unittest style ships with Django. pytest with pytest django adds plain functions, fixtures, parametrised tables and no database unless a test asks. pytest runs Django's test classes unchanged, so the choice is easy to reverse.
- Use factory_boy for test data, and declare factories so their rows agree with each other.
- Fake the clock with time machine or freezegun and outside HTTP with responses. Pin query counts at two sizes.
- The worked example: a repair price with VAT and a booking overlap rule, built test first in small cycles, ending in a PostgreSQL exclusion constraint.
Most TDD tutorials stop at a function that adds two numbers. This one builds two real rules of a Limerick bicycle repair chain's booking system test first in Django 5.0, one small cycle at a time, and compares unittest with pytest fairly along the way.
The question behind this chapter
"How do I actually do test driven development in Django, step by step, and should I use unittest or pytest?" Most answers to that question stop at the first half. They show a test for a function that adds two numbers, say "now write the code", and leave you alone with a real model, a real database and a real deadline.
This chapter does the second half: two real rules, built one small step at a time, with the test and the code at every step. Along the way it compares Django's built in testing with pytest and pytest django from their own documentation, and covers what makes or breaks a suite in practice: test data, time, outside services, query counts and parallel runs.
The example is the one this whole programme uses, and it is invented. Freewheel Cycles runs six bicycle repair workshops around Limerick (freewheelcycles.example): 38 mechanics, about 1,150 repair bookings a week, 9,000 active customers and 2,400 spare parts in stock. Its founder Niamh wanted her spreadsheets and a rented booking widget replaced by an application of her own. Her developers Aisling and Cian built a two week spike of the core in both frameworks before choosing. This is the Django version of the spike. The Rails chapter test driven development in Rails walks through exactly the same two rules with Minitest, so you can lay the two side by side.
If the words TDD, unit test or test double are new to you, read the testing map for web applications first. The models used here come from the Django ORM chapter.
Everything here is written for Django 5.0 (5.0.6 is the current patch release, from 7 May 2024)1 and Python 3.12, on PostgreSQL, with pytest 8.2 and pytest django 4.823.
The one idea: the fastest test that fails for the right reason
Test driven development (TDD) comes from Kent Beck's book Test Driven Development: By Example (2002)4. The cycle is short. Write a small test for behaviour that does not exist yet and watch it fail (red). Write the least code that makes it pass (green). Then improve the code's design while every test stays green (refactor). Repeat, in steps of a few minutes.
Two words in that description carry more weight than they seem to, and they are where Django projects go wrong.
The first is fail. A red test is only useful if it fails for the reason you meant. A test that fails because a module does not exist, a table is missing or a related row was never saved has told you nothing about your rule. Worse, a test can pass before you write any code at all, because something else in the setup raises the very error you were waiting for. You will see that happen in the booking example below. So my first rule is: read every red message, and only move on when it names the behaviour you are about to build.
The second is small. Django offers several kinds of test, and they differ in cost by orders of magnitude. A plain function call takes microseconds. A test that touches the database runs inside a transaction that is rolled back afterwards. A test that needs real commits has every table emptied after it. A test in a real browser starts a server and a browser. If the cycle is to stay a few minutes long, each test has to sit on the lowest rung that can still prove the behaviour.
Put the two together and you get the idea I want you to keep from this chapter: write the fastest test that can fail for the right reason. Not the most realistic one, not the most isolated one. The fastest one that can tell you, truthfully, that the behaviour is missing.
Here is the ladder, from the Django testing tools documentation5 and the pytest django documentation6. The timings are illustrative orders of magnitude on a laptop, not measurements.
| Rung | Django class | pytest django | What it can prove | Illustrative cost per test |
|---|---|---|---|---|
| 1. No database | SimpleTestCase (database queries are refused) | A plain test function, no mark | Pure logic: prices, rounding, parsing | well under 1 ms |
| 2. Database, rolled back | TestCase (each test inside a transaction that is rolled back) | @pytest.mark.django_db or the db fixture | Models, constraints, queries, views through the test client | about 5 to 30 ms |
| 3. Real commits | TransactionTestCase (tables emptied after each test) | django_db(transaction=True) or transactional_db | Code that must see a real commit, such as on_commit running for real or locks | about 50 to 200 ms |
| 4. Real browser | StaticLiveServerTestCase with a browser driver | live_server with a browser | Journeys, JavaScript, htmx in a page | about 1 to 5 s |
The documentation itself points in this direction. It tells you to use SimpleTestCase if your code does not touch the database, and explains that TestCase uses transactions to reset the database because that is faster than emptying tables5. pytest django goes one step further by default: a test that does not ask for the database is refused access to it6. That default is the ladder, built into the tool.
Example: where Freewheel's first tests sit on the ladder
Aisling lists the first behaviours of the spike and puts each on the lowest rung that can prove it.
| Behaviour | Lowest rung that can fail for the right reason | Why not lower |
|---|---|---|
| The price of a repair, with VAT | 1, no database | It is arithmetic on numbers |
| A booking cannot overlap another for the same mechanic | 2, rolled back | It needs other bookings in the database |
| The workshop board runs a fixed number of queries | 2, rolled back | It needs rows and the test client |
| "Your bike is ready" is queued only after commit | 2, rolled back, with captured commit callbacks | Django can capture on_commit callbacks inside a TestCase5 |
| Two mechanics dragging the same card at once | 3, real commits | Row locks only mean something across real transactions |
| A customer books a slot in the browser | 4, browser | The journey is the behaviour |
Only one behaviour needs rung 3, and only one needs a browser, which belongs to the next chapter in this series. Everything here lives on rungs 1 and 2.
What Django gives you out of the box
Django's testing documentation is plain about its default: the preferred way to write tests in Django is with the unittest module from the Python standard library7. You write classes that inherit from one of Django's test case classes, put them in files whose names start with test, and run them with python manage.py test. Django finds them with unittest's own discovery, creates a separate test database, runs everything and destroys the database again7.
The classes form a ladder of their own5:
SimpleTestCaseadds useful assertions (for HTML, redirects, templates, form errors), the test client and settings overrides, and refuses database queries by default.TransactionTestCaseadds the database and resets it by emptying all tables after each test.TestCase, the one you will use most, wraps each test in two nestedatomic()blocks, one for the class and one for the test, and rolls them back. It addssetUpTestData(), which creates data once for the whole class instead of before every test, andcaptureOnCommitCallbacks(), which collects functions registered withtransaction.on_commit()so you can assert on them or run them.LiveServerTestCaseandStaticLiveServerTestCasestart a real server for browser tests.
The documentation also names the trade off honestly: because TestCase wraps everything in a transaction, some behaviour cannot be tested there. Its own example is code that must run inside a transaction, as select_for_update() requires. For that, use TransactionTestCase5.
Three tools in the box matter for daily TDD:
- The test client (
self.client) sends requests to your URLs without a server and gives you the response, the template context and the templates used5. assertNumQueries(n)fails if a block of code runs any number of database queries other thann5.- The test command's options8:
--parallelruns test classes in several processes,--shufflerandomises the order to catch tests that depend on each other,--keepdbkeeps the test database between runs, and, new in Django 5.0,--durations Nlists the N slowest tests on Python 3.12 or later9.
Example: Freewheel's first test, unittest style
Before any rule, Aisling writes the smallest test that proves the project is wired together: a logged in mechanic can open the workshop board. It is the board from the ORM chapter.
# repairs/tests/test_board.py
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from workshops.models import Mechanic, Workshop
class BoardTest(TestCase):
@classmethod
def setUpTestData(cls):
# Created once for the whole class, rolled back at the end.
cls.workshop = Workshop.objects.create(name="Castletroy", city="Limerick")
user = get_user_model().objects.create_user(username="darragh", password="x")
cls.mechanic = Mechanic.objects.create(
user=user, workshop=cls.workshop, display_name="Darragh"
)
def test_a_mechanic_can_open_the_board(self):
self.client.force_login(self.mechanic.user)
response = self.client.get(reverse("repairs:board", args=[self.workshop.id]))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "repairs/board.html")
python manage.py test repairs
Nothing here needs a third party package, and every Django developer can read it.
pytest and pytest django: the same tests with less ceremony
pytest is a separate test framework for Python, at version 8.2.2 at the time of writing2. pytest django is a plugin that teaches it about Django: it finds your settings, creates the test database, and gives you Django's tools as fixtures3. Its documentation gives its reasons: less boilerplate, fixtures for test dependencies, parallel runs, many plugins, and existing unittest style tests keep working unchanged3.
Three pytest ideas change how tests read.
Plain assert. You write assert price.vat == Decimal("17.00") instead of self.assertEqual(...). When it fails, pytest shows both values.
Fixtures. A pytest fixture is a function that prepares something a test needs. A test asks for it by naming it as a parameter, and pytest calls the fixture and passes in the result10. Fixtures can use other fixtures, can clean up after themselves with yield, and can be shared across files from a conftest.py. This is dependency injection: the test says what it needs, not how to build it.
Parametrisation. @pytest.mark.parametrize runs one test function once for every row of a table of inputs and expected results11. Each row is reported as its own test.
pytest django then adds the Django parts as fixtures and marks6:
@pytest.mark.django_dbgives a test the database, with the same rollback behaviour asTestCase. Withtransaction=Trueit behaves likeTransactionTestCase. Thedbandtransactional_dbfixtures do the same from inside other fixtures.clientandadmin_clientare Django's test client, the second logged in as a superuser.settingslets a test change a setting and puts it back afterwards.django_assert_num_queriesisassertNumQueriesas a fixture.django_capture_on_commit_callbacksiscaptureOnCommitCallbacksas a fixture.mailoutboxis the list of emails sent during the test.
And one command line option saves time on every run: --reuse-db keeps the test database between runs. The documentation warns that it does not pick up schema changes, so you add --create-db once after a migration12.
Example: the same board test, pytest style
Aisling installs the test dependencies. These are the current releases on PyPI at the time of writing:
python -m pip install "pytest==8.2.2" "pytest-django==4.8.0" "factory-boy==3.3.0" \
"time-machine==2.14.1" "responses==0.25.2" "pytest-xdist==3.6.1"
She points pytest at the settings in pyproject.toml, as the pytest django tutorial shows3:
# pyproject.toml
[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "freewheel.settings"
python_files = ["tests.py", "test_*.py"]
addopts = "--reuse-db"
Then the test:
# repairs/tests/test_board.py
import pytest
from django.urls import reverse
@pytest.mark.django_db
def test_a_mechanic_can_open_the_board(client, mechanic):
client.force_login(mechanic.user)
response = client.get(reverse("repairs:board", args=[mechanic.workshop_id]))
assert response.status_code == 200
assert "repairs/board.html" in [t.name for t in response.templates]
The mechanic parameter is a fixture. It lives in a conftest.py that every test file can use, and it is built with a factory, which the section on test data explains:
# conftest.py (at the project root)
import pytest
from tests.factories import MechanicFactory
@pytest.fixture
def mechanic(db):
# Asking for "db" gives this fixture the database.
return MechanicFactory(display_name="Darragh", workshop__name="Castletroy")
pytest repairs
The test is shorter, and its setup has a name.
unittest or pytest: what actually differs
Both run on the same Django test database machinery. Both can do everything in this chapter. The differences are in how tests read, how setup is shared and what is installed.
| Question | Django's unittest style | pytest with pytest django |
|---|---|---|
| Installed with Django | Yes, nothing to add | No, two packages to install and keep updated |
| A test is | A method on a class | A plain function, or a method on a plain class |
| Assertions | self.assertEqual, assertContains, assertRedirects and many more | Plain assert, and Django's assertions are still available through pytest_django.asserts |
| Shared setup | setUp, setUpTestData, class inheritance | Fixtures, requested by name, shared through conftest.py |
| Same test, many inputs | A loop, or subTest | @pytest.mark.parametrize, one reported test per row |
| Database access | Chosen by base class | Refused unless the test asks for it |
| Parallel runs | manage.py test --parallel, by test class | pytest -n with pytest xdist, by test |
| Slowest tests | --durations N (Django 5.0, Python 3.12) | --durations N |
| Runs the other style's tests | No | Yes, unittest classes run unchanged |
The last row is the one most comparisons miss, and it changes the decision. pytest runs unittest based tests out of the box, including setUp, setUpClass and skip decorators13. pytest django says the same for Django's test classes3. So switching to pytest does not mean rewriting the suite. The limits run the other way: inside a unittest.TestCase class, pytest fixtures (other than autouse ones) and parametrisation do not work, and the pytest documentation says they probably never will13.
That gives a simple asymmetry. Choosing pytest is reversible in practice, because nothing you already have stops working. Choosing unittest keeps you on the smaller feature set for new tests until you choose again. The cost of pytest is two more dependencies to keep up to date, and a second vocabulary for new team members.
A word on a word: "fixture" means two different things in Django projects. In Django's documentation, a fixture is a file of data (usually JSON) loaded into the test database5. In pytest, a fixture is a function that prepares anything a test needs. Most confusion in mixed teams starts there. In this chapter, "fixture file" means the first and "fixture" means the second.
Example: why Aisling and Cian chose pytest
Aisling has four years of Python, mostly data analysis, and she has written pytest tests before. Cian comes from JavaScript and TypeScript, where Jest and Vitest tests are plain functions with expect, so pytest's plain functions read naturally to him. Neither has written a unittest class in anger.
They write down the decision and its exit: pytest with pytest django, plain functions for new tests, and Django's TestCase classes allowed where setUpTestData saves real time on a slow set of data. If pytest ever becomes a burden, the same tests can be moved back class by class.
My view: for a new Django project, I would choose pytest with pytest django, for the parametrisation and the fixtures, and because the default of refusing the database pushes tests down the ladder. For a team that already has a large, healthy unittest suite, I would not migrate it for its own sake. Run it with pytest and write new tests in the new style. And for a small project or a library that wants zero extra dependencies, Django's own runner is a perfectly sound choice. The Django documentation does not take sides here, and nor should a reviewer.
Test data: factory_boy or fixture files
Every database test needs rows. There are two classic ways to make them.
Fixture files. You export rows with manage.py dumpdata, store the JSON in a fixtures folder, and name it in the test class's fixtures attribute. TestCase loads fixture files once per class5. They are quick to load and easy to make from real data. Their weakness is distance: the facts a test depends on sit in a file far from the test, and every new test bends the shared file a little further. Django's own documentation says it plainly: tests are more readable and more maintainable when you create objects with the ORM, for example in setUpTestData()5.
Factories. factory_boy, at version 3.3.014, lets you declare once how to build a valid object of each model, and then build one in a single line, overriding only the fields the test cares about. It was originally designed for Django, and its DjangoModelFactory saves objects with the model manager's create()14. Factories have two strategies: create() saves to the database, build() makes an object in memory only15. Related objects come from SubFactory, and SelfAttribute copies a value from elsewhere in the object being built, including from the parent with a double dot, as in "..customer"16.
Factories have a cost the tutorials rarely mention: every factory call is a small tree of INSERT statements, and the tree is invisible in the test. A booking needs a workshop, a mechanic with a user, a customer and a bike. One innocent BookingFactory() writes six rows. A test that makes fifty bookings writes three hundred. And if the factory is declared carelessly, some of those rows contradict each other.
Example: Freewheel's factories, and the booking at the wrong workshop
Cian's first BookingFactory gave every foreign key its own SubFactory. It worked, and every test passed. Then Aisling wrote a test for the board at the Castletroy workshop and found a booking whose mechanic worked at a different workshop, and a bike that belonged to a different customer. Each SubFactory had built its own workshop and its own customer: eight rows per booking, two of them describing a world that cannot exist.
The fix is SelfAttribute. The booking's workshop is copied from its mechanic, and the bike is built for the booking's own customer:
# tests/factories.py
import datetime as dt
from zoneinfo import ZoneInfo
import factory
from django.utils import timezone
LIMERICK = ZoneInfo("Europe/Dublin")
def next_saturday_at_nine():
today = timezone.localdate()
days_ahead = (5 - today.weekday()) % 7 or 7 # Monday is 0, Saturday is 5
day = today + dt.timedelta(days=days_ahead)
return dt.datetime(day.year, day.month, day.day, 9, 0, tzinfo=LIMERICK)
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = "accounts.User"
username = factory.Sequence(lambda n: f"user{n}")
class WorkshopFactory(factory.django.DjangoModelFactory):
class Meta:
model = "workshops.Workshop"
name = factory.Sequence(lambda n: f"Workshop {n}")
city = "Limerick"
class MechanicFactory(factory.django.DjangoModelFactory):
class Meta:
model = "workshops.Mechanic"
user = factory.SubFactory(UserFactory)
workshop = factory.SubFactory(WorkshopFactory)
display_name = factory.Sequence(lambda n: f"Mechanic {n}")
class CustomerFactory(factory.django.DjangoModelFactory):
class Meta:
model = "bookings.Customer"
name = factory.Sequence(lambda n: f"Customer {n}")
email = factory.Sequence(lambda n: f"customer{n}@example.test")
class BikeFactory(factory.django.DjangoModelFactory):
class Meta:
model = "bookings.Bike"
customer = factory.SubFactory(CustomerFactory)
make = "Raleigh"
class BookingFactory(factory.django.DjangoModelFactory):
class Meta:
model = "bookings.Booking"
mechanic = factory.SubFactory(MechanicFactory)
# The booking happens where the mechanic works, never at a second workshop.
workshop = factory.SelfAttribute("mechanic.workshop")
customer = factory.SubFactory(CustomerFactory)
# The bike belongs to this booking's customer, never to a stranger.
bike = factory.SubFactory(BikeFactory, customer=factory.SelfAttribute("..customer"))
starts_at = factory.LazyFunction(next_saturday_at_nine)
ends_at = factory.LazyAttribute(lambda booking: booking.starts_at + dt.timedelta(hours=1))
class JobCardFactory(factory.django.DjangoModelFactory):
class Meta:
model = "repairs.JobCard"
booking = factory.SubFactory(BookingFactory)
status = "waiting"
Now BookingFactory() writes six rows, all consistent: a user, a workshop, a mechanic, a customer, a bike and the booking. A test can still say exactly what it cares about, for example BookingFactory(mechanic=daniel, starts_at=nine), or reach deeper with double underscores, such as JobCardFactory(booking__customer__name="Ann").
My view: factories for everything a test is about, fixture files only for reference data that never changes between tests (a list of countries, say). Keep the factory defaults minimal and valid, put the facts a test depends on into the test itself, and treat the row count of a factory as a performance budget. When a set of rows is expensive and shared by many tests in one file, build it once with a module or class scoped fixture or setUpTestData, not once per test.
The walk through, part one: a booking cannot overlap another
Now the real thing, and in the same order as the Rails chapter, so you can lay the two walk throughs side by side, cycle by cycle. In the ORM chapter, every booking was one fixed slot, and a unique constraint on mechanic and start time was enough. Then Niamh introduced repairs of different lengths: a full service takes 90 minutes, a puncture 30. Now a 9.30am booking can collide with a 9am one that runs until 10am. The rule becomes: a mechanic cannot be booked for two repairs at the same time.
Before any code, Aisling writes the test list, as Kent Beck recommends4. It is the same list as in the Rails chapter:
- A booking that starts while another one runs, for the same mechanic, is refused.
- Back to back bookings are fine: one ends at 10am, the next starts at 10am.
- A different mechanic at the same time is fine.
- A cancelled booking does not block the slot.
- Moving an existing booking by 15 minutes does not clash with itself.
- Two requests at the same moment cannot both win.
This sits on rung 2. Each test needs a saved booking to collide with, and the new booking is checked with full_clean(), the method a form calls. One small helper keeps the tests readable: it makes an unsaved booking that reuses the saved workshop, mechanic, customer and bike of an existing one.
# bookings/tests/helpers.py
import datetime as dt
from bookings.models import Booking
from tests.factories import LIMERICK
def at(hour, minute=0):
"""Saturday 8 June 2024 at the given time in Limerick."""
return dt.datetime(2024, 6, 8, hour, minute, tzinfo=LIMERICK)
def candidate(existing, starts_at, ends_at, **changes):
"""An unsaved booking whose related rows already exist in the database."""
fields = {
"workshop": existing.workshop,
"mechanic": existing.mechanic,
"customer": existing.customer,
"bike": existing.bike,
"starts_at": starts_at,
"ends_at": ends_at,
}
fields.update(changes)
return Booking(**fields)
Example: cycle 1, the overlap is refused, and a test that passed too early
Cian's first attempt at the test used the factory's build() strategy for the new booking:
# bookings/tests/test_overlap.py (first attempt, do not copy)
def test_an_overlapping_booking_is_refused():
first = BookingFactory(starts_at=at(9), ends_at=at(10))
second = BookingFactory.build(mechanic=first.mechanic, starts_at=at(9, 30), ends_at=at(10, 30))
with pytest.raises(ValidationError):
second.full_clean()
He ran it before writing any code, and it passed. A test that passes before the behaviour exists is lying to you. The reason: build() pushes its strategy down to the related factories15, so the new booking's customer and bike were built in memory and never saved. full_clean() raised a ValidationError because those fields were empty, not because of any overlap. The right error for the wrong reason.
The fix is to say exactly which error is expected, and to build the candidate from saved rows:
# bookings/tests/test_overlap.py
import pytest
from django.core.exceptions import ValidationError
from bookings.models import OVERLAP
from bookings.tests.helpers import at, candidate
from tests.factories import BookingFactory
pytestmark = pytest.mark.django_db # every test in this file may use the database
def test_a_booking_that_starts_while_another_runs_for_the_same_mechanic_is_refused():
first = BookingFactory(starts_at=at(9), ends_at=at(10))
clash = candidate(first, at(9, 30), at(10, 30))
with pytest.raises(ValidationError) as excinfo:
clash.full_clean()
# Exactly one error, and it is ours. Nothing else may be wrong with the row.
assert excinfo.value.message_dict == {"__all__": [OVERLAP]}
Aisling adds the message to bookings/models.py as a module constant, so the test can import it. Her prediction before the run: "fails, because nothing raises yet". The run says Failed: DID NOT RAISE <class 'django.core.exceptions.ValidationError'>. That is the right red. Now the least code that passes, and Beck's advice for this moment is to be shameless4:
# bookings/models.py
from django.core.exceptions import ValidationError
OVERLAP = "This mechanic already has a booking at that time."
class Booking(models.Model):
# ... fields as in the ORM chapter ...
def clean(self):
# Deliberately too simple: any other booking for this mechanic counts as a clash.
if Booking.objects.filter(mechanic_id=self.mechanic_id).exists():
raise ValidationError(OVERLAP)
Green. The code is wrong, and everybody at the desk knows it. The next test on the list will prove it wrong, so the real logic arrives because a test demanded it, not because someone guessed. Errors raised in clean() are collected under the key "__all__", which is how Django marks errors that belong to the whole object rather than one field17.
Example: cycle 2, back to back bookings are fine
def test_a_booking_may_start_the_minute_the_previous_one_ends():
first = BookingFactory(starts_at=at(9), ends_at=at(10))
next_one = candidate(first, at(10), at(11))
next_one.full_clean() # must not raise
Prediction: "fails with the overlap message, because the fake rule refuses any second booking". The run says ValidationError: {'__all__': ['This mechanic already has a booking at that time.']}. Correct red. Two time ranges overlap when each one starts before the other ends. With the end time exclusive, as Niamh confirmed, that is two strict comparisons:
def clean(self):
clash = Booking.objects.filter(
mechanic_id=self.mechanic_id,
starts_at__lt=self.ends_at,
ends_at__gt=self.starts_at,
)
if clash.exists():
raise ValidationError(OVERLAP)
Both tests pass.
Example: cycle 3, another mechanic, and a test that never went red
def test_another_mechanic_can_be_booked_at_the_same_time():
first = BookingFactory(starts_at=at(9), ends_at=at(10))
colleague = candidate(first, at(9), at(10), mechanic=MechanicFactory(workshop=first.workshop))
colleague.full_clean()
(MechanicFactory joins the imports from tests.factories.) Prediction: "passes already, because the query filters by mechanic". It does. That is honest TDD too: sometimes the code you wrote for one test already covers the next. But never trust a test you have not seen fail. Cian comments out the mechanic_id=self.mechanic_id line for a moment, watches this test go red with the overlap message, and puts the line back. Now the test is known to guard that line.
Example: cycle 4, a cancelled booking frees the slot
from django.utils import timezone
def test_a_cancelled_booking_does_not_block_the_slot():
first = BookingFactory(starts_at=at(9), ends_at=at(10), cancelled_at=timezone.now())
candidate(first, at(9), at(10)).full_clean()
Prediction: "fails with the overlap message, because cancelled rows still count". Correct. Green: one more filter, cancelled_at__isnull=True.
Example: cycle 5, moving a booking does not clash with itself
import datetime as dt
def test_moving_a_booking_by_15_minutes_does_not_clash_with_itself():
booking = BookingFactory(starts_at=at(9), ends_at=at(10))
booking.starts_at += dt.timedelta(minutes=15)
booking.ends_at += dt.timedelta(minutes=15)
booking.full_clean()
Prediction: "fails, because the query finds the booking's own row, still at 9am, and 9.15am to 10.15am overlaps it". Correct red. Green: .exclude(pk=self.pk) at the end of the query. For a new booking pk is None, and every saved row has a primary key, so the one line serves both cases.
Example: refactor, say what the code means
All five tests are green. Now, and only now, Aisling tidies up. The query pieces become named QuerySet methods, in the spirit of the ORM chapter's rule to name the shape, and the check skips cancelled bookings and half filled forms (the field validation reports those):
# bookings/models.py
class BookingQuerySet(models.QuerySet):
def live(self):
return self.filter(cancelled_at__isnull=True)
def overlapping(self, starts_at, ends_at):
# Two ranges overlap when each starts before the other ends (end time exclusive).
return self.filter(starts_at__lt=ends_at, ends_at__gt=starts_at)
class Booking(models.Model):
# ... fields as in the ORM chapter ...
objects = BookingQuerySet.as_manager()
def clean(self):
if self.cancelled_at or not (self.mechanic_id and self.starts_at and self.ends_at):
return
clash = (
Booking.objects.live()
.filter(mechanic_id=self.mechanic_id)
.overlapping(self.starts_at, self.ends_at)
.exclude(pk=self.pk)
)
if clash.exists():
raise ValidationError(OVERLAP)
Five tests, all green. The refactor changed the shape of the code and not a single behaviour, and the tests prove it.
Example: cycle 6, the twin, and the door that skips clean()
The last case on the list, two requests at the same moment, cannot be solved in Python: both requests check, both see a free slot, both save. And as the ORM chapter showed, save(), update(), the bulk methods and Django REST Framework serializers never call full_clean(). So the last test goes through such a door, the way a twin request would:
from django.db import IntegrityError, transaction
def test_two_requests_at_the_same_moment_cannot_both_win():
first = BookingFactory(starts_at=at(9), ends_at=at(10))
twin = candidate(first, at(9, 30), at(10, 30))
with pytest.raises(IntegrityError), transaction.atomic():
twin.save() # save() does not call full_clean(), just like the second request
The inner transaction.atomic() matters. The test already runs inside a transaction, and an IntegrityError inside it would break that transaction for the rest of the test. The inner block becomes a savepoint, which is rolled back cleanly.
Red: Failed: DID NOT RAISE <class 'django.db.utils.IntegrityError'>. Here the spikes differ: in Rails the constraint already existed, while the Django spike only had the unique constraint on mechanic and start time, which cannot see a 9.30am booking colliding with a 9am one. So this test drives the database rule in. Green needs PostgreSQL's exclusion constraint from django.contrib.postgres. It needs the btree_gist extension, installed by the BtreeGistExtension migration operation, and it is checked during model validation as well as in the database18. For a range made from two columns, the documentation's example wraps them in PostgreSQL's tstzrange(), with RangeBoundary() giving "start included, end excluded"18:
# bookings/models.py
from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import DateTimeRangeField, RangeBoundary, RangeOperators
from django.db import models
from django.db.models import F, Func, Q
OVERLAP = "This mechanic already has a booking at that time."
class TsTzRange(Func):
# PostgreSQL's tstzrange(): two timestamp columns as one range of time.
function = "TSTZRANGE"
output_field = DateTimeRangeField()
class Booking(models.Model):
# ... fields, manager and clean() as above ...
class Meta:
constraints = [
ExclusionConstraint(
name="no_overlapping_live_bookings",
expressions=[
(TsTzRange("starts_at", "ends_at", RangeBoundary()), RangeOperators.OVERLAPS),
("mechanic", RangeOperators.EQUAL),
],
condition=Q(cancelled_at__isnull=True), # cancelled bookings free the time
violation_error_message=OVERLAP,
),
models.CheckConstraint(
check=Q(ends_at__gt=F("starts_at")), name="booking_ends_after_it_starts"
),
]
makemigrations writes the migration. Aisling adds the extension by hand as its first operation, and adds "django.contrib.postgres" to INSTALLED_APPS. The test database runs the same migration, so the database user that runs the tests must be allowed to create the extension.
# bookings/migrations/0007_no_overlapping_live_bookings.py (top of the file)
from django.contrib.postgres.operations import BtreeGistExtension
operations = [
BtreeGistExtension(), # added by hand, before the constraint needs it
# ... the generated RemoveConstraint and AddConstraint follow ...
]
Cycle 6 is green. Then Aisling runs the whole file, not only the new test, and cycle 1 has turned red: assert {'__all__': [OVERLAP, OVERLAP]} == {'__all__': [OVERLAP]}. The constraint is checked by full_clean() now, so the Python check reports the same problem a second time. The Rails chapter found its casualty the same way, by running more than the new test. Here, the precise assertion from cycle 1, the one that rejected Cian's early pass, tells Aisling which code to delete.
Example: the database owns the rule
Aisling deletes the overlap check from clean(). The live() and overlapping() methods stay, because the board and the booking form use them to offer free slots. She also removes the old unique constraint on mechanic and start time from the ORM chapter, because two live bookings that start together for the same mechanic overlap anyway, so the exclusion constraint covers it. All six tests are green.
Look at what happened over the six cycles. The tests never changed after they were written. The rule moved from Python into PostgreSQL, the form still shows the same friendly message, and every door into the table is now guarded. This is what tests written against behaviour, not against implementation, buy you: the freedom to move a rule to the place it belongs.
The walk through, part two: the price of a repair
The second feature is the price on a job card: labour plus parts plus VAT. By the ladder, this needs no database at all, so it sits on rung 1: no Django, a plain pytest function.
Niamh's invoices charge labour at €52 an hour, plus the parts used, plus VAT at the Irish standard rate of 23%, as Revenue lists it19. Her accountant wants VAT worked out on the job's net total and rounded to the nearest cent, halves rounded up, exactly as in the Rails chapter. That rounding rule is the accountant's choice for Freewheel. Check yours with your own accountant: this is general information, not tax or legal advice.
As a formula (Foundations: percentages):
where is the net price in euro, the minutes of labour, the labour rate in euro an hour, the price of part net of VAT, the VAT rate as a fraction, rounding to the nearest cent with halves going up, the VAT and the total the customer pays.
With Freewheel's average repair, 90 minutes of labour, a chain at €12.00 and a brake cable at €5.00, and with a quick job, 30 minutes plus an inner tube at €6.99:
where every symbol means the same as above, and is the Irish standard rate as a fraction (Foundations: percentages). These are the same figures as in the Rails chapter, so both versions can be checked against one invoice.
The test list is the Rails chapter's list too: labour, parts, VAT, then rounding for VAT and for labour that do not come to whole cent.
Example: cycles 1 to 3, the straight path
The three tests:
# repairs/tests/test_pricing.py
from decimal import Decimal
from repairs.pricing import repair_price
RATE = Decimal("52.00") # euro an hour
VAT = Decimal("0.23") # Irish standard rate
def test_labour_is_charged_by_the_minute():
price = repair_price(minutes=90, labour_rate=RATE, vat_rate=VAT)
assert price.labour == Decimal("78.00")
def test_parts_are_added_to_labour_for_the_net_total():
price = repair_price(minutes=90, labour_rate=RATE,
parts=[Decimal("12.00"), Decimal("5.00")], vat_rate=VAT)
assert price.net == Decimal("95.00")
def test_vat_is_added_to_the_net_total():
price = repair_price(minutes=90, labour_rate=RATE,
parts=[Decimal("12.00"), Decimal("5.00")], vat_rate=VAT)
assert price.vat == Decimal("21.85")
assert price.total == Decimal("116.85")
Each was written and run alone, red first. The very first run fails with ModuleNotFoundError: No module named 'repairs.pricing'. That is the predicted red, but it only says a file is missing, nothing about the price. So Aisling creates a skeleton that returns zeros, and the red becomes assert Decimal('0') == Decimal('78.00'): now the message names the missing behaviour. The code that makes all three green is the obvious arithmetic:
# repairs/pricing.py (after cycle 3)
from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True)
class Price:
labour: Decimal
parts: Decimal
net: Decimal
vat: Decimal
total: Decimal
def repair_price(minutes, labour_rate, vat_rate, parts=()):
labour = labour_rate * minutes / 60
parts_total = sum(parts, Decimal("0"))
net = labour + parts_total
vat = net * vat_rate
return Price(labour=labour, parts=parts_total, net=net, vat=vat, total=net + vat)
Decimal compares values, not the number of digits, so Decimal("21.8500") equals Decimal("21.85"). The numbers match Freewheel's average repair: €95 net, €116.85 with VAT.
Example: cycle 4, the cent that is never rounded
def test_vat_is_rounded_to_the_nearest_cent_halves_up():
# 30 minutes (€26.00) plus an inner tube (€6.99) is €32.99 net.
# 23% of €32.99 is €7.5877, which rounds to €7.59.
price = repair_price(minutes=30, labour_rate=RATE, parts=[Decimal("6.99")], vat_rate=VAT)
assert price.vat == Decimal("7.59")
assert price.total == Decimal("40.58")
Prediction: "fails with 7.5877, because nothing rounds". The run says assert Decimal('7.5877') == Decimal('7.59'). Here the two frameworks fail differently, which is worth seeing. Rails works in whole cent, and integer division throws the fraction away, so the Rails test sees 758 instead of 759. Python's Decimal keeps the fraction exactly, so the Django test sees a VAT amount with four decimal places, a figure no invoice can carry. Two different wrong answers, one missing rule.
The fix already exists. When the project started, Aisling wrote vat_for() in parts/money.py, and it does exactly what Niamh's accountant asks: VAT on a net amount, rounded to the cent, half up. It gives €7.59 here and €21.85 for the average repair, so Aisling reuses it rather than writing a second copy of a money rule:
from parts.money import vat_for
vat = vat_for(net, vat_rate) # in repair_price(), replacing "net * vat_rate"
Four tests, all green.
Example: cycle 5, labour that does not divide evenly
At €52 an hour a minute costs 86 and two thirds cent, so 10 minutes come to €8.666..., and labour by the minute no longer comes to whole cent. The test was already on the list:
def test_labour_is_rounded_to_the_nearest_cent_when_the_rate_does_not_divide_evenly():
# €52.00 an hour for 10 minutes is €8.666...
price = repair_price(minutes=10, labour_rate=RATE, vat_rate=VAT)
assert price.labour == Decimal("8.67")
Prediction: "fails with a long row of sixes". The run says assert Decimal('8.666666666666666666666666667') == Decimal('8.67'). Correct. Now refactor, with one rounding rule named once. Aisling moves the rounding out of vat_for() into its own small function in parts/money.py, and both lines use it:
# parts/money.py (after the refactor)
from decimal import ROUND_HALF_UP, Decimal
IE_STANDARD_RATE = Decimal("0.23")
CENT = Decimal("0.01")
def to_cent(amount: Decimal) -> Decimal:
"""Exact amount in, whole cent out, halves rounded up."""
return amount.quantize(CENT, rounding=ROUND_HALF_UP)
def vat_for(net: Decimal, rate: Decimal = IE_STANDARD_RATE) -> Decimal:
return to_cent(net * rate)
# repairs/pricing.py (after the refactor)
from dataclasses import dataclass
from decimal import Decimal
from parts.money import to_cent, vat_for
@dataclass(frozen=True)
class Price:
labour: Decimal
parts: Decimal
net: Decimal
vat: Decimal
total: Decimal
def repair_price(minutes, labour_rate, vat_rate, parts=()):
"""Labour by the minute, plus parts, then VAT on the net total."""
labour = to_cent(labour_rate * minutes / 60)
parts_total = sum(parts, Decimal("0"))
net = labour + parts_total
vat = vat_for(net, vat_rate)
return Price(labour=labour, parts=parts_total, net=net, vat=vat, total=net + vat)
Five tests, five green, and the file runs in milliseconds because no test touches the database.
Example: one table instead of ten tests
Once the rule is built, more cases are documentation, not drivers. Rather than a new function for each, Aisling turns the invoices Niamh cares about into a table with parametrize:
import pytest
@pytest.mark.parametrize(
("minutes", "parts", "net", "vat", "total"),
[
(90, [], "78.00", "17.94", "95.94"), # labour only
(90, ["12.00", "5.00"], "95.00", "21.85", "116.85"), # the average repair
(30, ["6.99"], "32.99", "7.59", "40.58"), # VAT of 7.5877 rounds up
(10, [], "8.67", "1.99", "10.66"), # a quick check
(0, ["1.50"], "1.50", "0.35", "1.85"), # 0.345 rounds half up
],
)
def test_repair_prices(minutes, parts, net, vat, total):
price = repair_price(
minutes=minutes, labour_rate=RATE, parts=[Decimal(p) for p in parts], vat_rate=VAT
)
assert (price.net, price.vat, price.total) == (Decimal(net), Decimal(vat), Decimal(total))
pytest reports five tests, one per row, each with its inputs in the test id. A new case is one new line, written in the language Niamh uses on an invoice. These pass at once, because the behaviour already exists. To trust a test that never went red, break the code on purpose for a moment (change ROUND_HALF_UP to ROUND_HALF_EVEN in to_cent()), watch the last row fail, and put it back.
The last row deserves a second look. At 23%, VAT on a net amount in whole cent can land exactly on half a cent: 23% of €1.50 is 34.5 cent. Rounded half up, that is 35 cent. Rounded half to even, which Python calls ROUND_HALF_EVEN, it is 34 cent. A row like this pins the rule, not just the arithmetic.
Locking in the N+1 fix with a query count
The ORM chapter took the workshop board from 61 queries to a fixed handful with select_related and a Prefetch for the before photos, and pinned it with assertNumQueries at two sizes. The trick was to assert the same number with few cards and with many: if the count does not change, it does not grow with the number of cards.
With pytest, the two sizes become two rows of parametrize, and the query assertion is a fixture6. Each row runs in its own rolled back transaction, so the sizes do not leak into each other.
Example: the board stays at four queries, however busy Saturday gets
# repairs/tests/test_board_queries.py
import datetime as dt
import pytest
from django.urls import reverse
from django.utils import timezone
from tests.factories import JobCardFactory
@pytest.mark.django_db
@pytest.mark.parametrize("cards", [2, 12])
def test_board_query_count_does_not_grow_with_cards(cards, client, mechanic, django_assert_num_queries):
client.force_login(mechanic.user)
eight = timezone.localtime().replace(hour=8, minute=0, second=0, microsecond=0)
for i in range(cards):
start = eight + dt.timedelta(minutes=30 * i) # one mechanic, no overlaps
JobCardFactory(
booking__mechanic=mechanic,
booking__starts_at=start,
booking__ends_at=start + dt.timedelta(minutes=30),
)
url = reverse("repairs:board", args=[mechanic.workshop_id])
with django_assert_num_queries(4): # session, user, cards, before photos
client.get(url)
The bookings are 30 minutes apart because they share one mechanic, and the exclusion constraint would refuse overlapping test data: test data obeys the same rules as production data. If someone later adds the bike's make to the template without loading it, the 12 card row fails with 16 queries and the 2 card row with 6. Run pytest with -v to see the queries6.
Time: freezegun or time machine
Rails has travel_to built into its test helpers20. Django has nothing built in for moving the clock, so the Python world offers two libraries.
freezegun, at version 1.5.1, freezes time through a decorator or context manager, freeze_time("2024-06-08 09:00"), by mocking the datetime module and several functions in time21. It has been the familiar choice for years.
time machine, by Adam Johnson, at version 2.14.1, hooks into the C level functions Python uses to read the clock, so it also catches code that freezegun cannot reach, and its README says it is much faster22. Time keeps ticking after travel by default (tick=True), naive datetimes are read as UTC rather than local time, a ZoneInfo destination also sets the current time zone, and a pytest fixture, time_machine, offers move_to() and shift()22.
Both are fine. For a new project I would choose time machine, mainly for its rule that naive times mean UTC, which removes a class of tests that pass on a developer's laptop in Limerick and fail on a build server set to UTC.
There is a second reason to care about the clock, and it hides in the walk through above. Every overlap test books slots on Saturday 8 June 2024. The day a rule about the past arrives, every one of those tests fails from 9 June 2024 onwards, without a single line of code changing. A hard coded date in a test is a time bomb unless the test also fixes the clock. The Rails chapter defuses the same bomb with travel_to in its setup.
Example: a booking cannot start in the past
Niamh asks for one more rule, the same one as in the Rails chapter: a booking cannot start in the past. The clean() method keeps it, because it is the one rule the database cannot know. Aisling writes the test first, travelling to Saturday at half past nine:
# bookings/tests/test_booking_time.py
import pytest
from django.core.exceptions import ValidationError
from bookings.models import IN_THE_PAST
from bookings.tests.helpers import at, candidate
from tests.factories import BookingFactory
@pytest.mark.django_db
def test_a_booking_cannot_start_in_the_past(time_machine):
time_machine.move_to(at(9, 30)) # Saturday 8 June 2024, half past nine in Limerick
earlier = BookingFactory(starts_at=at(8), ends_at=at(8, 30)) # save() does not validate
gone = candidate(earlier, at(9), at(10)) # 9am has gone
with pytest.raises(ValidationError) as excinfo:
gone.full_clean()
assert excinfo.value.message_dict == {"__all__": [IN_THE_PAST]}
candidate(earlier, at(10), at(11)).full_clean() # 10am is still ahead
It fails as predicted, with DID NOT RAISE, and the code is one condition:
# bookings/models.py
from django.utils import timezone
IN_THE_PAST = "That time is in the past. Please choose a later slot."
# inside class Booking
def clean(self):
# Only new bookings: an old booking may be corrected after its time has passed.
if self._state.adding and self.starts_at and self.starts_at <= timezone.now():
raise ValidationError(IN_THE_PAST)
_state.adding is True until a model instance has been saved, which is how Django marks a new row17. It plays the part of the Rails validation's on: :create.
The day this rule goes in, Aisling also defuses the overlap tests. One autouse fixture, a fixture that every test in its folder uses without asking, sets the clock for all booking tests to the Friday evening before their slots, the same moment the Rails chapter freezes:
# bookings/tests/conftest.py
import datetime as dt
import pytest
from tests.factories import LIMERICK
@pytest.fixture(autouse=True)
def friday_evening_before_the_slots(time_machine):
# Every booking test runs on Friday 7 June 2024 at 6pm, before the Saturday rush.
time_machine.move_to(dt.datetime(2024, 6, 7, 18, 0, tzinfo=LIMERICK))
The test above moves the clock again, to Saturday, and that later move wins. Now every booking test means the same thing in December as in June, and on any machine.
Outside services: never let a test talk to the real world
The "your bike is ready" message goes out by email and by SMS. The background tasks chapter built the sender, send_bike_ready_sms(), which posts to an SMS provider's API with the requests library, raises SmsTemporaryError when the provider says "try again later", and returns the provider's message id. A test must never send a real SMS. It must also prove that the request looks right and that failures are handled.
responses, maintained by Sentry, at version 0.25.2, mocks the requests library23. You register expected responses with responses.post(...) and friends and decorate the test with @responses.activate. Matchers check the request's body or headers, each response counts its calls, and a request to any address you did not register fails with a ConnectionError23, so a test can never reach the real provider by accident. It covers requests only; another HTTP client needs its own mocking tool.
Email is easier: Django's test runner replaces the email backend with an in memory one that collects messages in django.core.mail.outbox5, and pytest django's mailoutbox fixture hands you that list6. And for the step between the two, django_capture_on_commit_callbacks shows which tasks would be queued when the transaction commits6.
Example: the text reaches the provider once, and a busy provider is retried
# notifications/tests/test_sms.py
import json
import pytest
import responses
from responses import matchers
from notifications.models import Notification
from notifications.senders import SmsTemporaryError, send_bike_ready_sms
from tests.factories import NotificationFactory
SMS_URL = "https://sms.example/v1/messages"
PHONE = "+0000000001" # a placeholder, never a real number
@pytest.fixture
def sms_settings(settings):
settings.SMS_API_URL = SMS_URL
settings.SMS_API_TOKEN = "test-token"
@pytest.mark.django_db
@responses.activate
def test_the_bike_ready_text_reaches_the_provider_once(sms_settings):
note = NotificationFactory(
channel=Notification.Channel.SMS, job_card__booking__customer__mobile=PHONE
)
provider = responses.post(
SMS_URL,
json={"id": "msg_1"},
status=201,
match=[matchers.header_matcher({"Authorization": "Bearer test-token"})],
)
assert send_bike_ready_sms(note) == "msg_1"
assert provider.call_count == 1
sent = json.loads(responses.calls[0].request.body)
assert sent["to"] == PHONE
assert sent["reference"] == f"freewheel-{note.pk}"
@pytest.mark.django_db
@responses.activate
def test_a_busy_provider_raises_a_temporary_error(sms_settings):
note = NotificationFactory(channel=Notification.Channel.SMS)
responses.post(SMS_URL, status=503)
with pytest.raises(SmsTemporaryError):
send_bike_ready_sms(note) # the task retries this type, see the tasks chapter
NotificationFactory follows the same pattern as the others, with job_card = factory.SubFactory(JobCardFactory), and the customer factory gains a mobile field. The double underscores reach four levels down to set the one fact the first test is about. Everything else is a valid default.
And the step before the sender, written as a pytest function:
# repairs/tests/test_mark_ready.py
import pytest
from repairs.services import mark_ready
from tests.factories import JobCardFactory
@pytest.mark.django_db
def test_marking_ready_queues_one_email_and_one_text(django_capture_on_commit_callbacks):
card = JobCardFactory(status="in_repair", booking__customer__mobile="+0000000001")
with django_capture_on_commit_callbacks() as callbacks:
mark_ready(card.pk)
assert len(callbacks) == 2 # nothing is sent until the transaction commits
It is the same assertion as the TestCase version in the background tasks chapter, with less around it.
Running fast: parallel runs and the slowest tests
A TDD cycle only works if the tests you run while working take seconds. Two habits keep it there. Run only the file you are working on while you work, and the whole suite before you push. And keep the whole suite fast enough that nobody is tempted to skip it.
Both test runners can run in parallel:
python manage.py test --parallel autoruns one process per core. Django hands out whole test classes, gives each process its own copy of the test database, and needs thetblibpackage to show tracebacks properly. It is not available on Windows. Debugging withpdbneeds--parallel=18.pytest -n autowith pytest xdist, at version 3.6.1, starts one worker per physical core and hands out individual tests by default24. pytest django adds a suffix to the test database name for each worker, so each worker has its own database12.
To find what is slow, Django 5.0 added --durations N to the test command, which needs Python 3.129, the same version in which unittest itself gained the option25. pytest has --durations N too.
A simple model tells you what to expect from parallel runs (Foundations: ratios and rates):
where is the wall clock time of a full run in seconds with workers, is the fixed setup that does not shrink with more workers (creating and migrating the test databases, importing Django), is the time the tests themselves take when run one after another, and is the number of workers. The model ignores uneven sharing of work between workers, so treat it as a best case.
Example: the spike suite on Aisling's laptop
At the end of the two week spike, the Django version has about 180 tests. On Aisling's laptop (illustrative figures, not a benchmark), a serial run takes 96 seconds, of which about 9 are setup: , . With four workers:
where the symbols mean the same as above (Foundations: ratios and rates). With --reuse-db, the database is not created again on each run, and drops to about 1 second, so seconds. The model also shows the limit: with fixed, more workers shave less and less, and can never fall below .
The two runners score the same on purpose: parallel speed comes from the processes, not the framework. Django shares out test classes, pytest xdist single tests, which balances better when one class is much slower than the rest.
Random order (--shuffle on the Django runner, a plugin for pytest) is worth switching on early too, because it exposes tests that depend on each other's leftovers.
Rails and Django testing, side by side
If you read the Rails chapter first, this table maps the tools. Both columns describe the documented state as of Rails 7.1 and Django 5.0.
| Need | Rails 7.1 | Django 5.0 |
|---|---|---|
| Default test framework | Minitest, through bin/rails test20 | unittest, through manage.py test7 |
| The popular alternative | RSpec, with rspec rails | pytest, with pytest django |
| Test with the database, rolled back | ActiveSupport::TestCase, transactional tests by default20 | TestCase, or @pytest.mark.django_db |
| Test without the database | Any Ruby test that touches no model | SimpleTestCase, or a pytest test without the mark |
| Requests through the stack | Integration tests (ActionDispatch::IntegrationTest)20 | The test client, client fixture |
| Built in test data | YAML fixtures in test/fixtures20 | Fixture files (JSON) via fixtures |
| Factories | factory_bot26 | factory_boy |
| Moving the clock | travel_to, built in20 | time machine or freezegun |
| Faking outside HTTP | WebMock27 | responses, for the requests library |
| Counting queries | No documented public assertion in the Rails 7.1 testing guide, but strict_loading guards lazy loads28 | assertNumQueries, django_assert_num_queries |
| Side effects after commit | Job and mailer assertions in the test helpers20 | captureOnCommitCallbacks, django_capture_on_commit_callbacks |
| Parallel runs | parallelize(workers: :number_of_processors), built in20 | --parallel, or pytest xdist |
The shape is the same on both sides: a default from the framework's own toolbox, a popular alternative with more expressive syntax, factories for data, a library to fake the outside world. The differences are in what ships in the box. Rails includes time travel and parallel testing, so a Rails developer reaches for fewer gems. Django includes assertNumQueries and commit callback capture, two tools I miss when I am in Rails.
For the person paying for this
You do not need to read test code to judge whether a team works test first. Ask for three things and look at what comes back.
| Ask for | A good answer looks like |
|---|---|
| The test for your most expensive rule (double bookings, prices, stock) | A short test with a name you can read aloud, that fails if the rule breaks, and a second one that goes through a door other than the form |
| How long the full suite takes, and how often it runs | Minutes, not tens of minutes, on every push, with the slowest tests listed |
| What happens to outside services in tests | Faked: no real SMS, email or payment ever leaves a test run |
Then ask one question: "Show me a test that went red before the code existed." A team that works test first can show you one in their history in a minute. A team that writes tests afterwards will talk about coverage instead.
I build web applications on Ruby on Rails, test first, with the same habits shown here, and the code, the accounts and the data are yours from day one. If you want a second opinion on a test suite or a plan, the free workshop is the place to start.
My view
Separating what is documented from what is my judgement: how Django's test classes, pytest, pytest django, factory_boy, time machine, freezegun and responses behave comes from their own documentation, cited above. The ladder, the rule about the right red and the advice below are mine.
My view: the unittest or pytest question matters less than the internet suggests, because pytest runs unittest tests unchanged and both sit on the same Django machinery. I would start a new project with pytest and pytest django, for parametrised tables, fixtures with names, and a default that keeps tests off the database unless they ask. I would keep Django's TestCase where setUpTestData saves real time.
What matters more is the discipline inside the cycle. Read every red message, and move on only when it names the behaviour you are building. Write the fastest test that can fail for the right reason. Assert precisely, because a precise assertion later tells you which code to delete. And test behaviour, not implementation, so a rule can move from Python into PostgreSQL without touching a test.
Django developers reading this will recognise every tool. Rails developers will recognise every habit. TDD looks the same in both frameworks once you stop looking at the syntax.
Conclusion
Test driven development in Django is the same short cycle as anywhere else: a test that fails for the right reason, the least code that passes, a refactor under green tests. Django gives you a sound default with unittest and its test case classes, and pytest with pytest django gives you plain functions, fixtures, parametrisation and a default of no database. Because pytest runs Django's test classes unchanged, the choice is easy to reverse.
Build test data with factory_boy, with factories whose rows agree. Put each test on the lowest rung that can prove it: the price rule needs no database, the overlap rule one rolled back transaction per test. Fake the clock and the outside world, pin query counts at two sizes, run in parallel and watch --durations.
The next chapter in this series takes the same booking journey and the live workshop board into a real browser, with behaviour driven and end to end tests in Django.
