from django.contrib.auth.models import User from django.test import TestCase, modify_settings, override_settings from django.urls import reverse @override_settings( ROOT_URLCONF="admin_views.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.template.context_processors.csp", ], }, } ], ) @modify_settings( MIDDLEWARE={"append": "django.middleware.csp.ContentSecurityPolicyMiddleware"} ) class AdminCspNonceTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def setUp(self): self.client.force_login(self.superuser) @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", ], }, } ], ) def test_no_nonce_without_csp_context_processor(self): response = self.client.get(reverse("admin:index")) self.assertNotContains(response, 'nonce="') def test_index_base_scripts_have_nonce(self): response = self.client.get(reverse("admin:index")) content = response.content.decode() self.assertRegex(content, r'