Django’s testing framework (built on Python’s unittest) provides a TestCase class with database transaction isolation, a Client for simulating requests, fixture loading, and assertion helpers, while pytest-django adds fixtures, parametrization, and plugin ecosystem for more expressive and maintainable test suites.
Testing solves the problem of verifying application behavior automatically and preventing regressions. Django’s TestCase wraps each test in a transaction that rolls back after completion, ensuring database isolation without manual cleanup. The Client simulates HTTP requests (GET, POST, PUT, DELETE) with session and authentication support, allowing end-to-end view testing. pytest-django enhances this with dependency injection via fixtures, parametrize for data-driven tests, and parallel execution.
- TestCase subclass —
class MyTest(TestCase):— each test method runs in atomic transaction - setUpTestData — Class method runs once per class; creates objects in DB before all tests
- setUp — Instance method runs before each test; for per-test state
- Client requests —
self.client.get('/url/'),self.client.post('/url/', data, format='json') - Authentication —
self.client.force_login(user)orself.client.credentials(HTTP_AUTHORIZATION=...) - Assertions —
assertEqual,assertContains,assertRedirects,assertTemplateUsed,assertNumQueries - Fixtures —
fixtures = ['initial_data.json']loads JSON/XML/YAML before tests
- Transaction isolation:
TestCaserolls back after each test;TransactionTestCasedoesn’t (for testing transactions) - Test Client:
client.get(),post(),put(),patch(),delete(),head(),options(),trace() - Authentication helpers:
force_login(user),logout(),credentials(**headers) - Database assertions:
assertNumQueries(n)catches N+1;assertQuerysetEqual(qs, values) - Fixtures:
loaddata/dumpdata;factory_boyfor programmatic test data (preferred over JSON fixtures) - pytest-django:
pytest.mark.django_dbenables DB access;client,admin_client,userfixtures built-in
- Built from: ORM — Test data creation and assertions
- Built from: Function-Based Views — Test view behavior
- Built from: Class-Based Views — Test CBV methods
- Built from: Authentication System — Test auth flows
- Built from: Database Transactions — TestCase isolation mechanism
- Builds into: Test Client — Request simulation API
- Builds into: Factory Boy — Test data generation
- Builds into: pytest-django — Modern test runner with fixtures
- Builds into: Coverage Reporting — Code coverage metrics
- Builds into: Mocking — Isolate units from dependencies
- Contrasts with: pytest Standalone — Django-specific extensions vs pure pytest
- Related: CD Integration — Automated test runs on push
- Related: Test Database Config —
DATABASES['TEST']settings
- TestCase vs TransactionTestCase:
TestCasefaster (rollback); useTransactionTestCaseonly when testing transaction behavior setUpTestDatacaveats: Objects created here persist across tests in class; don’t modify them in testsassertNumQueries: Counts all queries including middleware; usewith self.assertNumQueries(2):context manager- Migrations in tests:
migrateruns automatically;--nomigrationsspeeds up but may miss migration bugs - Static/media in tests:
MEDIA_ROOTshould use temp dir;STATICFILES_STORAGE=StaticFilesStorage(no manifest)