Chapter 34 · Testing fundamentals and first-release acceptanceCHAPTER 34
Complete six-part pre-release for review. Adds two development packages (coverage.py and tblib) and no migration. The CI outputs come from real runs in a private repository made for the book's checks. GitHub is optional: without it, run check.py yourself. Fixtures arrive in Chapter 41, browser tests in Chapter 58, and CI/CD in Chapter 64.
Milestone reached in this chapter: First release. One community runs free events. Members sign up, register, see, and cancel their registrations; organizers publish their own events; two people cannot both take the last place. Tests check each product rule. All milestones
CHAPTER THIRTY-FOUR
Testing fundamentals and first-release acceptance
Stage 4: Accounts and first release (Chapters 24 to 34)
Prerequisites: Chapters 15 to 33, including the Chapter 33 project on PostgreSQL 18 with its 354 passing tests, the race tests of Chapter 33, Chapter 2’s product rules PR-1 to PR-6 and its traceability register (Table 2.3), and Git from Chapter 8
What you’ll build: Tests organized into a tests/ package in every app, with shared helpers in one module; coverage measured and read, and the missing tests it reveals; a suite that passes in any order; an acceptance trace that links each Chapter 2 rule to named tests and checks itself; a check.py command and a GitHub Actions workflow that runs it on PostgreSQL for every push; a skip link and clearer messages; and the first release, tagged v0.1.0
Why This Matters
Soni, Otahque’s administrator, has to decide whether the community can use Otahque for its real events next month. Sam shows her a terminal: Ran 354 tests, OK. Soni asks the question a green line cannot answer: “Which of those tests proves that nobody gets a place in a full event? And which proves Raj cannot cancel Sai’s place?” Sam knows the tests exist. He cannot point at them, and nothing would warn him if one were renamed or deleted.
Soni asks a second question: “Does it pass anywhere except your laptop?” The suite has only ever run on the author’s computer, in the order Django happens to choose, with a database he set up by hand. A test that only passes there proves less than it seems.
This chapter turns “the tests pass” into an argument Soni can check. You will organize the tests so they can grow, measure which code they run, and find three rules nothing checked. You will find a test that depends on the order the suite runs in. You will trace every Chapter 2 rule to the tests that prove it, run every check on a fresh Linux machine for every push, and only then mark the first release.
By the end of the chapter, you will be able to:
choose the right Django test tool for a question, and organize tests into packages with shared helpers;
measure coverage under --parallel, read the report for untested behaviour, and say what a percentage cannot prove;
find and fix a test that depends on the order of the suite;
write an acceptance trace that links rules to named tests and fails when a name goes stale;
run the project’s checks in GitHub Actions against PostgreSQL, read a red run, and tag a release from a checklist.
Out of scope: browser tests that press keys and click, failure injection, and async tests (Chapter 58); fixtures files beside the helpers (Chapter 41); deploying from CI (Chapters 63 and 64); and measuring responsiveness (Chapter 66).
A test proves one thing: in this situation, the code did this. test_a_full_event_says_so proves that one full event refuses one member, on the database the test used. It does not prove that the page shows the refusal, that two requests at once are handled, or that the rule is the right rule. Each kind of test answers a different question, and Django gives you a tool for each. Figure 34.1 sets them side by side.
Figure 34.1 — Which test tool answers which question.
You have used all of them. Chapter 9’s first tests were SimpleTestCase; most of Otahque’s tests are TestCase, which wraps each test in a transaction and undoes it. The page tests use the test client, which sends a request through the whole of Django. Chapter 10 met RequestFactory, and the time-zone tests in accounts use it to build requests by hand, skipping URLs and middleware so that one piece can be checked alone. Chapter 33’s race tests needed TransactionTestCase, because other connections must see what each test commits. Sixty-two classes already share their rows through setUpTestData, which makes them once per class instead of once per test.
People often name these unit, integration, and acceptance tests. In Django terms, a unit test checks one function or method, often with SimpleTestCase; an integration test checks pieces working together, such as a page through the test client and the database; an acceptance test checks a rule the product promised, in words the person who asked for it would recognize. The last kind is not a different tool. It is a test chosen and named for a rule, and this chapter makes that link explicit.
Coverage: what ran, not what was checked
New Concept: test coverage
What problem exists? You cannot read 362 tests and know which lines of code none of them ever runs.
What did people do before? Guess, or add tests wherever a bug had appeared.
What is it?Coverage measures which lines, and which branches of each if, ran while the tests ran. coverage.py is the standard Python tool. It reports each file’s percentage and the line numbers that never ran.
Why use it? A line that never ran during the tests is a line no test checked. The report points at them.
Now let’s use it. Step 4 measures Otahque; Step 5 reads the report and writes the tests it reveals.
Coverage has one trap: a line that ran is not a line that was checked. A test can run a function and assert nothing about its result. So coverage finds candidates, places that no test reaches, and people decide what to test. This chapter sets no target percentage. You will see Otahque at 99% of its lines with three of its rules unchecked.
Tests that depend on each other
Every test should pass alone, in any order, and beside any other test. A test that passes only after another one, or fails only after another one, depends on something left behind: a row, a file, a setting, or a value in the cache. Such failures appear “at random”, because the order changes when tests are added. Django’s test --reverse runs the suite backwards, and --shuffle runs it in a random order whose seed it prints, so that the same order can be run again. Both shake out these dependencies on purpose.
Under the Hood: --parallel and worker processes
Since Chapter 32, the checkpoint runs test --parallel. Django starts one worker process for each processor core, gives each a copy of the test database, and shares the test classes out among them. Two consequences follow. First, a tool that watches the program, such as coverage.py, sees only the main process unless it is told to follow the workers. Second, a failure happens inside a worker and must be sent back to the main process; Python cannot send a traceback between processes without help, so Django asks for a small package, tblib, that can.
Continuous integration
Continuous integration, or CI, means running the project’s checks automatically on every change, on a machine nobody configured by hand. If the checks pass only on the author’s laptop, the laptop is part of the product. A CI service starts a fresh machine, installs exactly what the lock file names, starts a fresh database, and runs the same command the author runs. A green mark then means “passes from a clean start”, and a red mark names the change that broke it.
This chapter uses GitHub Actions, the CI service built into GitHub. A workflow is a file in .github/workflows/ that says when to run (on every push), on what machine, and which steps to take. Figure 34.4, in Step 10, shows Otahque’s. If you use another host, such as GitLab or Codeberg, the same steps fit its own CI file; Chapter 64 compares them.
GitHub is optional
You need a GitHub account for Steps 10 and 11 and the final push. Without one, run check.py yourself before every commit and skip the pushes; everything else in the chapter, including the release checklist and the tag, works the same.
Acceptance: rules, cases, tests, evidence
Chapter 2 wrote six product rules, PR-1 to PR-6, and planned a check for each. Table 2.3 marked every row “Planned”. Acceptance is the decision that the product meets its rules well enough to use. It needs evidence, not confidence: for each rule, the cases that prove it, the tests that check each case, and the run that shows they pass. That record is an acceptance trace. Figure 34.2 follows one rule through it.
Figure 34.2 — From a rule to its tests to evidence: the M2 trace.
A trace is honest only if it shows its gaps. Where a rule is only partly met, or a case is deliberately not handled, the trace says so and says why. A release with written limits can be accepted; a release with hidden ones cannot.
In practice: the pilot meeting
Situation. Soni will let Sam’s Django clinic and the Leeds meetup use Otahque next month, if she can see the evidence for each rule.
Application. Sam opens docs/acceptance/M2.md. Under PR-3 he points at three tests and the overlap case, and at the known limit written below them. He opens the green CI run for the commit he will tag.
Consideration. Soni accepts PR-3 with its limit. She asks for the keyboard check to be repeated with a screen reader before a wider launch; that request goes into the trace as future work, not into this release.
Try it yourself
Que. 1 Otahque’s coverage report shows 99% of lines run. Name one thing that number cannot tell you.
Flip to check your answerFold answer back
Answer. Whether any test checked what those lines did. A test can run a line and assert nothing, and a rule can be missing from the code altogether, so no line exists to be uncovered. The report shows where no test reached; it cannot show that the tests that did reach a line were right.
Que. 2 A test passes when run alone and fails in the full suite. What kind of cause should you look for first?
Flip to check your answerFold answer back
Answer. Something an earlier test left behind: a row it committed, a value it cached, a setting it changed, or a file it wrote. Run the suite with --reverse or --shuffle to make the failure repeat, then find what the failing test assumed was empty.
Start from Chapter 33, in the folder containing manage.py, with Otahque on PostgreSQL 18, 354 passing tests, every migration applied, and the work committed. Two development packages are added: coverage.py 7.17.4 and tblib 3.2.2. No model or migration changes. Each app’s tests.py becomes a tests/ package; the new files are config/helpers.py, events/tests/test_locking.py, config/tests/test_acceptance.py, check.py, .github/workflows/ci.yml, docs/testing.md, docs/acceptance/M2.md, and docs/release-checklist.md, and pyproject.toml, .gitignore, templates/base.html, and the stylesheet source change. The visible result: a “Skip to the main content” link for keyboard users, and messages coloured by what they say. The chapter’s checks ran in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.3, and in GitHub Actions on Ubuntu 24.04 against PostgreSQL 18.
The Custom Way
CI begins where your laptop’s history does not: with a fresh copy of the repository and nothing else. Make one by hand, beside your project, and try to use it:
Terminal
git clone . ../otahque-clean
cd ../otahque-clean
uv sync --locked
uv run python manage.py check
Output
Cloning into '../otahque-clean'...
Using CPython 3.14.9
Creating virtual environment at: .venv
Installed 24 packages in 10.55s
...
django.core.exceptions.ImproperlyConfigured: Set
DJANGO_SECRET_KEY; see .env.example.
Git copied every committed file and uv installed exactly the locked packages, but Django refuses to start: the secret key lives in .env, which Git never records (Chapter 8). The clean copy also has no database settings, so it would fall back to SQLite. This is precisely what a CI machine sees, and why the workflow in Step 10 must supply both. Go back to your project folder and delete the copy (Remove-Item -Recurse -Force ../otahque-clean in PowerShell, rm -rf ../otahque-clean elsewhere).
The Django Way
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 354 test(s).
Creating test database for alias 'default'...
...
Ran 354 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Lock the last place; refuse stale edits
The 354 tests live in five files: accounts/tests.py (86 tests), audit/tests.py (4), config/tests.py (14), events/tests.py (188, about 2,900 lines), and registrations/tests.py (62). Three of those files import helpers from events/tests.py, so the events tests are also a library for the others. Both facts shape the next two steps.
Step 2: Move the tests into packages
A package lets each app keep several test files: the old tests in one, and each new subject in its own. Move each app’s file into a tests/ folder with an empty __init__.py, which makes the folder a package. git mv moves the file and tells Git it was moved, so its history follows it.
# Git Bash, macOS, Linux, WSL
for app in accounts audit config events registrations; do
mkdir "$app/tests"
touch "$app/tests/__init__.py"
git mv "$app/tests.py" "$app/tests/test_$app.py"
done
Each file keeps every test it had; only its address changes, from events.tests to events.tests.test_events. Moving and splitting are two changes: do the move now, and split a file further when you next work in it. Run the suite, this time without --parallel: while imports are broken, a parallel run can stop without a summary, for a reason Step 7 explains and fixes.
Terminal
uv run python manage.py test
Output
Found 5 test(s).
...
ImportError: cannot import name 'admin_url' from
'events.tests' (...\events\tests\__init__.py)
ImportError: cannot import name 'views' from 'events.tests'
(...\events\tests\__init__.py)
ImportError: cannot import name 'as_sent' from 'events.tests'
(...\events\tests\__init__.py)
...
Ran 5 tests in ...s
FAILED (errors=5)
Two kinds of import broke. Inside a moved file, from . import views now means “from the tests package”, which has no views. Make each relative import name its app. In events/tests/test_events.py, replace
Python
from . import views
from .forms import CopyForm, EventForm
from .models import ORGANIZERS, Event, OrganizerAssignment
with
events/tests/test_events.py
from events import views
from events.forms import CopyForm, EventForm
from events.models import (
ORGANIZERS, Event, OrganizerAssignment,
)
and do the same in the other three files that used relative imports:
accounts/tests/test_accounts.py
from accounts.adapter import DISPOSABLE
from accounts.models import Profile, User
from accounts.timezones import (
audit/tests/test_audit.py
from audit.models import AuditEvent, record
registrations/tests/test_registrations.py
from registrations.models import Registration
Run the same command again:
Output
Found 195 test(s).
...
ImportError: cannot import name 'admin_url' from
'events.tests' (...\events\tests\__init__.py)
ImportError: cannot import name 'as_sent' from 'events.tests'
(...\events\tests\__init__.py)
...
Ran 195 tests in ...s
FAILED (errors=3)
The events tests now load. What is left are the other apps’ imports from events.tests, which is now an empty package. They need a proper home.
Step 3: One module for shared helpers
Helpers that several apps’ tests use belong in one module that belongs to no single app. Create config/helpers.py. Its name does not start with test, so the runner never collects it as tests; a name such as testing.py would match the runner’s test*.py pattern.
config/helpers.py
"""Helpers that more than one app's tests use.
Not a test module: its name does not start with "test",
so the test runner never collects it. Each helper makes
data or a request the way the earlier chapters' tests
did; one copy here replaces the imports from
events.tests that broke when the tests moved.
"""
from datetime import UTC, datetime, timedelta
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.urls import reverse
from events.forms import EventForm
from events.models import Event, OrganizerAssignment
User = get_user_model()
SAI_PASSWORD = 'a-long-safe-pass-123'
def save_event(**changes):
"""Save a published event; keywords replace defaults."""
fields = {
'title': 'Python meetup',
'starts_at': datetime(2026, 11, 19, 18, 30,
tzinfo=UTC),
'timezone': 'Europe/London',
'location': 'Leeds Central Library',
'capacity': 40,
'status': Event.Status.PUBLISHED,
}
fields.update(changes)
fields.setdefault(
'ends_at', fields['starts_at'] + timedelta(hours=2)
)
return Event.objects.create(**fields)
def in_group(email, group, **flags):
"""Add a member with SAI_PASSWORD to the named group."""
name = email.split('@')[0].title()
user = User.objects.create_user(
email, SAI_PASSWORD, display_name=name, **flags
)
user.groups.add(Group.objects.get(name=group))
return user
def admin_url(model, page, *args):
"""Return an admin page's address, such as an event's."""
meta = model._meta
name = f'admin:{meta.app_label}_{meta.model_name}_{page}'
return reverse(name, args=args)
def event_form(event, **changes):
"""Build what the admin's event page sends; UTC times."""
data = {
'title': event.title,
'status': event.status,
'starts_at_0': f'{event.starts_at:%Y-%m-%d}',
'starts_at_1': f'{event.starts_at:%H:%M}',
'ends_at_0': f'{event.ends_at:%Y-%m-%d}',
'ends_at_1': f'{event.ends_at:%H:%M}',
'timezone': event.timezone,
'location': event.location,
'capacity': event.capacity,
'registrations-TOTAL_FORMS': 0,
'registrations-INITIAL_FORMS': 0,
'seen_version': event.version,
}
data.update(changes)
return data
def remove_selected(client, *assignments):
"""Run the admin's Remove selected organizers action."""
return client.post(
admin_url(OrganizerAssignment, 'changelist'),
{'action': 'remove_selected',
'_selected_action': [a.pk for a in assignments]},
follow=True,
)
def as_sent(event, **changes):
"""Return what the edit page sends, before any change."""
form = EventForm(instance=event)
data = {}
for name in form.fields:
value = form[name].value()
if isinstance(value, datetime):
value = f'{value:%Y-%m-%dT%H:%M}'
# A blank time is sent as an empty box.
data[name] = '' if value is None else value
# The version the page was opened at (Chapter 33).
data['version'] = event.version
return data | changes
def outcome(response):
"""Name a response as the permission matrix names it."""
code = response.status_code
if code == 302 and response.url.startswith(
reverse('account_login')):
return 'sign in'
return {200: 'ok', 302: 'ok'}.get(code, str(code))
These are the eight helpers the other apps imported, unchanged. Delete their definitions from events/tests/test_events.py: save_event(), admin_url(), event_form(), remove_selected(), as_sent(), in_group(), outcome(), and the SAI_PASSWORD line. Then import them from their new home. In events/tests/test_events.py, after from audit.models import AuditEvent:
events/tests/test_events.py
from audit.models import AuditEvent
from config.helpers import (
SAI_PASSWORD, admin_url, as_sent, event_form, in_group,
outcome, remove_selected, save_event,
)
from registrations.models import Registration
In the other three files, replace each from events.tests import line:
accounts/tests/test_accounts.py
from config.helpers import (
admin_url, event_form, save_event,
)
config/tests/test_config.py
from config.helpers import (
(keep the names in its parentheses as they are)
registrations/tests/test_registrations.py
from config.helpers import SAI_PASSWORD as PASSWORD
from config.helpers import (
admin_url, as_sent, in_group, outcome,
)
Helpers used by one app’s tests only, such as verified() and soon() in the registrations tests, stay where they are.
Terminal
uv run python manage.py test --parallel
Output
Found 354 test(s).
Creating test database for alias 'default'...
...
Ran 354 tests in ...s
OK
354 before, 354 after: the same count is the evidence that the move lost nothing. Commit the move on its own, so that Git records renames and the history of each test stays readable:
Terminal
git add .
git commit -m "Move the tests into packages; share helpers"
coverage.py is needed by developers and CI, not by the running site, so add it as a development dependency. uv records those in a separate group in pyproject.toml and in uv.lock, and installs them with uv sync unless asked not to.
Terminal
uv add --dev coverage==7.17.4
Output
Resolved 26 packages in 184ms
Installed 1 package in 973ms
+ coverage==7.17.4
coverage run runs a Python program while measuring it. Run the suite through it, then ask for the report:
Terminal
uv run coverage run manage.py test --parallel
uv run coverage report
Output
Name Cover
----------------------------------------------------
events\models.py 36%
events\views.py 28%
...
----------------------------------------------------
TOTAL 34%
The book prints two rows and the total. events/models.py at 36% would be alarming, and it is false. With --parallel, the tests run in worker processes, and coverage.py measured only the main process, which mostly waited. Tell it to follow the workers. Add to the end of pyproject.toml:
pyproject.toml
[tool.coverage.run]
# Measure the project's own code, not its tests.
source = ["accounts", "audit", "config", "events",
"registrations"]
omit = ["*/migrations/*", "*/tests/*", "config/helpers.py"]
branch = true
# test --parallel runs the tests in several processes:
# each writes its own data file, and combine joins them.
parallel = true
concurrency = ["multiprocessing", "thread"]
[tool.coverage.report]
show_missing = true
skip_covered = true
source limits the report to Otahque’s apps, omit leaves out migrations and the tests themselves, and branch = true also records which way each if went. With parallel = true each process writes its own data file, and concurrency names how the program runs in parallel: in several processes, and, in the race tests, in threads. Those data files and the HTML report must not be committed. Add to .gitignore:
.gitignore
# coverage's data files and HTML report (Chapter 34)
.coverage
.coverage.*
htmlcov/
Now measure again. erase removes the old data, and combine joins the workers’ files before the report:
Terminal
uv run coverage erase
uv run coverage run manage.py test --parallel
uv run coverage combine
uv run coverage report
The full report also has Stmts, Miss, Branch, and BrPart columns; the book prints Name, Cover, and Missing. The Missing column lists lines that never ran, and 485->489 means “the if on line 485 never went to line 489”. For a page you can click through, run uv run coverage html and open htmlcov/index.html in your browser; lines that never ran are marked red.
Step 5: Read the report, then test what it shows
Read each row as a question: what behaviour lives on those lines, and does it matter? Three answers matter.
events/models.py, line 498: in locked(), a database error that is not a lock timeout is raised again. Chapters 31 and 33 both insisted on this rule (“do not hide other errors”), and no test proves it.
events/views.py, lines 187 to 189: the edit page when the event is busy. A member would see this; no test does.
registrations/views.py, lines 100 and 101: the cancel page after the event has started. The model refuses it and a model test proves that; the page’s answer is untested.
The branch 485->489 is the SQLite path of locked(), which never runs on PostgreSQL; the SQLite run in Chapter 33 covers it. Lines in config/settings.py run only when a setting is missing, and asgi.py and wsgi.py run only under a web server (Chapter 63). Those are reasons, not tests to write.
A new subject gets its own file, which is what the packages are for. Create events/tests/test_locking.py:
events/tests/test_locking.py
"""The event lock's other answers (found with coverage)."""
from unittest import mock
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.exceptions import ValidationError
from django.db import OperationalError
from django.test import TestCase
from django.urls import reverse
from psycopg import errors
from config.helpers import as_sent, save_event
from events.models import Event, OrganizerAssignment, refusal
User = get_user_model()
def database_error(sqlstate):
"""Return Django's error for a psycopg one with sqlstate."""
error = OperationalError('the row could not be locked')
error.__cause__ = errors.lookup(sqlstate)()
return error
class LockErrorTests(TestCase):
"""locked() calls only a lock timeout "busy"."""
def setUp(self):
self.event = save_event()
def lock_fails_with(self, sqlstate):
"""Make the row lock fail with that database code."""
rows = mock.Mock()
rows.get.side_effect = database_error(sqlstate)
return mock.patch.object(
Event.objects, 'select_for_update',
return_value=rows,
)
def test_a_lock_timeout_is_busy(self):
with self.lock_fails_with('55P03'):
with self.assertRaises(ValidationError) as caught:
self.event.locked()
self.assertEqual(caught.exception.error_list[0].code,
'busy')
def test_any_other_database_error_is_raised(self):
# 53100 is PostgreSQL's "disk full".
with self.lock_fails_with('53100'):
with self.assertRaises(OperationalError):
self.event.locked()
class BusyEditTests(TestCase):
"""The edit page while another request holds the row."""
def test_a_busy_edit_says_so_and_saves_nothing(self):
event = save_event()
sam = User.objects.create_user('sam@example.org',
display_name='Sam')
sam.user_permissions.add(
Permission.objects.get(codename='change_event')
)
OrganizerAssignment.objects.create(event=event,
member=sam)
self.client.force_login(sam)
busy = refusal(['busy'])
with mock.patch.object(Event, 'locked',
side_effect=busy):
response = self.client.post(
reverse('events:edit', args=[event.pk]),
as_sent(event, location='Room 2'),
)
self.assertContains(
response, 'Otahque is busy. Please try again.'
)
event.refresh_from_db()
self.assertEqual(event.location,
'Leeds Central Library')
database_error() builds the error Django raises for psycopg’s, with the PostgreSQL error code on its cause, as Chapter 33’s locked() reads it. mock.patch.object replaces select_for_update() for the duration of the with block only. 53100 is PostgreSQL’s code for “disk full”, an error that must never be shown as “busy”.
In registrations/tests/test_registrations.py, add to MyRegistrationsTests, before test_a_visitor_is_sent_to_sign_in:
registrations/tests/test_registrations.py
def test_the_page_refuses_after_the_start(self):
past = timezone.now() - timedelta(minutes=5)
Event.objects.filter(pk=self.event.pk).update(
starts_at=past, registration_closes_at=past,
cancellation_deadline=past,
)
self.client.force_login(self.sai)
response = self.client.post(
url('cancel', self.sais.pk), follow=True
)
self.assertContains(
response, 'The event has started, so this place '
'can no longer be cancelled.'
)
self.sais.refresh_from_db()
self.assertEqual(self.sais.status, 'active')
Chapter 2’s PR-3 also listed a case nobody tested: a cancellation that overlaps a registration request. Chapter 33’s design note argued it can only cause a refusal, never a place too many. Prove it. Add to the end of RaceTests:
registrations/tests/test_registrations.py
def test_a_cancel_during_a_request_only_refuses(self):
raj = verified('raj@example.org')
rajs = self.event.register(raj, self.now)
sai = verified('sai@example.org')
meet = threading.Barrier(2, timeout=5)
count = Event.places_taken
def counted(event):
taken = count(event)
meet.wait() # Sai's request has counted...
meet.wait() # ...and Raj's cancel is saved.
return taken
def cancel():
meet.wait()
place = Registration.objects.get(pk=rajs.pk)
done = place.cancel(self.now)
meet.wait()
return done
with mock.patch.object(Event, 'places_taken',
counted):
outcomes = at_once(cancel, self.register(sai))
# Sai counted Raj's place, so she is told "full",
# although it is free a moment later. A refusal,
# never a place too many (PR-3).
self.assertEqual(outcomes, [True, ['full']])
self.assertEqual(self.event.places_taken(), 0)
The meeting point holds Sai’s request just after it has counted Raj’s place, lets Raj’s cancel save, and only then lets Sai’s request decide. Run the two apps:
Terminal
uv run python manage.py test events registrations --parallel
Output
Found 255 test(s).
Creating test database for alias 'default'...
...
Ran 255 tests in ...s
OK
They pass at once: the code was right, and what was missing was the proof. A test you have never seen fail may not be able to fail, so make one fail on purpose. In events/models.py, inside locked(), change the raise under if code != LOCK_NOT_AVAILABLE: to pass, and run the new file:
Terminal
uv run python manage.py test events.tests.test_locking
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
django.core.exceptions.ValidationError: ['Otahque is busy.
Please try again.']
Ran 3 tests in ...s
FAILED (errors=1)
The disk-full error came back as “busy”, and the test caught it. Change pass back to raise and run it again: three tests, OK. Measure once more:
Terminal
uv run coverage erase
uv run coverage run manage.py test --parallel
uv run coverage combine
uv run coverage report
events/views.py and registrations/views.py have left the report: every line in them ran. Notice what the percentage did: it barely moved, from 97% to 98%, while three rules went from unchecked to checked. That is why this book sets no coverage target.
Common Error: coverage reports a low figure, or “No data to report”
A figure far below the serial run means the workers were not measured: check parallel and concurrency in pyproject.toml, and run coverage combine before coverage report. “No data to report” after combine means there were no data files, usually because coverage run was skipped or erase ran after it. Files listed from .venv mean source is missing.
Step 6: A test that depends on the order
Run the accounts tests backwards:
Terminal
uv run python manage.py test accounts --reverse
Output
Found 86 test(s).
Creating test database for alias 'default'...
...
AssertionError: 0 != 1
Ran 86 tests in ...s
FAILED (failures=1)
The test passes in the normal order. Reversed, the sign-up test that expects a confirmation email gets none. The cause is in django-allauth’s settings: it sends at most one confirmation email per address every three minutes, and it counts them in Django’s cache. Run backwards, an earlier test has already sent one to the same address, the count is still in the cache, and allauth quietly sends nothing. The other account test classes clear the cache in setUp; SignUpTests never did. In accounts/tests/test_accounts.py, give SignUpTests the same start:
accounts/tests/test_accounts.py
url = '/accounts/signup/'
def setUp(self):
# allauth sends one confirmation email per address
# every three minutes, counted in the cache: start
# each test with an empty cache, as others do.
cache.clear()
def test_the_page_asks_for_name_and_zone(self):
Terminal
uv run python manage.py test accounts --reverse
Output
Found 86 test(s).
Creating test database for alias 'default'...
...
Ran 86 tests in ...s
OK
Running the whole suite reversed takes a few minutes, so it goes on the release checklist in Step 12 rather than into every run. test --shuffle goes further: it runs a random order and prints its seed, and --shuffle SEED repeats that order.
A test can also depend on time. While this chapter was being checked, on a machine running both shells’ test suites at once, Chapter 33’s test_the_last_place_goes_to_one_member failed once: the second request was told ['busy'] instead of ['full']. With the lock, the first request holds the event row while it waits up to two seconds at the meeting point; the second request waits for the row, and gives up after the three-second limit of Chapter 33. On a loaded machine the margin between two and three seconds ran out. The race tests are about taking turns, not about “busy”, which has its own test, so the meeting point should lift the limit while it is in use. In registrations/tests/test_registrations.py, add an import:
registrations/tests/test_registrations.py
import threading
from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
and replace meet_after_counting() with:
registrations/tests/test_registrations.py
@contextmanager
def meet_after_counting(timeout=2):
"""Make each request wait, after counting, for the other.
Without a lock both count before either inserts, so
the race happens every time. With the lock the other
request is still waiting for the event row, so the
meeting times out and the requests take turns. The
lock's time limit is raised meanwhile: on a busy
machine the wait for the row can pass 3 s, and these
tests are about turns, not "busy".
"""
barrier = threading.Barrier(2, timeout=timeout)
count = Event.places_taken
def counted(event):
taken = count(event)
try:
barrier.wait()
except threading.BrokenBarrierError:
pass
return taken
with mock.patch.object(Event, 'places_taken', counted):
with mock.patch('events.models.LOCK_TIMEOUT', '30s'):
yield
@contextmanager turns a function with one yield into something with can use: both patches are in place for the body of the with block, and both are undone after it, even if the test fails.
Terminal
uv run python manage.py test registrations -k RaceTests
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
A test that fails now and then is not “flaky” by nature; it depends on something it does not control, here the speed of the machine. Find that thing, as with the cache, rather than running the test again until it passes.
Step 7: When a test fails under --parallel
Make a test fail on purpose: in audit/tests/test_audit.py, change self.assertEqual(add.status_code, 403) to self.assertEqual(add.status_code, 200). Run it with another app, in parallel:
Terminal
uv run python manage.py test audit events --parallel
Output
Found 195 test(s).
...
TypeError: cannot pickle 'traceback' object
The failure happened in a worker process, and the runner could not send its traceback back, so it crashed without naming the test. Add tblib, which can:
Terminal
uv add --dev tblib==3.2.2
Run the same command again:
Output
Found 195 test(s).
Creating test database for alias 'default'...
...
AssertionError: 403 != 200
Ran 195 tests in ...s
FAILED (failures=1)
Now the failing test is named and its assertion shown, exactly as in a run without --parallel. Undo the change; the file is as you committed it in Step 3, so Git can restore it:
Terminal
git restore audit/tests/test_audit.py
Step 8: A skip link and messages coloured by meaning
Chapter 2 asked for the main journeys to work with a keyboard alone. With the keyboard, every page begins with the navigation: four or five presses of Tab before reaching the event. A skip link is the page’s first link, “Skip to the main content”, hidden until Tab reaches it. Messages have a second problem: “This place was already cancelled.” is information, not success, yet it shows in the success colour, because the layout knows only two kinds.
Write the tests first. In events/tests/test_events.py, add to the end of LayoutTests:
events/tests/test_events.py
def test_a_skip_link_comes_first(self):
link = ('<a href="#main" class="skip-link">'
'Skip to the main content</a>')
for url, template, title in self.pages:
with self.subTest(url=url):
response = self.client.get(url)
self.assertContains(response, link, html=True)
page = response.content.decode()
self.assertLess(page.index('skip-link'),
page.index('site-nav'))
self.assertIn('<main id="main"', page)
In registrations/tests/test_registrations.py, add to MyRegistrationsTests, before test_a_visitor_is_sent_to_sign_in:
uv run python manage.py test events registrations --parallel
Output
Found 257 test(s).
Creating test database for alias 'default'...
...
AssertionError: False is not true : Couldn't find
'alert-info' in the following response
Ran 257 tests in ...s
FAILED (failures=4)
In templates/base.html, replace the lines from <body> to the message’s alert class with:
templates/base.html
<body>
{# First on the page: Tab once, Enter, and the keyboard #}
{# skips the navigation (Chapter 34). #}
<a href="#main" class="skip-link">Skip to the main
content</a>
{% include "includes/site_nav.html" %}
<main id="main" tabindex="-1"
class="mx-auto w-full max-w-6xl space-y-4 px-4 pt-6
pb-12 sm:px-6 lg:px-8">
{% if messages %}
<div role="status" class="space-y-2">
{% for message in messages %}
<div class="alert
{% if message.level_tag == 'error' %}alert-error
{% elif message.level_tag == 'warning' %}
alert-warning
{% elif message.level_tag == 'info' %}alert-info
{% else %}alert-success{% endif %}">
id="main" is where the link leads, and tabindex="-1" lets the browser move the keyboard focus there, so the next Tab continues inside the page. Messages now take daisyUI’s info and warning classes too. Otahque’s theme defines a warning colour (Chapter 33) but no information colour, so alert-info would be grey. In static/otahque/source.css, add two lines to the theme, after --color-warning-content:
Dark blue on light blue has a contrast ratio of about 9 to 1, well above the 4.5 to 1 that WCAG asks of normal text. Then, inside @layer components, before the .form-grid comment:
static/otahque/source.css
/* Off the screen until a keyboard user reaches it with
Tab; then it shows at the top left. */
.skip-link {
position: absolute;
top: -5rem;
left: 1rem;
z-index: 50;
padding: 0.5rem 1rem;
border-radius: var(--radius-field);
background-color: var(--color-primary);
color: var(--color-primary-content);
font-weight: 600;
}
.skip-link:focus {
top: 0.75rem;
outline-color: var(--color-base-content);
}
/* The skip link moves focus to main; no ring is needed
on the page area itself. */
main:focus {
outline: none;
}
Build the stylesheet and run the tests:
Terminal
npm run build
uv run python manage.py test events registrations --parallel
Output
Found 257 test(s).
Creating test database for alias 'default'...
...
Ran 257 tests in ...s
OK
Open any page, click the address bar, and press Tab once: the link appears at the top left. Press Enter, then Tab again: the focus is on the first link of the page itself. Figure 34.3 shows the link and an information message on a phone and a desktop.
Figure 34.3 — The skip link on a desktop and an information message on a phone.
Step 9: The acceptance trace
Now the record Soni asked for. Create docs/acceptance/M2.md. Each rule lists its allowed and refused cases and the tests that check each; every name is written Class.test_name in backticks, with its app in brackets.
docs/acceptance/M2.md
# M2 acceptance trace: the first release
Each rule from Chapter 2 (Table 2.3), the cases that prove
it, and the tests that check each case. Names are
`Class.test_name`; the app is given in brackets.
`TraceTests` (config) fails if a named test is missing.
Evidence: `check.py` passes locally and in CI on the commit
tagged v0.1.0, with the suite also run in reverse order.
The release checklist is docs/release-checklist.md.
## PR-1 One confirmed registration
Allowed:
- An eligible member gets one place (registrations):
`RegisterTests.test_a_place_is_made`,
`RegisterPageTests.test_a_member_registers_with_one_post`
- The member and the organizer see it (registrations):
`MyRegistrationsTests.test_the_page_lists_upcoming_places`,
`AttendeeListTests.test_the_list_shows_contacts_and_counts`
Refused, and nothing saved:
- A repeated request keeps one place (registrations):
`RegisterTests.test_a_second_request_keeps_one_place`,
`RegisterPageTests.test_two_posts_make_one_place`,
`RaceTests.test_the_same_member_twice_gets_one_place`
- Full, closed, or not published (registrations):
`RegistrationRuleTests.test_a_full_event_says_so`,
`RegistrationRuleTests.test_closing_is_exclusive`,
`RegistrationRuleTests.test_a_past_event_is_closed`,
`RegistrationRuleTests.test_only_published_events_take_places`,
`RegisterTests.test_a_refusal_names_why_and_saves_nothing`
- Signed out, or the email not confirmed (registrations):
`RegisterPageTests.test_a_visitor_signs_in_and_comes_back`,
`RegistrationRuleTests.test_an_unconfirmed_email_is_named`
## PR-2 Cancellation releases one place
Allowed:
- The first cancel releases one place (registrations):
`CancelTests.test_cancel_releases_the_place_once`,
`MyRegistrationsTests.test_confirm_then_cancel`
- A late cancel is allowed and marked (registrations):
`CancelTests.test_late_from_the_deadline`,
`MyRegistrationsTests.test_a_late_cancel_is_marked`
- The member may register again (registrations):
`CancelTests.test_a_member_may_register_again`
Refused, or changes nothing:
- A repeat, or a lost response sent again (registrations):
`CancelTests.test_a_stale_copy_changes_nothing`,
`MyRegistrationsTests.test_a_repeated_cancel_is_information`
- After the start (registrations):
`CancelTests.test_no_cancel_once_the_event_starts`,
`MyRegistrationsTests.test_the_page_refuses_after_the_start`
## PR-3 Never more places than capacity
PostgreSQL only; the race tests skip on SQLite.
- Two members for the last place (registrations):
`RaceTests.test_the_last_place_goes_to_one_member`
- A cancel overlaps a request (registrations):
`RaceTests.test_a_cancel_during_a_request_only_refuses`
- Capacity lowered below the places taken (events,
registrations):
`CapacityTests.test_below_the_places_taken_is_refused`,
`CapacityTests.test_the_admin_refuses_it_too`,
`RaceTests.test_capacity_edit_counts_a_place_being_made`
- A request that waits too long is told "busy" (events,
registrations):
`RaceTests.test_busy_while_another_request_holds_it`,
`BusyEditTests.test_a_busy_edit_says_so_and_saves_nothing`
## PR-4 Own records, assigned events
Allowed:
- An organizer edits an assigned event (events):
`EditAccessTests.test_organizer_gets_the_form`
- The attendee list for its organizers (registrations):
`AttendeeMatrixTests.test_every_row`
Refused, nothing changed or shown, attempt recorded:
- Another member's place (registrations):
`MyRegistrationsTests.test_someone_elses_place_is_missing`
- Another organizer's event, or access revoked (events):
`EditAccessTests.test_member_may_see_but_not_edit`,
`EditAccessTests.test_revoked_organizer_is_refused`,
`PermissionMatrixTests.test_every_row`
- Contacts stay off public pages (registrations):
`AttendeeListTests.test_contacts_stay_off_the_event_page`
- A form sent without its CSRF token (events):
`CsrfTests.test_a_post_without_the_token_is_refused`,
`EditCsrfTests.test_an_edit_without_the_token_is_refused`,
`ActionCsrfTests.test_publish_needs_the_token`
- Refusals are recorded (events):
`AuditTrailTests.test_refusals_by_members_are_recorded`
## PR-5 Publication boundary
Allowed:
- A complete draft is published by its organizer (events):
`PublishTests.test_an_organizer_publishes_a_complete_draft`,
`PublishTests.test_visitors_see_it_once_it_is_published`
Refused:
- Drafts are hidden from visitors and members (events):
`EventDetailTests.test_drafts_are_hidden`
- An incomplete draft stays a draft (events):
`ReadinessTests.test_every_missing_detail_is_named`,
`ReadinessTests.test_a_refused_publish_changes_nothing`
- Someone who may not edit it (events):
`PublishTests.test_a_member_who_may_not_edit_is_refused`
- An edit from an out-of-date page (events):
`EditVersionTests.test_a_save_from_an_old_page_is_refused`
## PR-6 Access management
Allowed:
- The administrator adds an organizer (events):
`OrganizerPageTests.test_an_administrator_adds_an_organizer`,
`OrganizerRuleTests.test_an_organizer_is_added_and_recorded`
Refused:
- An ordinary member, recorded (events):
`OrganizerPageTests.test_others_get_403_and_are_recorded`
- Changes need a recent sign-in (events):
`OrganizerPageTests.test_changes_need_a_recent_sign_in`
- The last organizer stays (events):
`OrganizerRuleTests.test_the_last_organizer_stays`
## Quality: time, access, recovery
- Times in the event's zone, and the viewer's (events):
`EventDetailTests.test_time_in_event_time_zone`,
`BothTimesTests.test_another_zone_shows_both`
- A lost response, sent again, is safe: PR-1 and PR-2.
- Status lookup: My registrations, PR-1.
- Keyboard: the skip link is tested (events):
`LayoutTests.test_a_skip_link_comes_first`.
The keyboard-only journey is checked by hand with the
UI checklist in docs/release-checklist.md. Partly met:
browser tests that press the keys come in Chapter 58.
## Quality: responsiveness
Deferred: no workload or target is agreed yet. Chapter 66
measures it. Not a release blocker for a pilot.
## Known limits
- A cancel saved while another request counts can refuse
that request although a place is free a moment later
(PR-3, the overlap test). It never gives a place too
many. The member can press Register again.
- Not in M2, so not tested here: email notices, the
waitlist, check-in, and reminders (M3).
- The UI checklist is a first check, not an accessibility
certification.
Read it as Soni would. Every PR has a test for each case Chapter 2 listed, the refused cases included. The quality rows say what is met, what is partly met, and what is deferred, with the chapter that continues each. The known limits are written, not hidden.
A trace written by hand goes stale the first time someone renames a test. Make the trace check itself. Create config/tests/test_acceptance.py:
config/tests/test_acceptance.py
"""The acceptance trace names only tests that exist."""
import re
from importlib import import_module
from django.conf import settings
from django.test import SimpleTestCase
TRACE = settings.BASE_DIR / 'docs/acceptance/M2.md'
APPS = ['accounts', 'audit', 'config', 'events',
'registrations']
NAME = re.compile(r'`(\w+Tests)\.(test_\w+)`')
def test_classes():
"""Yield every test class in the apps' tests packages."""
for app in APPS:
folder = settings.BASE_DIR / app / 'tests'
for path in sorted(folder.glob('test*.py')):
module = import_module(f'{app}.tests.{path.stem}')
yield from vars(module).values()
class TraceTests(SimpleTestCase):
"""docs/acceptance/M2.md, checked against the tests."""
def test_every_named_test_exists(self):
names = NAME.findall(TRACE.read_text(encoding='utf-8'))
self.assertGreater(len(names), 40)
found = {(c.__name__, m) for c in test_classes()
if isinstance(c, type) for m in dir(c)}
missing = [f'{c}.{m}' for c, m in names
if (c, m) not in found]
self.assertEqual(missing, [])
It reads every name in backticks from the trace, imports every test module of the five apps, and lists any name that no class defines. assertGreater(len(names), 40) guards against a trace that loses its names entirely. Also add the short guide to how Otahque is tested, docs/testing.md, for whoever joins next:
docs/testing.md
# How Otahque is tested
## Where tests live
Each app has a `tests/` package. Its `test_<app>.py` holds
the tests of the earlier chapters; a new subject gets its
own `test_<subject>.py` beside it. Helpers that more
than one app's tests use live in `config/helpers.py`, which
the runner does not collect: its name does not start with
"test". Helpers for one app stay in that app's tests.
## Which tool for which question
| Question | Tool |
|---|---|
| Is this function right, no database? | `SimpleTestCase` |
| Is this rule right, with the database? | `TestCase` |
| Does this page answer as it should? | the test client |
| Does this middleware work alone? | `RequestFactory` |
| What if two requests overlap? | `TransactionTestCase` |
| Does a test class share costly rows? | `setUpTestData` |
`TestCase` undoes each test inside a transaction, so other
connections never see its rows; race tests need
`TransactionTestCase`, which commits and empties the tables
afterwards, and PostgreSQL.
## Commands
uv run python check.py
uv run python manage.py test --parallel --reverse
uv run coverage run manage.py test --parallel
uv run coverage combine
uv run coverage report
Coverage is read, not targeted: a line that ran is not a
rule that was checked. docs/acceptance/M2.md names the
tests behind each rule.
Terminal
uv run python manage.py test config
Output
Found 15 test(s).
Creating test database for alias 'default'...
...
Ran 15 tests in ...s
OK
Step 10: One command, then CI
The checks a change must pass are three commands. Put them in one file beside manage.py, so that you and CI run exactly the same thing. Create check.py:
check.py
"""Run the checks every change must pass, as CI does.
Usage: uv run python check.py
Runs Django's system checks, the migration check, and the
whole test suite, in that order. It stops at the first
check that fails and exits with that check's code, so CI
marks the run as failed.
"""
import subprocess
import sys
CHECKS = [
['manage.py', 'check'],
['manage.py', 'makemigrations', '--check', '--dry-run'],
['manage.py', 'test', '--parallel'],
]
def main():
"""Run each check; return the first failure's code."""
for args in CHECKS:
print('== python', ' '.join(args), flush=True)
result = subprocess.run([sys.executable, *args])
if result.returncode:
print('== failed:', ' '.join(args))
return result.returncode
print('== all checks passed')
return 0
if __name__ == '__main__':
sys.exit(main())
makemigrations --check --dry-run fails if a model changed without a migration, and writes nothing. subprocess.run() runs each command with the same Python, and the first failure ends the script with its exit code, which is how CI knows the run failed.
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
No changes detected
== python manage.py test --parallel
Found 362 test(s).
System check identified no issues (0 silenced).
Ran 362 tests in ...s
OK
== all checks passed
Now the workflow. Create .github/workflows/ci.yml; the two folders start with a dot:
.github/workflows/ci.yml
# Run check.py on every push and pull request, on Linux,
# against a fresh PostgreSQL 18 (Chapter 34).
name: Checks
on:
push:
pull_request:
jobs:
checks:
runs-on: ubuntu-24.04
timeout-minutes: 20
services:
postgres:
image: postgres:18
env:
POSTGRES_PASSWORD: ci-only-password
ports:
- 5432:5432
# Start the steps only once the server answers.
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
env:
DB_ENGINE: django.db.backends.postgresql
DB_NAME: otahque
DB_USER: postgres
DB_PASSWORD: ci-only-password
DB_HOST: localhost
DB_PORT: "5432"
PGPASSWORD: ci-only-password
steps:
- uses: actions/checkout@v7.0.1
- uses: astral-sh/setup-uv@v10.3.3
with:
version: "0.13.5"
- name: Install the locked packages
run: uv sync --locked
- name: Create the databases (Chapter 32)
run: |
for name in otahque otahque_template; do
psql -h localhost -U postgres -c \
"CREATE DATABASE $name TEMPLATE template0
LOCALE_PROVIDER builtin
BUILTIN_LOCALE 'C.UTF-8'"
done
- name: Make a secret key for this run only
run: |
key=$(python3 -c \
'import secrets; print(secrets.token_hex(32))')
echo "DJANGO_SECRET_KEY=$key" >> "$GITHUB_ENV"
- name: Run the checks
run: uv run python check.py
Read it from the top. on: push runs it for every push to any branch, and for pull requests (Chapter 64). The job runs on Ubuntu 24.04, named exactly so that an upgrade is your decision. services starts PostgreSQL 18 in a container beside the job, and the health options make the steps wait until it answers. The env lines are the DB_* settings Chapter 32 introduced, here as environment variables instead of a .env file. actions/checkout and astral-sh/setup-uv are ready-made steps, each pinned to an exact release, and setup-uv installs the uv version the book uses. uv sync --locked installs exactly what uv.lock names, and fails if the lock no longer matches pyproject.toml. The databases are made as Chapter 32 made them, with the builtin C.UTF-8 locale. The secret key is made fresh for each run and never stored: the tests need a key, not your key. Figure 34.4 shows the run in order.
Figure 34.4 — The CI run, from push to a green or red mark.
Commit everything from Steps 4 to 10:
Terminal
git add .
git commit -m "Trace M2, measure coverage, and check in CI"
Output
[main 346a603] Trace M2, measure coverage, and check in CI
15 files changed, 662 insertions(+), 3 deletions(-)
Now give the repository a home on GitHub. Sign in at github.com, choose New repository, name it otahque, choose Private, and add nothing else: no README, no .gitignore, no licence, because your repository already has its history. GitHub shows the repository’s address. Connect your repository to it and send your history; replace YOUR-NAME with your GitHub name:
Terminal
git remote add origin https://github.com/YOUR-NAME/otahque.git
git push -u origin main
A remote is another copy of the repository that Git can send to and fetch from, and origin is the usual name of the first one. -u makes your main follow origin/main, so later a plain git push is enough. The first push asks you to sign in; on Windows, Git Credential Manager opens a browser window. Git prints:
Output
To https://github.com/YOUR-NAME/otahque.git
* [new branch] main -> main
branch 'main' set up to track 'origin/main'.
On GitHub, open the repository’s Actions tab. A run named after your commit starts within seconds. Open it, then the checks job, and expand Run the checks:
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
No changes detected
== python manage.py test --parallel
Creating test database for alias 'default'...
Cloning test database for alias 'default'...
Cloning test database for alias 'default'...
Found 362 test(s).
System check identified no issues (0 silenced).
Ran 362 tests in ...s
OK
== all checks passed
The same 362 tests, on Linux, on PostgreSQL 18, from a clean start, the race tests included: none was skipped. The list of steps on the left shows each one ticked.
Common Error: the CI run fails before the tests
“Set DJANGO_SECRET_KEY” means the key step is missing or after the checks. A connection error on port 5432 means the services block or a DB_* line is wrong, or the health options were left out, so the checks started before PostgreSQL. uv sync --locked failing with “The lockfile needs to be updated” means pyproject.toml changed without uv lock: run uv lock locally, commit uv.lock, and push. Never change the workflow to uv sync without --locked to make it pass: that hides the stale lock instead of fixing it.
Step 11: A red run, on a branch
A branch is a separate line of history. Work on a branch does not change main until you choose to bring it in, so it is the safe place to try something. Make one:
Terminal
git switch -c try-ci
Now make a mistake that a code review could easily miss. In registrations/tests/test_registrations.py, rename test_a_place_is_made to test_a_member_gets_a_place. The test still passes, but the trace names the old name. Locally:
Terminal
uv run python manage.py test config
Output
Found 15 test(s).
Creating test database for alias 'default'...
...
AssertionError: Lists differ:
['RegisterTests.test_a_place_is_made'] != []
Ran 15 tests in ...s
FAILED (failures=1)
On GitHub, the run for try-ci turns red. Its log names the check that failed and the reason:
Output
== python manage.py check
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
FAIL: test_every_named_test_exists
(config.tests.test_acceptance.TraceTests
.test_every_named_test_exists)
AssertionError: Lists differ:
['RegisterTests.test_a_place_is_made'] != []
First list contains 1 additional elements.
First extra element 0:
- ['RegisterTests.test_a_place_is_made']
+ []
Ran 362 tests in ...s
FAILED (failures=1)
== failed: manage.py test --parallel
The fix is to change the trace in the same commit as the rename. Here the rename was only an exercise, so throw the branch away, on your computer and on GitHub:
git branch -D deletes a branch that was never brought into main; its commit is no longer part of any branch. main never had the mistake.
Step 12: The release checklist, and the tag
A release is a commit you can name and return to. Before naming one, run a checklist, and stop if any box stays empty. Create docs/release-checklist.md:
docs/release-checklist.md
# Release checklist
Run it before tagging a release. Every box must be ticked on
the commit you tag; a box you cannot tick stops the release.
## Checks
- [ ] `git status --short` prints nothing.
- [ ] `uv run python check.py` ends with "all checks passed"
(system checks, migrations, the whole suite).
- [ ] `uv run python manage.py test --parallel --reverse`
passes too: no test depends on the order.
- [ ] The race tests ran, not skipped: the suite used
PostgreSQL.
- [ ] CI is green for this commit.
- [ ] docs/acceptance/M2.md matches what was tested, its
known limits included.
## UI, at 390 and 1280 pixels wide
On the event list, an event page, My registrations, and the
new event and edit pages:
- [ ] Nothing scrolls sideways; text and buttons fit.
- [ ] Tab reaches "Skip to the main content" first, then
every link, field, and button in order, each with a
visible ring.
- [ ] Register and cancel can be done with the keyboard
alone (Tab, Enter, Space).
- [ ] Messages say in words what happened; colour only
repeats it.
- [ ] Text is readable at 200% zoom.
## Then
- [ ] Tag the commit: `git tag -a v0.1.0 -m "..."`.
- [ ] Push the tag: `git push origin v0.1.0`.
Go through it. The order check takes a few minutes:
Terminal
uv run python manage.py test --parallel --reverse
Output
Found 362 test(s).
Creating test database for alias 'default'...
...
Ran 362 tests in ...s
OK
Do the UI part by hand, at 390 and 1280 pixels wide; your browser’s developer tools can set the width. Then commit the checklist and push, and wait for CI to turn green for this commit:
A tag is a permanent name for one commit. -a makes an annotated tag, which records who tagged it, when, and why. v0.1.0 follows semantic versioning: 0 because the product is still in its first, pre-1.0 phase, and the first minor release of it. It matches the version = "0.1.0" line that uv init wrote into pyproject.toml. Tag the commit CI passed, push the tag, and list it:
Terminal
git tag -a v0.1.0 -m "First release: M2, the trace holds"
git push origin v0.1.0
git tag -n
Output
v0.1.0 First release: M2, the trace holds
36bd0f5 Add the release checklist
346a603 Trace M2, measure coverage, and check in CI
7704048 Move the tests into packages; share helpers
befbc11 Lock the last place; refuse stale edits
That is M2: the first release, with its evidence in docs/acceptance/M2.md, its limits written down, and its checks green on a machine nobody prepared by hand.
When something goes wrong
Table 34.1 — Diagnosing test layout, coverage, and CI
Symptom
Likely cause
Recovery
ImportError: Failed to import test module
A relative import in a moved file, or an import from an old tests module
Name the app: from events.models import ...; shared helpers from config.helpers
Fewer tests than before the move
A tests folder without __init__.py, or a file not named test*.py
Add the empty __init__.py; rename the file
Ran 0 tests in a new file
The file is named testing.py or helpers_test.py
Test files start with test
coverage: a low figure under --parallel
Workers not measured
parallel and concurrency in pyproject.toml; coverage combine
A test fails only in the full suite or reversed
State left by another test: cache, rows, settings
Clear it in setUp; repeat with --reverse or --shuffle SEED
Race test gets ['busy'] now and then
The wait for the row passed the lock's limit on a loaded machine
meet_after_counting() raises the limit while it is in use
TypeError: cannot pickle 'traceback' object
A failure in a worker, without tblib
uv add --dev tblib==3.2.2; or rerun without --parallel
TraceTests lists a name
A test named in M2.md was renamed or removed
Update the trace in the same commit
CI: Set DJANGO_SECRET_KEY
The key step is missing
The "Make a secret key" step before the checks
CI: connection refused on 5432
No service, or checks started before it was ready
The services block with its health options
CI: The lockfile needs to be updated
pyproject.toml changed without uv lock
uv lock locally; commit uv.lock
git push asks for a password and refuses it
GitHub no longer accepts account passwords for Git
Sign in through Git Credential Manager, or use a personal access token
No recovery here touches your data: tests run in their own test database, coverage writes only its own files, and a CI machine is thrown away after each run.
GitLab, Codeberg, and other CI hosts; macOS runners
Chapter 64
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 33 checkpoint with a reader’s data, against a PostgreSQL 18.3 server made for the check. The CI runs are real runs of this workflow on GitHub Actions, in a private repository made for the book’s checks; in the printed outputs its address is replaced by the reader’s (YOUR-NAME/otahque), and the project folder is shortened to ....
Que. 3 After Step 2, from . import views in the moved events tests failed. Why?
Flip to check your answerFold answer back
Answer. A relative import is relative to the package of the file that contains it. The file now lives in the events.tests package, so . means events.tests, which has no views. from events import views names the app.
Que. 4 Why is the shared helpers module called helpers.py and not testing.py?
Flip to check your answerFold answer back
Answer. The runner collects every module whose name matches test*.py. testing.py would be imported as a test module; helpers.py is imported only by the tests that need it.
Que. 5 Coverage under --parallel reported a fraction of the real figure until pyproject.toml was changed. What did the settings change?
Flip to check your answerFold answer back
Answer. parallel = true makes each process write its own data file, and concurrency = ["multiprocessing", "thread"] makes coverage.py follow the worker processes and threads. coverage combine joins the files before the report.
Que. 6 The three new tests of Step 5 passed at once. Why make one fail on purpose?
Flip to check your answerFold answer back
Answer. A test that has never failed may be unable to fail, for example if it asserts the wrong thing. Breaking the code it guards and seeing it fail proves it checks what it claims.
Que. 7 Why does the workflow make a new secret key for every run instead of using a repository secret?
Flip to check your answerFold answer back
Answer. The tests need some key, not the real one. A throwaway key cannot leak anything, and nothing has to be stored or rotated. The real key is a deployment matter (Chapter 63).
Que. 8 What does uv sync --locked refuse to do, and why does that matter in CI?
Flip to check your answerFold answer back
Answer. It refuses to install when uv.lock no longer matches pyproject.toml, instead of quietly resolving new versions. CI then tests exactly what the lock names, and a forgotten uv lock turns the run red.
Mini-Challenge
The report still lists accounts/models.py, line 73. Decide whether it deserves a test, and if it does, write one in a new file, accounts/tests/test_profile.py, then measure again.
Hint: open the file at that line. What calls it, and would anyone notice if it broke?
Model answer: line 73 is Profile.__str__, the name the admin’s pages use for a profile. It is cheap to test and visible to the administrator, so a test is worth it:
accounts/tests/test_profile.py
"""A profile's name, as the admin's pages show it."""
from django.test import TestCase
from accounts.models import Profile, User
class ProfileNameTests(TestCase):
"""Profile.__str__, the line coverage left untested."""
def test_a_profile_is_named_after_its_member(self):
sai = User.objects.create_user('sai@example.org',
display_name='Sai')
profile = Profile.objects.create(user=sai)
self.assertEqual(str(profile), f'Profile of {sai}')
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
A defensible alternative is to leave it, noting that the admin page tests would catch a crash, though not a wrong name. Either way, write the reason down.
What We Learned
Each Django test tool answers one question; acceptance tests are tests chosen and named for a product rule.
A tests/ package per app lets new subjects get their own files; move first, split later, and check that the count is unchanged.
Shared helpers belong in one module the runner does not collect; one app’s helpers stay with its tests.
Coverage under --parallel needs parallel, concurrency, and coverage combine; without them the workers are not measured.
Coverage shows what ran, not what was checked: read the report for behaviours, and make a new test fail once.
--reverse and --shuffle find tests that depend on what an earlier test left behind.
A test that fails now and then depends on something it does not control, such as time; find it rather than rerunning.
tblib lets --parallel report failures from worker processes.
An acceptance trace links each rule to named tests, states its limits, and can check its own names.
CI runs one command, check.py, on a clean machine with a fresh PostgreSQL, the locked packages, and a throwaway key.
A release is a tagged commit that passed its checklist, with its limits written down.
Key terms
Use Table 34.3 to explain this chapter’s ideas in your own words.
Table 34.3 — Key terms from Chapter 34
Term
Meaning
Unit test
A test of one function or method alone.
Integration test
A test of several pieces working together, such as a page and its database.
Acceptance test
A test chosen and named for a rule the product promised.
Test coverage
Which lines and branches ran while the tests ran.
Development dependency
A package needed to develop and check the project, not to run it.
Order-dependent test
A test whose result depends on what ran before it.
Acceptance trace
The record linking each rule to its cases, tests, and evidence.
Continuous integration
Running the checks automatically on every change, on a clean machine.
Workflow
A CI file saying when to run, on what machine, and which steps to take.
Remote
Another copy of the repository that Git sends to and fetches from.
Branch
A separate line of history.
Tag
A permanent name for one commit, such as v0.1.0.
Readiness checkpoint: you are ready for Chapter 35 when every app’s tests are in a tests/ package, uv run python check.py ends with “all checks passed” and 362 tests, the accounts tests pass with --reverse, docs/acceptance/M2.md exists and its test passes, the skip link appears on the first Tab, and git tag -n lists v0.1.0. With GitHub, the Actions tab shows a green run for the tagged commit.
Git Commit
Your Chapter 34 work was committed in three steps. Step 3: “Move the tests into packages; share helpers”, with the five tests/ packages and config/helpers.py. Step 10: “Trace M2, measure coverage, and check in CI”, with the coverage settings, the development dependencies, the new tests, the order and timing fixes, the skip link and message colours, the trace and its test, docs/testing.md, check.py, and the workflow. Step 12: “Add the release checklist”, tagged v0.1.0.
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to debugging a suite and to deciding a release. They are extension questions, not a gate to the next chapter.
L1 (Junior): What are unit, integration, and acceptance tests, in Django terms?
What the interviewer is testing: Can you map the words people use to the tools Django gives?
Flip to check your answerFold answer back
Perfect answer: A unit test checks one function or method alone, often a SimpleTestCase with no database: Otahque’s database_error() cases in LockErrorTests check one method’s answer to one error. An integration test checks pieces together: a page test sends a request through URLs, middleware, the view, the template, and the database with the test client. An acceptance test checks a rule the product promised, in terms the person who asked for it would recognize, such as “two members for the last place get one place”. It uses the same tools; what makes it acceptance is that it is chosen and named for a rule, and recorded in a trace.
Table 34.4 — Test kinds in Django terms
Kind
Otahque example
Tool
Unit
LockErrorTests
TestCase, mock
Integration
BusyEditTests
The test client
Acceptance
RaceTests, named under PR-3
TransactionTestCase
Behind the scenes:
test kinds (summary)
unit one function, alone
integration pieces together, often through a page
acceptance a promised rule, named in the trace
Code proof: the trace’s own test checks that every acceptance test it names exists:
Output
Found 15 test(s).
Creating test database for alias 'default'...
...
Ran 15 tests in ...s
OK
Common mistakes:
Calling every test that touches the database an integration test, whatever it checks.
Treating acceptance as a separate tool rather than a choice of what to check.
Follow-up the interviewer might ask:
Is RequestFactory unit or integration? (Closer to unit: it skips URLs and middleware to check one piece.)
Would a browser test change the kinds? (It is integration across the browser too; Chapter 58.)
L2 (Mid-Level): Predict what coverage reports for a parallel run with no settings
What the interviewer is testing: Do you know how coverage.py measures, and where processes hide code?
Flip to check your answerFold answer back
Perfect answer: A figure far too low. coverage run measures the process it starts. manage.py test --parallel starts worker processes, and the tests run there; the main process mostly waits, so most of the code that ran is never recorded. Setting parallel = true gives each process its own data file, concurrency = ["multiprocessing", "thread"] makes coverage.py start in each worker and follow threads, and coverage combine joins the files. Then the figure matches a run without --parallel.
Figure 34.5 — Measuring a parallel run.
Behind the scenes:
coverage and processes (summary)
main process measured, mostly waiting
workers run the tests; measured only if told
combine joins one data file per process
Code proof: Step 4’s first run, without the settings:
Output
Name Cover
----------------------------------------------------
events\models.py 36%
events\views.py 28%
...
----------------------------------------------------
TOTAL 34%
Common mistakes:
Reading the low figure as missing tests and writing tests for code already tested.
Forgetting combine, then reporting only the main process’s file.
Follow-up the interviewer might ask:
Why add thread to concurrency? (Naming multiprocessing alone turns off thread measurement; the race tests run code in threads.)
Would running without --parallel be simpler? (Yes, and slower; CI runs the same command people run.)
L3 (Senior): Defend an acceptance trace over a coverage target
What the interviewer is testing: Can you argue what evidence a release needs?
Flip to check your answerFold answer back
Perfect answer: A coverage target measures lines that ran. Otahque was at 99% of its lines while three rules had no test, including “a database error that is not a timeout must not be called busy”. Adding those tests moved the figure one point. A target invites tests that run lines and check nothing, and says nothing about a rule with no code. A trace starts from the rules: for each, the allowed and refused cases, the tests that check them, the run that passed, and the limits. It answers the release question directly. Coverage is still useful, as a list of candidates for the trace to consider.
Figure 34.6 — Evidence for a release.
Behind the scenes:
two kinds of evidence (summary)
coverage which lines ran
trace which rule, which case, which test, which run
Code proof: the report after Step 5: three rules more, one point more:
Writing a trace that lists only passing tests and hides the gaps.
Follow-up the interviewer might ask:
Would you ever gate on coverage? (On a drop, perhaps, as a prompt to look; never as the definition of done.)
How do you keep a trace from going stale? (Make it fail: TraceTests checks every name.)
L4 (Staff): A test passes alone and fails in the full suite. Diagnose it
What the interviewer is testing: Can you find shared state systematically, not by guessing?
Flip to check your answerFold answer back
Perfect answer: Something an earlier test left behind is changing this one. First make it repeatable: run with --reverse, or --shuffle and keep the seed, then narrow the run to the failing test plus the classes that ran before it. Then ask what state is shared outside the test transaction: the cache, settings changed without override_settings, files, class attributes, rows committed by a TransactionTestCase, mocks left running. In Otahque, the sign-up test failed reversed because django-allauth counts confirmation emails per address in the cache, and an earlier test had used the allowance. The fix is to start the class clean, as its neighbours do, not to reorder the tests.
Figure 34.7 — Finding state left by another test.
Behind the scenes:
shared state (summary)
TestCase undoes database rows of the test
not undone cache, files, module state, mocks
Code proof: Step 6, reversed, before the fix:
Output
Found 86 test(s).
Creating test database for alias 'default'...
...
AssertionError: 0 != 1
Ran 86 tests in ...s
FAILED (failures=1)
Common mistakes:
Marking the test as flaky and rerunning until it passes.
Fixing the order instead of the state, so the next new test breaks it again.
Follow-up the interviewer might ask:
Why does TestCase not undo the cache? (It undoes the database transaction only; the cache is outside it.)
When would you use --shuffle in CI? (With the seed printed, regularly; a failing seed can be repeated.)
L5 (Lead): Defend when to tag the first release
What the interviewer is testing: Can you decide a release on evidence and say what it does not include?
Flip to check your answerFold answer back
Perfect answer: Tag when the checklist is complete on one commit: every check passes, the suite passes in reverse order, CI is green for that commit, the trace covers every rule with its gaps and limits written, and the UI checks are done at both widths. Not before, because a tag is a promise people will refer back to; and not later, waiting for perfection, because written limits are acceptable for a pilot and hidden ones are not. Otahque’s v0.1.0 goes to two events with known limits: a cancel during a request can refuse that request, the keyboard journey is checked by hand, and responsiveness has no agreed target. Each limit names the chapter that continues it.
Figure 34.8 — Deciding the first release.
Behind the scenes:
a release (summary)
checklist every box, on one commit
tag an annotated name for that commit
trace what it proves, and what it does not
Code proof: the tag and the commits it closes:
Output
v0.1.0 First release: M2, the trace holds
36bd0f5 Add the release checklist
346a603 Trace M2, measure coverage, and check in CI
7704048 Move the tests into packages; share helpers
befbc11 Lock the last place; refuse stale edits
Common mistakes:
Tagging a commit CI never ran on, or tagging before the trace is updated.
Treating the tag as a deployment: it names a version; deploying it is Chapters 63 and 64.
Follow-up the interviewer might ask:
What would make you move a tag? (Nothing: make a new version, v0.1.1, and say why.)
When does Otahque reach 1.0? (When the product is promised to be stable for its users; that is a product decision, not a test result.)