pytest-django
02 / 02

pytest-django Fundamentals: django_db, client & Fixtures

pytest-django: django_db, client & Fixtures

pytest-django lets a Django project use pytest's test discovery, fixtures, and plugin ecosystem, while still integrating properly with Django's settings, database setup, and test client.

Database Access Requires Opt-In

@pytest.mark.django_db
def test_create_user():
    user = User.objects.create(username="ada")
    assert User.objects.count() == 1

# pytest-django blocks DB access by default -- the marker
# makes a test's database dependency explicit and intentional

The client and rf Fixtures

def test_view_response(client):
    response = client.get("/users/")
    assert response.status_code == 200

def test_view_isolated(rf):
    request = rf.get("/users/")
    response = my_view(request)
    assert response.status_code == 200

# client: full request/routing/middleware stack via Django's
#         test client
# rf: RequestFactory -- builds a raw HttpRequest for testing
#     a view function more directly, without full routing

Configuring Django Settings

# pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = myproject.settings

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

Start free