liveBook · Manning

Test setup

As explained in Django in Action

setUp is a test lifecycle method invoked before each test method to prepare its required state.

setUp is a test lifecycle method that runs immediately before each test method. Use it to create the shared starting state that every test needs, such as ORM objects, while keeping each test independent. section 8.3

Listing 8.2 A test case for the musician view
# bands/tests.py
from datetime import date
from django.test import TestCase
from bands.models import Musician

class TestBands(TestCase):
    def setUp(self):  #1
        self.musician = Musician.objects.create(first_name="First",
            last_name="Last", birth=date(1900, 1, 1))

    def test_musician_view(self):
        url = f"/bands/musician/{self.musician.id}/"
        response = self.client.get(url)  #2

        self.assertEqual(200, response.status_code)
        self.assertEqual(response.context['musician'].id,
            self.musician.id)  #3
        self.assertIn(self.musician.first_name,
            str(response.content))  #4

The example creates a Musician in setUp, stores it as self.musician, requests the musician view, and checks the response status, context, and rendered content. section 8.3

A typical setUp flow looks like this:

  • Create the required model instance through the ORM inside setUp(). section 8.3
  • Assign the instance to self so every test method can use it. section 8.3
  • Exercise the view with Django’s test client and assert the expected response. section 8.3 section 8.10
  • Rely on Django’s per-test transaction rollback to return the database to a clean state afterward. section 8.3

How Django in Action covers it

How deep it goes
Explains invocation timing, ORM fixture creation, test-case attributes, and isolation through transaction rollback.
Examples
Uses a Musician fixture to test a view’s status code, response context, and rendered content.
What it assumes
Assumes familiarity with Python test classes and introduces database preparation through Django’s TestCase and ORM.
What you can do after
Build repeatable Django tests by preparing ORM fixtures once per test method.
How it connects
Connects setUp with Django TestCase, ORM models, database transactions, test clients, and assertions.

Also explained in

Compare how 2 books explain test setup →

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.