Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Writing tests for the Django admin with pytest-django#
I’m using pytest-django on a project and I wanted to write a test for a Django admin create form submission. Here’s the pattern I came up with:
1from .models import Location2import pytest3
4
5def test_admin_create_location_sets_public_id(client, admin_user):6 client.force_login(admin_user)7 assert Location.objects.count() == 08 response = client.post(9 "/admin/core/location/add/",10 {11 "name": "hello",12 "state": "13",13 "location_type": "1",14 "latitude": "0",15 "longitude": "0",16 "_save": "Save",17 },18 )19 # 200 means the form is being re-displayed with errors20 assert response.status_code == 30221 location = Location.objects.order_by("-id")[0]22 assert location.name == "hello"23 assert location.public_id == "lc"The trick here is to use the client and admin_user pytest-django fixtures (documented here) to get a configured test client and admin user object, then use client.force_login(admin_user) to obtain a session where that user is signed-in to the admin. Then write tests as normal.
Using the admin_client fixture#
Even better: use the admin_client fixture provided by pytest-django which is already signed into the admin:
1def test_admin_create_location_sets_public_id(admin_client):2 response = admin_client.post(3 "/admin/core/location/add/",4 # ...Before finding out that this was included I implemented my own version of it:
1import pytest2
3
4@pytest.fixture()5def admin_client(client, admin_user):6 client.force_login(admin_user)7 return client8
9# Then write tests like this:10def test_admin_create_location_sets_public_id(admin_client):11 response = admin_client.post(12 "/admin/core/location/add/",13 # ...