Skip to the workspace
Pebellslearn by building
Models, Views, Admin and Tests  ›  Capstone Project

tests.py — Proving It Works

tests.py 16 minDjango tests in tests.py subclass TestCase, run against a temporary test database, and use the test client to send fake requests and check the responses.

django / tests.py — Proving It Works

Explore each scene at your own pace.

01 · The rule

The rule

tests.py — Proving It Works

You changed the recipe URLs last week. Did the search page break? The detail page? The only honest way to know, every time, is to have the computer check. Django's test tools can pretend to be a browser, visit your pages and verify the answers in seconds.

The rule

Arrange data, send a fake request, assert on the response.

# recipes/tests.py
from django.test import TestCase
from django.urls import reverse
from .models import Recipe

class RecipeDetailTests(TestCase):
    def setUp(self):
        Recipe.objects.create(title="Tomato soup", slug="tomato-soup", minutes=25)

    def test_shows_recipe(self):
        url = reverse("recipes:detail", args=["tomato-soup"])
        response = self.client.get(url)
        self.assertContains(response, "Tomato soup")

    def test_missing_recipe_is_404(self):
        url = reverse("recipes:detail", args=["no-such-dish"])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

The parts:

  • TestCase from django.test, not plain unittest. It adds the test client and database handling.
  • Methods whose names start with test are tests; others, like setUp, are helpers. setUp runs before each test.
  • self.client sends requests through the whole stack, middleware, URLs, view and template, without a real server.
  • assertContains checks the status is 200 and the text appears in the page.
  • reverse() again: tests use names, so they survive URL changes too.

Run them:

python manage.py test recipes

Your real data is safe. Django creates a separate test database for the run and destroys it afterwards, and TestCase rolls back every test's changes, so tests never see each other's rows.

What to test first: each page loads, missing objects give 404, and any rule you care about, such as "quick recipes excludes a 45-minute stew".

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.