Django’s TestCase extends Python’s unittest.TestCase for web applications. A test runner finds test methods whose names begin with test_, runs them, and reports whether their assertions pass. Django adds a test database, ORM support, and a client for exercising views through URL routing. section 8.1.2 section 8.10
Create a test class by importing django.test.TestCase, inheriting from it, and adding test_ methods. The client’s get() and post() methods emulate requests: templates render, but no browser or JavaScript runs. Assertions such as assertEqual() check the response. section 8.2
A database-backed test typically follows this flow:
- Create required model objects in setUp(); it runs before each test method. section 8.3
- Request a routed URL with self.client.get() or self.client.post(). section 8.10
- Assert the status code, context, or rendered content. section 8.2 section 8.3
- Let Django undo database changes after the method, keeping tests isolated and order-independent. section 8.10
Testing a musician view
A TestBands class creates a Musician in setUp(), requests that musician’s URL, then checks for a 200 response, the expected context object, and the musician’s first name in the response content. 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
Use the listing as a compact pattern for arranging setup, a URL request, and assertions in one TestCase. section 8.3
For browser-level behavior, use LiveServerTestCase or StaticLiveServerTestCase with Selenium. They run a development server during tests; StaticLiveServerTestCase also serves static files. Ordinary TestCase calls views directly, so it cannot execute page JavaScript. section 8.7.1
