Code Reference

Django pytest

Pytest · Reference cheat sheet

Django pytest

Pytest · Reference cheat sheet


📋 Overview

pytest-django replaces manage.py test with pytest fixtures: client, admin_client, db, django_user_model, and DB access markers.

🔧 Core concepts

Fixture / markRole
db / django_dbEnable DB access
clientDjango test client
admin_clientLogged-in staff
rfRequestFactory
settingsOverride settings
live_serverLive HTTP server

Configure DJANGO_SETTINGS_MODULE in pytest config or env.

💡 Examples

Install:

python -m pip install pytest-django
[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "myproject.settings"
python_files = ["tests.py", "test_*.py", "*_tests.py"]

View test:

import pytest

@pytest.mark.django_db
def test_home(client):
    res = client.get("/")
    assert res.status_code == 200

Model + user:

@pytest.mark.django_db
def test_user(django_user_model):
    u = django_user_model.objects.create_user("ada", password="x")
    assert u.username == "ada"

Settings override:

def test_debug(settings):
    settings.DEBUG = True
    assert settings.DEBUG is True

Transactional / live:

@pytest.mark.django_db(transaction=True)
def test_signal():
    ...

@pytest.mark.django_db
def test_api(live_server, client):
    assert live_server.url.startswith("http")

⚠️ Pitfalls

  • Accessing DB without django_db / db fixture → error.
  • Relying on migration state without pytest-django DB setup.
  • Using unittest TestCase transactions mixed with pytest fixtures carelessly.
  • Factory Boy / fixtures creating data without cleanup in non-db tests.
  • Pointing DJANGO_SETTINGS_MODULE at production settings.

On this page