Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 77 ยท Testing

Testing Patterns: Factories, Mocks and pytest-django

Level up your Django tests with factory functions, unittest.mock for external services, override_settings, form and permission tests, pytest-django and coverage.

The previous lesson covered the mechanics: test classes, the test database, the Client and Django's assertions. Real projects add new problems. Creating realistic data becomes tedious, code calls payment gateways and weather APIs that you must not hit during tests, behavior depends on settings, and a suite with hundreds of tests needs structure and tooling.

This lesson collects the patterns that experienced Django teams rely on: factory functions for test data, mocks for external services, override_settings for configuration, focused tests for forms, permissions and APIs, then pytest-django and coverage. Most examples run live as real TestCase classes in your browser.

What to test, and at which level

Not every test needs the full stack. A healthy suite has many small, fast tests and fewer broad ones:

flowchart TD
    A["Few: end-to-end<br/>browser or live server"] --> B["Some: view and API tests<br/>Client, URLs, templates"]
    B --> C["Many: unit tests<br/>models, forms, services, helpers"]

Aim for a wide base of fast unit tests, a middle layer of view tests with the Client, and only a handful of browser tests.

Pure functions and model methods are easy to test and cheap to run. View tests confirm that URLs, middleware, permissions and templates cooperate. Browser tests are slow and fragile, so reserve them for the two or three journeys that must never break, such as signing up or paying.

Factories: test data without the noise

Every test needs data, and writing Order.objects.create(customer=..., total=..., status=...) with all required fields in every test hides what the test is about. A factory is a function (or class) that builds a valid object with sensible defaults, letting each test override only the fields that matter.

Python
# read-only: the pattern in its smallest form
def make_order(**overrides):
    values = {"customer": "someone", "total": 20, "status": "new"}
    values.update(overrides)
    return Order.objects.create(**values)

def test_free_shipping():
    order = make_order(total=80)      # only the interesting field is visible

Plain functions go a long way. Two refinements make them more robust:

  • Unique values: fields with unique constraints need a different value per call. A counter (itertools.count) or uuid solves that.
  • Related objects: a factory for Comment should create its own Post and User unless the test passes them in.

Libraries such as factory_boy (declarative factories with sequences and related factories) and model_bakery (automatically fills required fields with random valid data) build on the same idea. Learn the pattern with plain functions first; adopting a library later is a small step.

Mocking external services

A unit test must not call the real internet. Network calls are slow, flaky, may cost money and make it impossible to test failure cases such as timeouts. The solution is to replace the outgoing call with a mock, an object from unittest.mock that records how it was called and returns whatever you tell it to.

The key tools are:

  • mock.patch("package.module.name") or mock.patch.object(obj, "name") replaces an attribute for the duration of a with block or decorated test.
  • return_value=... sets what the fake returns; side_effect=SomeError(...) makes it raise.
  • assert_called_once_with(...) checks how your code used the dependency.

The most common mocking bug is patching the wrong place. Patch the name where your code looks it up, not where it was defined. If orders/views.py does from payments import charge, patch "orders.views.charge". Patching "payments.charge" would leave the view's own reference untouched, and the real function would still run.

Mock the boundary of your system (the HTTP client function, the email gateway), not your own internals. If you find yourself mocking a model method, the code probably needs a different design.

override_settings

Code often depends on settings: a free-shipping threshold, a feature flag, DEBUG, a cache backend. Tests must be able to change them temporarily. override_settings does that and restores the original value afterwards. It works as a class decorator, a method decorator or a context manager (with self.settings(...)).

Python Factories, override_settings and mocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details to notice. The factory gave every order a different customer, so unique-value rules never collide. And test_unmocked_call_is_caught proves a useful safety net: the stand-in fetch_rate raises if a test forgets to mock it, so an accidental real call fails loudly instead of silently reaching the internet. In real projects, libraries such as responses or respx (for requests and httpx) give the same protection for HTTP.

Testing forms, permissions and APIs

Three kinds of code deserve a standard recipe.

Forms. Instantiate the form with a dictionary, call is_valid() and assert on cleaned_data or errors. No Client or database is needed unless the form queries models. Test one valid case and each rule that can fail, using subTest to keep the cases in one method.

Permissions. Test both sides of every rule: the anonymous visitor, the logged-in user who lacks the permission, and the user who has it. Check the response (redirect to login, 403) and, for destructive views, that the data did not change. See Permissions, Groups and Authorization for the rules themselves.

APIs. Post JSON with content_type="application/json", assert the status code first and the body second (assertJSONEqual or response.json()), and cover validation errors and authentication failures as carefully as the happy path (see API Design).

The next example tests all three against a small app with the real auth models. It sets PASSWORD_HASHERS to a fast hasher, which is a standard trick to speed up tests that create users.

Python Testing a form, login protection and permissions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The comment about a "fresh object" points at a classic trap: Django caches a user's permissions on the user object the first time they are checked, so after granting a permission in a test, reload the user from the database before logging in.

Test-driven development of an API, with Docker

Test-driven development (TDD) reverses the usual order: you write a failing test first, then just enough code to make it pass, then clean up. The cycle is called red, green, refactor:

  1. Red: write a test that describes one behavior of the API. Run it and watch it fail for the right reason (a 404 because the endpoint does not exist yet, not a typo in the test).
  2. Green: write the simplest code that makes it pass.
  3. Refactor: improve the code while the tests keep you safe.

TDD fits APIs well because an API is a contract: status codes, JSON fields and validation messages are exactly what a test can state. The tests become the documentation, and a client team can read them to see what the endpoints promise. For one endpoint at a time, a typical test suite uses DRF's APITestCase and its self.client (an APIClient), which can send JSON with format="json" and log in with force_authenticate(user) (see DRF Authentication and DRF Permissions).

The example plays the whole first cycle against a real project written to the in-browser file system. It writes tests.py first, plus the smallest skeleton that lets the tests import (a model and an empty URL list), and runs the real Django test runner. Five tests fail with 404 because no endpoint exists. Then it adds a serializer, a ViewSet and a router (the pieces from DRF ViewSets, Routers and Generic Views) and runs the same tests again.

Python Red, then green: TDD for a DRF API with the real test runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first run is red: every test fails with 404 != 200 or 404 != 201, which is the right reason, since the routes are missing. After the implementation, the same five tests are green. Notice what the tests pin down without any implementation detail: an empty list on a fresh database, a 201 on creation, a 400 with a title error when a required field is missing, a 400 for a duplicate ISBN (the model's unique=True becomes a serializer validator automatically), and a 204 on delete.

Continue the cycle for each new requirement. Say the API must reject an ISBN that is not 13 digits. First write test_isbn_must_have_13_digits and watch it fail, then add validate_isbn to the serializer, and run again. Good habits while doing this:

  • One behavior per test, named after the behavior (test_delete_a_book), so a failure tells you what broke.
  • Assert on the contract, not on internals: status code, response JSON, and the visible effect (does the book exist afterwards?).
  • Test the sad paths (validation errors, missing objects, no permission) as carefully as the happy path.
  • Keep tests fast. The in-memory SQLite database used in tests makes a suite of hundreds of API tests finish in seconds, as long as you avoid network calls (mock them, see above).

Running the tests in Docker

Locally you would run python manage.py test. A Docker setup makes the environment part of the project: the same Python version and the same database engine as production, with no "works on my machine" differences. If production uses PostgreSQL, test against PostgreSQL, not only SQLite, because a few behaviors (case sensitivity, JSON lookups, constraints) differ.

DOCKERFILE
# Dockerfile (read-only)
FROM python:3.13-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["gunicorn", "config.wsgi", "--bind", "0.0.0.0:8000"]
YAML
# compose.yaml (read-only)
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: dev
      POSTGRES_DB: books
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 3s
      retries: 10

  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    environment:
      DATABASE_URL: postgres://postgres:dev@db:5432/books
      SECRET_KEY: dev-only
      DEBUG: "true"
    volumes:
      - .:/app                    # edit code on your machine, run it in the container
    ports:
      - "8000:8000"
    depends_on:
      db:
        condition: service_healthy   # wait until Postgres accepts connections
Terminal
# read-only
docker compose run --rm web python manage.py test            # run the whole suite
docker compose run --rm web python manage.py test bookapi --keepdb   # reuse the test database
docker compose run --rm web python manage.py test --parallel # use several CPU cores

How it fits together: docker compose run --rm web ... starts the database service (waiting for its health check), starts a one-off web container with your code mounted, runs the command and removes the container. Django's test runner creates a separate database named test_books for the run and drops it afterwards, so your development data is never touched (the database user needs permission to create databases). --keepdb keeps that database between runs for speed, and --parallel clones it per process.

In continuous integration, the same two files give you the same result on every push: the pipeline runs docker compose run --rm web python manage.py test, and a failing test fails the build (see Docker, Celery and CI for Django for a complete workflow). For a full container introduction, see the Docker tutorial.

pytest-django

Many Django teams prefer pytest over the built-in runner: plain assert statements, fixtures instead of setUp, parametrized tests and a rich plugin ecosystem. The pytest-django plugin connects pytest to Django's test database and settings. You install it with pip install pytest pytest-django and add a small configuration file:

INI
# pytest.ini (read-only; pytest needs a real shell and project files)
[pytest]
DJANGO_SETTINGS_MODULE = mysite.settings
python_files = tests.py test_*.py *_tests.py

The same tests look like this:

Python
# test_orders.py (read-only)
import pytest
from decimal import Decimal


@pytest.mark.django_db                      # gives the test database access
def test_shipping_is_free_over_threshold(settings):
    settings.FREE_SHIPPING_FROM = 50        # the `settings` fixture auto-restores
    order = make_order(total_usd=Decimal("80"))
    assert shipping_cost(order) == Decimal("0.00")


@pytest.mark.django_db
def test_my_notes_requires_login(client):   # `client` fixture = django.test.Client
    response = client.get("/my-notes/")
    assert response.status_code == 302


@pytest.mark.parametrize("text", ["", "x" * 11, "spam"])
def test_invalid_text_rejected(text):       # no database needed, so no mark
    assert not NoteForm({"text": text}).is_valid()

Useful built-in fixtures include client, admin_client, rf (a RequestFactory), settings, django_user_model, mailoutbox and django_assert_num_queries. You are free to mix styles: pytest also runs your existing TestCase classes unchanged, which makes migrating a project gradual.

Measuring coverage

Coverage tells you which lines your tests executed. It cannot prove tests are good, but a file with 0% coverage is certainly untested. The coverage package works with both runners:

TEXT
pip install coverage
coverage run manage.py test
coverage report --show-missing    # per-file percentages and missed line numbers
coverage html                     # browsable report in htmlcov/

With pytest-django use pytest --cov=myapp --cov-report=term-missing (from the pytest-cov plugin). Treat the number as a guide: review the missing lines of important modules such as permissions and payment code, set a modest threshold in CI (for example --cov-fail-under=80), and do not chase 100% by testing trivial code. Exclude migrations, settings files and if __name__ == "__main__" blocks in the coverage configuration.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of a factory function such as make_order(**overrides)?

    A factory builds a valid object with sensible defaults, so each test shows only the values that are relevant to what it checks, which keeps tests short and readable.
  2. 2. A view does from payments import charge. Where should you patch the function in a test?

    from-imports copy the reference into the importing module, so patching the original module leaves the view's reference untouched. Patch the name in the module where the code uses it.
  3. 3. What does @override_settings(FREE_SHIPPING_FROM=10) do?

    override_settings applies the new value while the test (or class, or with-block) runs and puts the original value back automatically.
  4. 4. Why does a test sometimes need to reload a user after granting a permission?

    The permission checks cache their results on the user instance. Fetching the user again from the database gives a clean object that sees the newly granted permission.
  5. 5. What does pytest.mark.django_db do in pytest-django?

    pytest-django blocks database access by default so accidental queries are noticed. The django_db mark opts a test in.

Summary

  • Build a wide base of fast unit tests, a middle layer of Client-based view tests and very few browser tests.
  • Factory functions create valid objects with defaults so tests show only what matters; factory_boy and model_bakery automate the pattern.
  • Mock the boundaries of your system (HTTP clients, gateways) with unittest.mock, and patch the name where your code looks it up.
  • override_settings and self.settings() change configuration temporarily and restore it.
  • Test forms with dictionaries, permissions for anonymous, unauthorized and authorized users, and APIs for both success and error responses.
  • TDD means red, green, refactor: write a failing API test first (the real runner shows the 404s), then the serializer, ViewSet and router, and run the suite in Docker against the same database engine as production.
  • pytest-django adds plain asserts, fixtures and parametrization; coverage shows untested code but not test quality.

Next lesson: Debugging Django Applications.