authentik/passbook/admin/tests.py

65 lines
1.7 KiB
Python
Raw Normal View History

2020-05-19 19:59:43 +01:00
"""admin tests"""
2020-07-02 21:29:30 +01:00
from importlib import import_module
2020-05-19 19:59:43 +01:00
from typing import Callable
2020-07-02 21:29:30 +01:00
from django.forms import ModelForm
2020-05-19 19:59:43 +01:00
from django.shortcuts import reverse
from django.test import Client, TestCase
from django.urls.exceptions import NoReverseMatch
from passbook.admin.urls import urlpatterns
from passbook.core.models import User
2020-07-02 21:29:30 +01:00
from passbook.lib.utils.reflection import get_apps
2020-05-19 19:59:43 +01:00
class TestAdmin(TestCase):
"""Generic admin tests"""
def setUp(self):
self.user = User.objects.create_superuser(username="test")
self.client = Client()
self.client.force_login(self.user)
def generic_view_tester(view_name: str) -> Callable:
"""This is used instead of subTest for better visibility"""
def tester(self: TestAdmin):
try:
full_url = reverse(f"passbook_admin:{view_name}")
response = self.client.get(full_url)
self.assertTrue(response.status_code < 500)
except NoReverseMatch:
pass
return tester
for url in urlpatterns:
method_name = url.name.replace("-", "_")
2020-07-02 21:29:30 +01:00
setattr(TestAdmin, f"test_view_{method_name}", generic_view_tester(url.name))
def generic_form_tester(form: ModelForm) -> Callable:
"""Test a form"""
def tester(self: TestAdmin):
form_inst = form()
self.assertFalse(form_inst.is_valid())
return tester
# Load the forms module from every app, so we have all forms loaded
for app in get_apps():
module = app.__module__.replace(".apps", ".forms")
try:
import_module(module)
except ImportError:
pass
for form_class in ModelForm.__subclasses__():
setattr(
TestAdmin, f"test_form_{form_class.__name__}", generic_form_tester(form_class)
)