liveBook · Manning

Unittest

As explained in Django in Action

unittest is Python's standard-library framework for defining, discovering, running, and reporting automated tests.

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

How Django in Action covers it

How deep it goes
Explains fixtures, cases, suites, runners, assertions, discovery, database isolation, setup, and exception checks.
Examples
Demonstrates a missing-musician 404 request and a ValueError check using assertRaises.
What you can do after
Build and run TestCase classes that discover tests, assert results, exercise Django views, and verify raised exceptions.
How it connects
Connects test cases with fixtures, test suites, test runners, assertions, Django ORM, Django views, pytest, and nose.

Also explained in

Compare how 4 books explain unittest →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.