an invalid request is rejected with a localized error message response self client post self assertcontainsresponse forbidden statuscode403 self assertcontains response csrf verification failed request aborted statuscode403 with self settingslanguagecodenl overrideenus response self client post self assertcontainsresponse verboden statuscode403 self assertcontains response csrfverificatie mislukt verzoek afgebroken statuscode403 overridesettingssecureproxysslheaderhttpxforwardedproto https def testnorefererself response self client post headersxforwardedproto https self assertcontains response you are seeing this message because this https site requires a referer header to be sent by your web browser but none was sent statuscode403 self assertcontains response if you have configured your browser to disable referer headers please reenable them at least for this site or for https connections or for sameorigin requests statuscode403 self assertcontains response if you are using the lt meta namequot referrerquot contentquot noreferrerquot gt tag or including the referrerpolicy noreferrer header please remove them statuscode403 def testnocookiesself response self client post self assertcontains response you are seeing this message because this site requires a csrf cookie when submitting forms this cookie is required for security reasons to ensure that your browser is not being hijacked by third parties statuscode403 overridesettingstemplates def testnodjangotemplateengineself response self client post self assertcontainsresponse forbidden statuscode403 overridesettings templates backend django template backends django djangotemplates options loaders django template loaders locmem loader csrffailuretemplatename test template for csrf failure def testcustomtemplateself an exception is raised if a nonexistent template is supplied factory requestfactory request factory post with self assertraisestemplatedoesnotexist csrffailurerequest templatenamenonexistent html def testtemplateencodingself from django views csrf import path with mock patch objectpath open as m csrffailuremock magicmock mock mock m assertcalledoncewithencodingutf8 an invalid request is rejected with a localized error message referer header is strictly checked for post over https trigger the exception by sending an incorrect referer the csrf cookie is checked for post failure to send this cookie should provide a nice error message the csrf view doesn t depend on the templates configuration 24388 a custom csrf_failure_template_name is used an exception is raised if a nonexistent template is supplied the template is loaded directly not via a template loader and should be opened as utf 8 charset as is the default specified on template engines
from unittest import mock

from django.template import TemplateDoesNotExist
from django.test import Client, RequestFactory, SimpleTestCase, override_settings
from django.utils.translation import override
from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure


@override_settings(ROOT_URLCONF="view_tests.urls")
class CsrfViewTests(SimpleTestCase):
    def setUp(self):
        super().setUp()
        self.client = Client(enforce_csrf_checks=True)

    @override_settings(
        USE_I18N=True,
        MIDDLEWARE=[
            "django.middleware.locale.LocaleMiddleware",
            "django.middleware.common.CommonMiddleware",
            "django.middleware.csrf.CsrfViewMiddleware",
        ],
    )
    def test_translation(self):
        
        response = self.client.post("/")
        self.assertContains(response, "Forbidden", status_code=403)
        self.assertContains(
            response, "CSRF verification failed. Request aborted.", status_code=403
        )

        with self.settings(LANGUAGE_CODE="nl"), override("en-us"):
            response = self.client.post("/")
            self.assertContains(response, "Verboden", status_code=403)
            self.assertContains(
                response,
                "CSRF-verificatie mislukt. Verzoek afgebroken.",
                status_code=403,
            )

    @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https"))
    def test_no_referer(self):
        
        response = self.client.post("/", headers={"x-forwarded-proto": "https"})
        self.assertContains(
            response,
            "You are seeing this message because this HTTPS site requires a "
            "“Referer header” to be sent by your web browser, but "
            "none was sent.",
            status_code=403,
        )
        self.assertContains(
            response,
            "If you have configured your browser to disable “Referer” "
            "headers, please re-enable them, at least for this site, or for "
            "HTTPS connections, or for “same-origin” requests.",
            status_code=403,
        )
        self.assertContains(
            response,
            "If you are using the &lt;meta name=&quot;referrer&quot; "
            "content=&quot;no-referrer&quot;&gt; tag or including the "
            "“Referrer-Policy: no-referrer” header, please remove them.",
            status_code=403,
        )

    def test_no_cookies(self):
        
        response = self.client.post("/")
        self.assertContains(
            response,
            "You are seeing this message because this site requires a CSRF "
            "cookie when submitting forms. This cookie is required for "
            "security reasons, to ensure that your browser is not being "
            "hijacked by third parties.",
            status_code=403,
        )

    @override_settings(TEMPLATES=[])
    def test_no_django_template_engine(self):
        
        response = self.client.post("/")
        self.assertContains(response, "Forbidden", status_code=403)

    @override_settings(
        TEMPLATES=[
            {
                "BACKEND": "django.template.backends.django.DjangoTemplates",
                "OPTIONS": {
                    "loaders": [
                        (
                            "django.template.loaders.locmem.Loader",
                            {
                                CSRF_FAILURE_TEMPLATE_NAME: (
                                    "Test template for CSRF failure"
                                )
                            },
                        ),
                    ],
                },
            }
        ]
    )
    def test_custom_template(self):
        
        response = self.client.post("/")
        self.assertContains(response, "Test template for CSRF failure", status_code=403)

    def test_custom_template_does_not_exist(self):
        
        factory = RequestFactory()
        request = factory.post("/")
        with self.assertRaises(TemplateDoesNotExist):
            csrf_failure(request, template_name="nonexistent.html")

    def test_template_encoding(self):
        
        from django.views.csrf import Path

        with mock.patch.object(Path, "open") as m:
            csrf_failure(mock.MagicMock(), mock.Mock())
            m.assert_called_once_with(encoding="utf-8")