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 / mark | Role |
|---|---|
db / django_db | Enable DB access |
client | Django test client |
admin_client | Logged-in staff |
rf | RequestFactory |
settings | Override settings |
live_server | Live 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 == 200Model + 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 TrueTransactional / 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/dbfixture → error. - Relying on migration state without
pytest-djangoDB setup. - Using unittest
TestCasetransactions mixed with pytest fixtures carelessly. - Factory Boy / fixtures creating data without cleanup in non-db tests.
- Pointing
DJANGO_SETTINGS_MODULEat production settings.