Skip to content

Commit

Permalink
Add tests for admin. (#308)
Browse files Browse the repository at this point in the history
  • Loading branch information
sarahboyce authored Feb 25, 2024
1 parent 81f9a0c commit 86ecb0e
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions requirements/requirements-test.in
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ pytest-django
pytest-mock
pytest-playwright
factory_boy
unittest_parametrize
3 changes: 3 additions & 0 deletions requirements/requirements-test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -282,10 +282,13 @@ typing-extensions==4.6.3
# azure-core
# azure-storage-blob
# pyee
# unittest-parametrize
tzdata==2024.1
# via
# -r requirements/requirements.txt
# django
unittest-parametrize==1.4.0
# via -r requirements/requirements-test.in
urllib3==1.26.18
# via
# -r requirements/requirements.txt
Expand Down
62 changes: 62 additions & 0 deletions tests/test_admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from __future__ import annotations

from http import HTTPStatus

from django.contrib.admin.sites import AdminSite
from django.contrib.admin.sites import all_sites
from django.db.models import Model
from django.test import TestCase
from django.urls import reverse
from unittest_parametrize import param
from unittest_parametrize import parametrize
from unittest_parametrize import ParametrizedTestCase

from accounts.models import CustomUser


each_model_admin = parametrize(
"site,model,model_admin",
[
param(
site,
model,
model_admin,
id=f"{site.name}_{str(model_admin).replace('.', '_')}",
)
for site in all_sites
for model, model_admin in site._registry.items()
],
)


class ModelAdminTests(ParametrizedTestCase, TestCase):
user: CustomUser

@classmethod
def setUpTestData(cls):
cls.user = CustomUser.objects.create_superuser(
username="admin", email="[email protected]", password="test"
)

def setUp(self):
self.client.force_login(self.user)

def make_url(self, site: AdminSite, model: type[Model], page: str) -> str:
return reverse(
f"{site.name}:{model._meta.app_label}_{model._meta.model_name}_{page}"
)

@each_model_admin
def test_changelist(self, site, model, model_admin):
url = self.make_url(site, model, "changelist")
response = self.client.get(url, {"q": "example.com"})
assert response.status_code == HTTPStatus.OK

@each_model_admin
def test_add(self, site, model, model_admin):
url = self.make_url(site, model, "add")
response = self.client.get(url)
assert response.status_code in (
HTTPStatus.OK,
HTTPStatus.FORBIDDEN, # some admin classes blanket disallow "add"
)

0 comments on commit 86ecb0e

Please sign in to comment.