• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

Formal Definition

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.

Explanation

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.

How It Works

  1. TestCase subclassclass MyTest(TestCase): — each test method runs in atomic transaction
  2. setUpTestData — Class method runs once per class; creates objects in DB before all tests
  3. setUp — Instance method runs before each test; for per-test state
  4. Client requestsself.client.get('/url/'), self.client.post('/url/', data, format='json')
  5. Authenticationself.client.force_login(user) or self.client.credentials(HTTP_AUTHORIZATION=...)
  6. AssertionsassertEqual, assertContains, assertRedirects, assertTemplateUsed, assertNumQueries
  7. Fixturesfixtures = ['initial_data.json'] loads JSON/XML/YAML before tests

Visual Explanation

testing TestClass class ViewTest(TestCase):    @classmethod    def setUpTestData(cls):        cls.user = User.objects.create(...) def test_post_create(self):    self.client.force_login(self.user)    response = self.client.post(...)    self.assertEqual(response.status_code, 201) Transaction Transaction Wrapper (rollback after test) TestClass->Transaction 1. Atomic block Client Test Client Simulates HTTP + Session + Auth TestClass->Client 2. Make requests Fixtures Fixtures JSON/XML/YAML Pre-load data TestClass->Fixtures 4. Load data Assertions Assertions assertEqual assertContains assertNumQueries TestClass->Assertions 5. Verify Database Test DB (created/destroyed per test run) Client->Database 3. Hits test DB

Semantic Network

semantic_testing THIS Testing (TestCase, Client) PRE1 Models / ORM THIS--PRE1 built from PRE2 Views (FBV/CBV) THIS--PRE2 built from PRE3 Authentication System THIS--PRE3 built from PRE4 Database Transactions THIS--PRE4 built from OUT1 Test Client Request Simulation THIS--OUT1 builds into OUT2 Fixtures / Factory Boy THIS--OUT2 builds into OUT3 pytest-django Fixtures/Parametrize THIS--OUT3 builds into OUT4 Coverage Reporting THIS--OUT4 builds into OUT5 Mocking (unittest.mock) THIS--OUT5 builds into CON1 pytest (Standalone) THIS--CON1 contrasts with CON2 Jest/Vitest (JS Testing) THIS--CON2 contrasts with REL1 CI/CD Integration THIS--REL1 related REL2 Test Database Config THIS--REL2 related

Key Properties

  • Transaction isolation: TestCase rolls back after each test; TransactionTestCase doesn’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_boy for programmatic test data (preferred over JSON fixtures)
  • pytest-django: pytest.mark.django_db enables DB access; client, admin_client, user fixtures built-in

Connections

Edge Cases & Gotchas

  • TestCase vs TransactionTestCase: TestCase faster (rollback); use TransactionTestCase only when testing transaction behavior
  • setUpTestData caveats: Objects created here persist across tests in class; don’t modify them in tests
  • assertNumQueries: Counts all queries including middleware; use with self.assertNumQueries(2): context manager
  • Migrations in tests: migrate runs automatically; --nomigrations speeds up but may miss migration bugs
  • Static/media in tests: MEDIA_ROOT should use temp dir; STATICFILES_STORAGE = StaticFilesStorage (no manifest)