Django includes a test framework built on Python's unittest (and pytest-django in many teams). Test models, views, forms, and APIs to catch regressions before deploy.
Test client
from django.test import TestCase, Client
class ArticleTests(TestCase):
def test_index_returns_200(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
What to test
- Model methods and validation
- Forms—valid/invalid data
- Views—status codes, redirects, context
- Permissions—anonymous vs authenticated
Important interview questions and answers
- Q: Test database?
A: Django creates a separate test DB—tests can run transactions rolled back per test. - Q: fixtures vs factories?
A: Fixtures are static JSON; factories (factory_boy) generate test data programmatically—factories scale better. - Q: Integration vs unit?
A: Unit tests isolate logic; integration tests hit DB and URL routing—balance speed and confidence.
Self-check
- What does Django's test Client simulate?
- Why test permission rules?
Tip: Test permission denials (403/redirect) alongside happy paths—auth bugs are common and cheap to catch with Client tests.