The Double Loop: Functional Tests Lead, Unit Tests Follow
When Harry Percival set out to teach test-driven development with Python, he chose a single project – a to-do list application built with Django – and a strict pedagogical rule: do nothing until you have a test. The mechanism that enforces this discipline is what technical reviewer Emily Bache called the Double-Loop TDD cycle. An outer loop of Selenium-driven functional tests (FTs) defines what the user should experience. An inner loop of unit tests, written against Django’s test client and the standard unittest framework, defines how the code delivers that experience.
The workflow reads like a conversation. You write a functional test that fails because the feature does not exist. You start the development server. You watch the test fail in the browser. Then you drill down: the FT complains that a URL resolves to nothing, so you write a unit test for the URL configuration. That test fails, so you add a view. The view test fails because the template is missing, so you write a template test. Each red test pulls the next slice of implementation into existence. When the FT finally passes, you have a vertical slice of working software verified at every layer.
Percival illustrates this with a technique he calls “programming by wishful thinking.” In a template, you write {{ list.get_absolute_url }} and {{ list.name }} before those methods exist on the model. The template test fails. The model test fails. You implement the methods. The tests pass. The wish becomes reality, guided entirely by the test suite’s demands.
Three Layers of Tests, Three Different Jobs
A mature test suite in this style naturally stratifies into three layers, each with distinct speed, scope, and maintenance characteristics.
- Functional tests drive a real browser via Selenium. They exercise the full stack: JavaScript, CSS, Django views, the ORM, the database, and the web server. They catch “unknown unknowns” like missing migrations or broken static-file configuration. They are slow and brittle – seven tests might take over a minute in continuous integration – but they provide the highest confidence that the user’s journey works.
- Integrated tests use Django’s TestClient and a real database (often SQLite in memory). They run in fractions of a second – fifty tests in well under a second – and are quick to write. However, they may not drive good design because they allow the test to reach deep into implementation details.
- Isolated tests mock external dependencies entirely. They run in milliseconds and are the best tool for design feedback: if a test requires elaborate mock setup, the code is telling you its dependencies are tangled. The trade-off is coupling to implementation details; a refactoring that changes List.objects.create() to List() breaks the test even if behavior is unchanged.
Percival cites Gary Bernhardt’s heuristic: if the test suite takes more than a few seconds to run, the feedback loop breaks and it takes roughly fifteen minutes to recover the state of flow. This speed budget forces deliberate choices about where a test belongs.
Deployment as a Test Target
One of the book’s most distinctive insights is treating deployment scripts as code that deserves the same TDD rigor as the application. The functional test suite includes a test that runs against a staging server. To make that test pass, you need a reproducible, idempotent deployment process.
The book develops a Fabric script (later translated to Ansible) that provisions a server from scratch: creating directory layouts, generating a SECRET_KEY via random.SystemRandom(), bootstrapping a virtual environment, running collectstatic and migrate, and configuring Nginx and Gunicorn (via Upstart in the 2014 edition). Each step is idempotent – re-running the script converges to the same state. Git tags (DEPLOYED-YYYY-MM-DD/HHMM and a force-updated LIVE tag) provide an audit trail and instant rollback.
This approach turns deployment from a fragile manual ritual into a verified, testable deliverable. The staging FT becomes the ultimate integration test: if it passes, the deployment worked.
Mocking with Discipline
Mocks are powerful but dangerous. Percival’s rule is simple: patch at the point of use, not the point of definition. If a view calls authenticate from django.contrib.auth, you patch accounts.views.authenticate, not the original module. This ensures the test verifies the wiring as it exists in production.
He introduces contract testing as a safeguard. When an outside-in TDD session crosses a boundary – say, a view calling a form’s save(owner=request.user) method – you write down the contract: the form initializes with POST data, is_valid() returns a boolean, save(owner) handles authentication, and save() returns the created list. These contracts live in a scratchpad or as self.fail() placeholders in the test. Later, integrated tests verify that the real implementations honor the contract.
A warning echoes through the chapters: “too many mocks are a code smell.” Isolated tests can miss integration bugs, such as a view expecting form.save() to return a list when the form actually returns None. The remedy is a thin layer of integrated “sanity check” tests that exercise real collaborations.
JavaScript TDD and the Async Challenge
The double loop extends to the browser. When a functional test demands behavior that requires JavaScript – dynamic list updates, for instance – the inner loop switches to QUnit with HTML fixtures (#qunit-fixture for isolation) and Sinon.JS for fake XHR and spies.
A key technique is dependency injection for testability. The navigator object (used by Mozilla Persona) is injected into Superlists.Accounts.initialize so tests can supply a stub. Sinon’s fakeServer simulates HTTP responses – including 403 errors – allowing deterministic testing of jQuery promise chains. Tests assert that navigator.id.logout is called only after server.respond(), proving the async flow works without real network calls.
Selenium Reliability: Explicit Waits and Page Objects
Flaky Selenium tests are the bane of functional testing. Percival identifies implicitly_wait as a trap: it only applies to find_element and can match stale elements across page navigations. The solution is a hand-rolled wait_for helper (five-second default, 0.1-second retry, catching AssertionError and WebDriverException) that preserves readable unittest failure messages. This Selenium Interact/Wait Pattern becomes mandatory after every navigation or AJAX trigger.
As the base functional test class grew past 1,500 lines, the Page Object pattern tamed the complexity. HomePage and ListPage classes encapsulate locators and interactions, receiving the test instance for access to browser, wait_for, and assertions. Method chaining (return self) enables fluent calls: HomePage(self).go_to_home_page().start_new_list(…) returns a ListPage ready for the next assertions.
Django Quirks That Bite
The book surfaces several Django behaviors that surprise newcomers and veterans alike:
- Model.save() does not run full validation. You must call full_clean() explicitly, typically inside a ModelForm.
- SQLite does not enforce TextField(blank=False) at the database level, and makemigrations reports “No changes detected” for that constraint.
- unique_together alters default ordering; an explicit ordering = (‘id’,) restores predictability.
- Database IntegrityError arrives too late for user-friendly feedback. The ExistingListItemForm overrides validate_unique to catch the model ValidationError, remap the error dictionary to {‘text’: [DUPLICATE_ITEM_ERROR]}, and call self._update_errors(e) so the form displays a clean message.
These are not theoretical; they appear as failing tests that drive the correct implementation.
Architectural Patterns for Testability
In the final chapters, Percival introduces two architectural patterns that mitigate the downsides of heavy mocking. Ports and Adapters (Hexagonal/Clean Architecture) isolates the core domain from boundaries – database, filesystem, UI, network. The core is tested with fast isolated tests; boundaries are tested with integrated tests. Functional Core, Imperative Shell (from Gary Bernhardt) pushes side effects to a thin outer layer, maximizing pure functions that require no mocks at all.
Percival is candid about his authority here: “grossly underqualified… pinch of salt.” The book offers no empirical validation, only the observation that these patterns align with the test-hierarchy trade-offs experienced during the project.
Practical Habits That Scale
Beyond the patterns, the book codifies habits that keep a TDD project healthy:
- Three Strikes Then Refactor: Wait for three duplications before extracting a helper. The check_for_row_in_list_table helper emerged only after the third assertIn with a list comprehension.
- Commit Before Refactor: A clean git history lets you git diff –staged to verify that refactoring changed only structure, not behavior.
- Direct ORM or Factory Boy for Test Data: JSON fixtures become a “nightmare to maintain when your model changes.”
- Hierarchical Loggers: logging.getLogger(__name__) with per-app handlers in the LOGGING dict (disable_existing_loggers: False). Test log output via patch.object on the module logger.
- Zero Tolerance for Flaky Tests: A CI failure that passes locally signals non-determinism that demands root-cause analysis, not a re-run.
Spiking as a Controlled Departure
When facing an unfamiliar API – Mozilla Persona, in the book’s case – Percival sanctions a spike: a throwaway branch (persona-spike) where you prototype without tests. The goal is learning, not production code. Once the API is understood, you revert the spike and reimplement the feature via TDD, driven by a functional test. The spike used Mozilla’s public verifier, a custom ListUser model (email primary key, no password), and MockMyID for test isolation. This discipline prevents exploratory code from fossilizing into untested production paths.
Data Migrations Under Test
Appendix D recounts a production crisis: duplicate data blocked a unique_together constraint. The fix followed a testable workflow: copy production data locally (with a PII warning), write a corrective data migration using RunPython to append index suffixes to duplicate Item.text values per List, declare explicit migration dependencies before the schema migration, test locally, deploy to staging, run the functional tests. The staging FT caught the problem before it reached production – a testament to the double loop’s reach.
The 2014 Lens and Modern Practice
Reading the book today reveals its vintage. Django 1.7 (beta) used url() not path(); migrations were new; StaticLiveServerTestCase was the FT base class. Jenkins with ShiningPanda and Xvfb ran the CI pipeline; PhantomJS handled headless JavaScript tests (now deprecated in favor of headless Chrome/Firefox). Fabric 1.x depended on Python 2; Upstart managed processes (since replaced by systemd). The author explicitly disclaims deployment best-practice status: no HTTPS, no monitoring, SECRET_KEY edited directly on the server.
Yet the principles transcend the tooling. The double-loop cycle, the test hierarchy, the treatment of deployment as tested code, the mocking discipline, the explicit wait pattern, the contract-tracking habit – these remain relevant whether the stack is Django 5, FastAPI, or a Node.js service. The book’s enduring value is not the specific commands but the demonstration of how a test-first mindset shapes every layer of a project, from the model’s clean() method to the server provisioning script.