Challenge 3: Prove the Rollback Behavior — Possible Solution ==================================================================== # catalog/tests.py from django.test import TestCase from .models import Book, Author class RollbackDemoTests(TestCase): def test_a_creates_a_book(self): author = Author.objects.create(name="Test Author") Book.objects.create(title="Temporary Book", author=author, price=1.00) self.assertEqual(Book.objects.count(), 1) def test_b_sees_no_books(self): # No setUp() creates any books, and test_a_creates_a_book ran # before this test alphabetically — yet this still passes. self.assertEqual(Book.objects.count(), 0) # Running: # python manage.py test catalog.tests.RollbackDemoTests # produces: # .. # Ran 2 tests in 0.031s # OK WHY test_b_sees_no_books PASSES EVEN THOUGH IT RUNS AFTER test_a_creates_a_book ------------------------------------------------------------------------------ Django's TestCase wraps EACH test method — not the whole test class, and not the whole test run — in its own database transaction. When test_a_creates_a_book finishes running, Django rolls back that transaction, which undoes every database change made during that test, including the Author and Book created inside it. By the time test_b_sees_no_books starts, the database is back to exactly the state it was in before test_a_creates_a_book ever ran — as if that test's changes never happened at all. This is fundamentally different from a setup where tests share one long-lived database connection with no automatic rollback: in that scenario, test_b_sees_no_books would see the leftover Book from test_a_creates_a_book and fail with "1 != 0" — exactly the kind of test-order-dependent flakiness the chapter's automatic rollback exists to prevent. WHY THIS WORKS -------------- - Test method execution order is not guaranteed to match the order methods are written in the file (Django's default test runner often sorts alphabetically, which is why these methods are deliberately named test_a_... and test_b_... to make the "runs after" relationship explicit and predictable for this demonstration) — but regardless of execution order, each test's rollback means order never actually matters for correctness. - This is the concrete, hands-on version of the chapter's core claim: TestCase's automatic rollback means tests never pollute each other, and this challenge proves it by making one test create data and a DIFFERENT test immediately verify that data is gone.