unittest is Python’s standard-library framework for organizing automated tests. Its mental model has four parts: fixtures prepare and clean up test data, test cases perform checks, test suites collect cases, and test runners find, execute, and report them. section 8.1.2
A test case is a class whose methods begin with test_. Assertions such as assertEqual() raise an exception when a condition fails. The runner discovers those methods, runs them, and reports whether they pass. section 8.10
Django builds on unittest with its own TestCase and runner. The runner finds tests.py files in app directories, creates a separate database copy, and lets tests use the ORM and a client for view requests. setUp() and setUpClass() prepare shared data; each test method runs inside a transaction that is undone afterward. section 8.1.2 section 8.10
Check a missing musician
A Django test can request a URL with the test client and verify that an unknown musician produces a 404 response. For ordinary Python code, assertRaises(ValueError) checks that a code block raises the expected exception; reaching its end without raising makes the test fail. section 8.4
Listing 8.4 Testing an exception got caused
# bands/tests.py
...
def raises_an_error(): #1
raise ValueError()
class TestBands(TestCase):
...
def test_raises_an_error(self):
with self.assertRaises(ValueError): #2
raises_an_error()
Use the listing to see assertRaises wrapped around a function expected to raise ValueError. section 8.4



