pytest-django
01 / 02

pytest-django: Fixture Reuse, Time Mocking & CI Practices

pytest-django: Fixture Reuse, Time Mocking & CI Practices

Fixtures vs. setUp/tearDown

pytest fixtures (defined once, often in conftest.py) are more composable and reusable across test modules than class-based setUp/tearDown hooks tied to one TestCase subclass -- and can be scoped per-function, per-class, per-module, or per-session.

Overriding Settings in a Single Test

def test_with_feature_flag(settings):
    settings.FEATURE_X_ENABLED = True
    # temporary override, scoped to this test only

Precise Assertions Over Weak Ones

Asserting a queryset's exact contents (not just its length) catches cases where the count happens to match but the actual returned objects are wrong -- a stronger, more meaningful check.

Mocking the Current Time

Freezing or mocking timezone.now() (often via freezegun) makes date/time-dependent tests (like an expiration check) deterministic, instead of depending on the actual moment the test happens to run.

--reuse-db Locally, Fresh in CI

--reuse-db speeds up local iterative test runs by skipping repeated schema recreation, while CI often still wants a genuinely fresh database to reliably catch migration issues a stale reused database might mask.

Coverage as a Gap-Finder, Not a Guarantee

pytest-cov quantifies which lines/branches are actually exercised by the suite, helping identify under-tested areas -- though high coverage alone doesn't verify assertion quality or guarantee correctness.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free