Introduction
Django extends Python's unittest assertions with web-specific assertions for testing HTTP responses, templates, and forms.
Key Concepts
Assertion: A statement that checks if a condition is true.
AssertionError: Raised when an assertion fails.
Deep Dive
Standard Assertions
pythonclass BasicAssertionTests(TestCase): def test_assertions(self): # Equality self.assertEqual(1 + 1, 2) self.assertNotEqual(1, 2) # Boolean self.assertTrue(True) self.assertFalse(False) # None self.assertIsNone(None) self.assertIsNotNone('value') # Containment self.assertIn('a', ['a', 'b', 'c']) self.assertNotIn('d', ['a', 'b', 'c']) # Type checking self.assertIsInstance([], list)
Django-Specific Assertions
pythonclass DjangoAssertionTests(TestCase): def test_response_assertions(self): response = self.client.get('/articles/') # Template assertions self.assertTemplateUsed(response, 'articles/list.html') self.assertTemplateNotUsed(response, 'error.html') # Content assertions self.assertContains(response, 'Welcome') self.assertNotContains(response, 'Error') # Redirect assertions response = self.client.get('/old-url/') self.assertRedirects(response, '/new-url/')
Exception Assertions
pythonfrom django.core.exceptions import ValidationError class ExceptionTests(TestCase): def test_raises_exception(self): with self.assertRaises(ValidationError): raise ValidationError('Invalid') with self.assertRaises(ValueError) as cm: raise ValueError('Bad value') self.assertIn('Bad', str(cm.exception))
Real World Context
Choosing the right assertion makes debugging failed tests dramatically easier. When assertTrue(a == b) fails, you see AssertionError: False is not true. When assertEqual(a, b) fails, you see the actual values of a and b. Django's custom assertions like assertContains and assertRedirects save dozens of lines of boilerplate in every test suite.
Common Pitfalls
- Using assertTrue for equality checks:
assertTrue(x == 5)gives unhelpful error messages. UseassertEqual(x, 5)instead. - Ignoring assertion messages: You can pass a
msgparameter to any assertion for context:self.assertEqual(x, 5, 'Score should be 5 after bonus'). - Not testing exception messages: Use
assertRaisesas a context manager to also verify the exception message content.
Best Practices
- Use specific assertions:
assertEqualoverassertTrue(a == b). - Check exception messages: Use context manager to verify message.
- One assertion focus: Each test should have one main assertion.
Summary
Django provides web-specific assertions for templates, responses, and redirects. Use specific assertions for clearer error messages when tests fail.