Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 77 ยท Testing

Testing Django Apps

Write Django tests with TestCase, setUpTestData, the test Client, fixtures and assertions like assertContains, assertRedirects and assertNumQueries.

Tests are what let you change code without fear. A good test suite tells you in seconds that a refactoring broke the login page, that a query now runs twice as many times as before, or that a form accepts an input it should reject. Django ships with a complete testing toolkit built on Python's unittest, so you can start without installing anything.

In this lesson you will learn how Django test classes work, how the test database is created and rolled back, how to drive your views with the test Client, how to load fixtures, and which Django-specific assertions save you the most time. The live examples define real TestCase classes and run them inside your browser, so you will see the same pass/fail results that python manage.py test prints on your machine.

How Django runs tests

On your own computer you run all tests of a project with:

TEXT
python manage.py test                 # everything
python manage.py test library         # one app
python manage.py test library.tests.BookViewTests.test_list_page
python manage.py test --keepdb        # reuse the test database between runs
python manage.py test --parallel      # use several processes
python manage.py test -k redirect     # only tests whose name matches

The test runner discovers files named test*.py, builds a separate test database (your real data is never touched), runs the migrations on it, executes every test and destroys the database afterwards. Each TestCase test additionally runs inside a transaction that is rolled back at the end, so tests cannot leak data into each other.

flowchart TD
    A["Create test database<br/>and run migrations"] --> B["Class setup<br/>setUpTestData runs once"]
    B --> C["Test 1: begin transaction,<br/>setUp, test, rollback"]
    C --> D["Test 2: begin transaction,<br/>setUp, test, rollback"]
    D --> E["Destroy test database"]

Data created in setUpTestData is shared by the class; everything a single test creates disappears with its rollback.

Choosing a test class

Django offers several base classes. Pick the lightest one that works:

Class Database Use it for
SimpleTestCase Blocked Pure logic, template rendering, URL resolving, anything without queries
TestCase Yes, wrapped in a rolled-back transaction Most tests: models, views, forms
TransactionTestCase Yes, truncates tables after each test Code that depends on real commits, on_commit hooks, transaction behavior
LiveServerTestCase Yes, plus a real HTTP server Browser-driven tests with Selenium or Playwright

TestCase is the default choice. It is also the fastest of the database-backed classes, because rolling back a transaction is cheaper than clearing tables.

Your first TestCase

A test method's name must start with test. Inside it you set up some data, perform an action and assert the result. A few habits help every suite:

  • One behavior per test. A failing test name should tell you what broke.
  • Arrange, act, assert. Prepare data, call the code, check the outcome.
  • No dependence on order. Each test builds what it needs (or inherits it from setUpTestData).

For data that every test in a class only reads, use setUpTestData. It runs once per class, which is much faster than rebuilding rows in setUp before every test. Django gives each test its own copy of the class-level objects, so one test modifying self.dune cannot disturb another.

The live examples below are not a normal Django project, so a few lines at the top stand in for what a project provides. We register a tiny stand-in app called library (so Django knows the model, which setUpTestData needs to copy objects), create the table with the schema editor instead of running migrations, and call setup_test_environment(), which the real test runner does for you. The test classes themselves are exactly what you would put in tests.py.

Python Model and view tests with TestCase

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the report: seven tests pass and test_a_failing_test fails with a message that tells you the two values it compared (0 != 99). Notice test_changes_are_rolled_back and test_previous_test_left_nothing_behind: the first creates a third book, yet the second still sees only two, proving that each test's changes are rolled back. The run() helper at the bottom only formats the output for this page; in a real project manage.py test does this for you, with dots and a summary.

The test Client

self.client is an instance of django.test.Client, a pretend browser. It builds a request, passes it through your entire stack (middleware, URL resolver, view, template) and returns the response, all without a network. You have used it in earlier lessons to explore views; in tests it is your main tool for view code.

Python
# read-only
response = self.client.get("/books/", {"page": 2})       # query string
response = self.client.post("/books/new/", {"title": "Kim"})  # form data
response = self.client.post("/api/books/", {"title": "Kim"}, content_type="application/json")
self.client.login(username="ada", password="secret")      # session login
self.client.force_login(user)                             # login without a password check
response = self.client.get("/old/", follow=True)          # follow redirects

The response carries extras that real responses do not: response.context (the template context), response.templates, and response.json(). Use force_login(user) in tests that are not about logging in; it is faster and does not depend on password hashing.

Django's assertions

On top of unittest's assertEqual, assertTrue and friends, Django adds assertions for web code. Prefer them over manual checks, since their failure messages are more helpful:

Assertion What it checks
assertContains(response, text, status_code=200, html=True) Status code plus the text appears (with html=True, comparison ignores whitespace and attribute order)
assertNotContains(response, text) The text is absent
assertRedirects(response, url) A redirect to url, and that url itself responds with 200
assertTemplateUsed(response, name) A template was rendered
assertJSONEqual(raw, expected) JSON equality, ignoring key order
assertQuerySetEqual(qs, values) A queryset's values equal a list (ordered unless ordered=False)
assertNumQueries(n) The code in the with block ran exactly n queries
assertFormError(form, field, errors) A form field has the given errors
assertRaises(Exc) An exception is raised (from unittest)

assertNumQueries deserves special mention: it turns the N+1 problem from ORM Performance into a regression test. If someone later removes a select_related(), the test fails immediately.

Fixtures and test data

There are three ways to create test data, from the simplest to the most reusable:

  1. Create objects in the test or setUp with Book.objects.create(...). Most readable for small cases.
  2. setUpTestData for class-wide, read-mostly data, as shown above.
  3. Fixtures: JSON (or YAML/XML) files that describe rows. You can create them with python manage.py dumpdata library --indent 2 > library/fixtures/books.json and then list them on the test class with fixtures = ["books.json"]. Django loads them before each test.

Fixtures are fine for small, stable reference data, but they are brittle for large datasets: the files go out of sync with your models and hide what a test depends on. Many teams prefer creating objects with small helper functions, which the next lesson develops into factories.

The second example loads a fixture with loaddata, tests a JSON endpoint and uses subTest to check several cases in one method while still getting a separate report for each. The fixture file is written to a temporary location, because the live runner has no project folder.

Python Fixtures, JSON endpoints and subTest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The deliberate failure 412 != 400 shows what a good message looks like: the actual value comes first, then the expected one. Note how setUp ran loaddata before every test, and each test still began with exactly two books.

Writing tests worth keeping

A test suite is only useful if you trust and run it. Some practical guidance:

  • Test behavior, not implementation. Assert on the response and the stored data, not on private helper calls.
  • Cover the unhappy paths: invalid input, missing permissions, empty results and boundary values are where bugs live.
  • Keep tests fast. Prefer SimpleTestCase when no database is needed, setUpTestData over setUp, and force_login over real logins. Speed up passwords in tests with a fast hasher (PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"] in a test-only settings module).
  • Do not test Django itself. You do not need a test proving that CharField stores strings, but you do need one for your own validation rules.
  • Run tests in CI on every push (see Docker, Celery and CI).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to data a TestCase test creates once the test ends?

    TestCase wraps every test in a transaction and rolls it back afterwards, so tests cannot affect each other. Data from setUpTestData is shared, but changes made inside a test are discarded.
  2. 2. Why use setUpTestData instead of setUp for reference rows?

    setUpTestData is a class method that runs once, so a class with twenty tests builds the data one time instead of twenty times. Each test still sees isolated copies of the objects.
  3. 3. Which assertion checks that a view does not run more queries than expected?

    assertNumQueries(n) used as a context manager fails when the block runs a different number of queries. It is a handy guard against N+1 regressions.
  4. 4. When should you choose SimpleTestCase over TestCase?

    SimpleTestCase blocks database access, which makes tests fast and prevents accidental queries. Use it for pure logic, template rendering and URL tests.
  5. 5. What does self.client.force_login(user) do?

    force_login attaches a session for the given user directly. It is faster than a real login and independent of passwords or hashers.

Summary

  • python manage.py test discovers test*.py files, creates a throwaway test database and reports failures with helpful messages.
  • Use TestCase for most tests (transaction rollback per test), SimpleTestCase for database-free tests, and TransactionTestCase or LiveServerTestCase only when needed.
  • setUpTestData builds shared data once per class; setUp runs before every test; fixtures load JSON data with fixtures = [...] or loaddata.
  • self.client sends requests through the full stack; use force_login for authenticated tests and follow=True to follow redirects.
  • Django adds assertContains, assertRedirects, assertTemplateUsed, assertJSONEqual, assertQuerySetEqual and assertNumQueries.
  • Test behavior and unhappy paths, keep the suite fast, and run it automatically.

Next lesson: Testing Patterns: Factories, Mocks and pytest-django.