warn if sessioncookiesecure is off and django contrib sessions is in installedapps sessioncookiesecure must be boolean self assertequalsessions checksessioncookiesecurenone sessions w010 overridesettings sessioncookiesecurefalse installedapps middlewaredjango contrib sessions middleware sessionmiddleware def testsessioncookiesecurewithmiddlewareself self assertequalsessions checksessioncookiesecurenone sessions w011 overridesettings sessioncookiesecurefalse installedappsdjango contrib sessions middlewaredjango contrib sessions middleware sessionmiddleware def testsessioncookiesecurebothself self assertequalsessions checksessioncookiesecurenone sessions w012 overridesettings sessioncookiesecuretrue installedappsdjango contrib sessions middlewaredjango contrib sessions middleware sessionmiddleware def testsessioncookiesecuretrueself self assertequalsessions checksessioncookiesecurenone class checksessioncookiehttponlytestsimpletestcase overridesettings sessioncookiehttponlyfalse installedappsdjango contrib sessions middleware def testsessioncookiehttponlywithinstalledappself self assertequalsessions checksessioncookiehttponlynone sessions w013 overridesettings sessioncookiehttponly1 installedappsdjango contrib sessions middleware def testsessioncookiehttponlywithinstalledapptruthyself warn if sessioncookiehttponly is off and django contrib sessions middleware sessionmiddleware is in middleware if sessioncookiehttponly is off and we find both the session app and the middleware provide one common warning if sessioncookiehttponly is on there s no warning about it warn if csrfviewmiddleware isn t in middleware warn if csrfviewmiddleware is in middleware but csrfcookiesecure isn t true csrfcookiesecure must be boolean self assertequalcsrf checkcsrfcookiesecurenone csrf w016 overridesettings middlewaredjango middleware csrf csrfviewmiddleware csrfusesessionstrue csrfcookiesecurefalse def testusesessionswithcsrfcookiesecurefalseself self assertequalcsrf checkcsrfcookiesecurenone overridesettingsmiddleware csrfcookiesecurefalse def testwithcsrfcookiesecurefalsenomiddlewareself self assertequalcsrf checkcsrfcookiesecurenone overridesettings middlewaredjango middleware csrf csrfviewmiddleware csrfcookiesecuretrue def testwithcsrfcookiesecuretrueself self assertequalcsrf checkcsrfcookiesecurenone class checksecuritymiddlewaretestsimpletestcase overridesettingsmiddleware def testnosecuritymiddlewareself self assertequalbase checksecuritymiddlewarenone base w001 overridesettingsmiddlewaredjango middleware security securitymiddleware def testwithsecuritymiddlewareself self assertequalbase checksecuritymiddlewarenone class checkstricttransportsecuritytestsimpletestcase overridesettings middlewaredjango middleware security securitymiddleware securehstsseconds0 def testnostsself self assertequalbase checkstsnone base w004 overridesettingsmiddleware securehstsseconds0 def testnostsnomiddlewareself self assertequalbase checkstsnone overridesettings middlewaredjango middleware security securitymiddleware securehstsseconds3600 def testwithstsself self assertequalbase checkstsnone class checkstricttransportsecuritysubdomainstestsimpletestcase overridesettings middlewaredjango middleware security securitymiddleware securehstsincludesubdomainsfalse securehstsseconds3600 def testnostssubdomainsself self assertequalbase checkstsincludesubdomainsnone base w005 overridesettings middleware securehstsincludesubdomainsfalse securehstsseconds3600 def testnostssubdomainsnomiddlewareself self assertequalbase checkstsincludesubdomainsnone overridesettings middlewaredjango middleware security securitymiddleware securesslredirectfalse securehstssecondsnone def testnostssubdomainsnosecondsself self assertequalbase checkstsincludesubdomainsnone overridesettings middlewaredjango middleware security securitymiddleware securehstsincludesubdomainstrue securehstsseconds3600 def testwithstssubdomainsself self assertequalbase checkstsincludesubdomainsnone class checkstricttransportsecuritypreloadtestsimpletestcase overridesettings middlewaredjango middleware security securitymiddleware securehstspreloadfalse securehstsseconds3600 def testnostspreloadself self assertequalbase checkstspreloadnone base w021 overridesettings middleware securehstspreloadfalse securehstsseconds3600 def testnostspreloadnomiddlewareself self assertequalbase checkstspreloadnone overridesettings middlewaredjango middleware security securitymiddleware securesslredirectfalse securehstssecondsnone def testnostspreloadnosecondsself self assertequalbase checkstspreloadnone overridesettings middlewaredjango middleware security securitymiddleware securehstspreloadtrue securehstsseconds3600 def testwithstspreloadself self assertequalbase checkstspreloadnone class checkxframeoptionsmiddlewaretestsimpletestcase overridesettingsmiddleware def testmiddlewarenotinstalledself self assertequalbase checkxframeoptionsmiddlewarenone base w002 overridesettings middlewaredjango middleware clickjacking xframeoptionsmiddleware def testmiddlewareinstalledself self assertequalbase checkxframeoptionsmiddlewarenone class checkxframeoptionsdenytestsimpletestcase overridesettings middlewaredjango middleware clickjacking xframeoptionsmiddleware xframeoptionssameorigin def testxframeoptionsnotdenyself self assertequalbase checkxframedenynone base w019 overridesettingsmiddleware xframeoptionssameorigin def testmiddlewarenotinstalledself self assertequalbase checkxframedenynone overridesettings middlewaredjango middleware clickjacking xframeoptionsmiddleware xframeoptionsdeny def testxframedenyself self assertequalbase checkxframedenynone class checkcontenttypenosnifftestsimpletestcase overridesettings middlewaredjango middleware security securitymiddleware securecontenttypenosnifffalse def testnocontenttypenosniffself self assertequalbase checkcontenttypenosniffnone base w006 overridesettingsmiddleware securecontenttypenosnifffalse def testnocontenttypenosniffnomiddlewareself self assertequalbase checkcontenttypenosniffnone overridesettings middlewaredjango middleware security securitymiddleware securecontenttypenosnifftrue def testwithcontenttypenosniffself self assertequalbase checkcontenttypenosniffnone class checksslredirecttestsimpletestcase overridesettings middlewaredjango middleware security securitymiddleware securesslredirectfalse def testnosslredirectself self assertequalbase checksslredirectnone base w008 overridesettingsmiddleware securesslredirectfalse def testnosslredirectnomiddlewareself self assertequalbase checksslredirectnone overridesettings middlewaredjango middleware security securitymiddleware securesslredirecttrue def testwithsslredirectself self assertequalbase checksslredirectnone class checksecretkeytestsimpletestcase overridesettingssecretkeyabcdefghijklmnopqrstuvwx 2 ab def testokaysecretkeyself self assertequallensettings secretkey base secretkeyminlength self assertgreater lensetsettings secretkey base secretkeyminuniquecharacters self assertequalbase checksecretkeynone overridesettingssecretkey def testemptysecretkeyself self assertequalbase checksecretkeynone base w009 overridesettingssecretkeynone def testmissingsecretkeyself del settings secretkey self assertequalbase checksecretkeynone base w009 overridesettingssecretkeynone def testnonesecretkeyself self assertequalbase checksecretkeynone base w009 overridesettings secretkeybase secretkeyinsecureprefix getrandomsecretkey def testinsecuresecretkeyself self assertequalbase checksecretkeynone base w009 overridesettingssecretkeyabcdefghijklmnopqrstuvwx 2 a def testlowlengthsecretkeyself self assertequallensettings secretkey base secretkeyminlength 1 self assertequalbase checksecretkeynone base w009 overridesettingssecretkeyabcd 20 def testlowentropysecretkeyself self assertgreaterlensettings secretkey base secretkeyminlength self assertless lensetsettings secretkey base secretkeyminuniquecharacters self assertequalbase checksecretkeynone base w009 class checksecretkeyfallbackstestsimpletestcase overridesettingssecretkeyfallbacksabcdefghijklmnopqrstuvwx 2 ab def testokaysecretkeyfallbacksself self assertequal lensettings secretkeyfallbacks0 base secretkeyminlength self assertgreater lensetsettings secretkeyfallbacks0 base secretkeyminuniquecharacters self assertequalbase checksecretkeyfallbacksnone def testnosecretkeyfallbacksself with self settingssecretkeyfallbacksnone del settings secretkeyfallbacks self assertequal base checksecretkeyfallbacksnone warningbase w025 msg secretkeyfallbacks idbase w025 id overridesettings secretkeyfallbacksbase secretkeyinsecureprefix getrandomsecretkey def testinsecuresecretkeyfallbacksself self assertequal base checksecretkeyfallbacksnone warningbase w025 msg secretkeyfallbacks0 idbase w025 id overridesettingssecretkeyfallbacksabcdefghijklmnopqrstuvwx 2 a def testlowlengthsecretkeyfallbacksself self assertequal lensettings secretkeyfallbacks0 base secretkeyminlength 1 self assertequal base checksecretkeyfallbacksnone warningbase w025 msg secretkeyfallbacks0 idbase w025 id overridesettingssecretkeyfallbacksabcd 20 def testlowentropysecretkeyfallbacksself self assertgreater lensettings secretkeyfallbacks0 base secretkeyminlength self assertless lensetsettings secretkeyfallbacks0 base secretkeyminuniquecharacters self assertequal base checksecretkeyfallbacksnone warningbase w025 msg secretkeyfallbacks0 idbase w025 id overridesettings secretkeyfallbacks abcdefghijklmnopqrstuvwx 2 ab badkey def testmultiplekeysself self assertequal base checksecretkeyfallbacksnone warningbase w025 msg secretkeyfallbacks1 idbase w025 id overridesettings secretkeyfallbacks abcdefghijklmnopqrstuvwx 2 ab badkey1 badkey2 def testmultiplebadkeysself self assertequal base checksecretkeyfallbacksnone warningbase w025 msg secretkeyfallbacks1 idbase w025 id warningbase w025 msg secretkeyfallbacks2 idbase w025 id class checkdebugtestsimpletestcase overridesettingsdebugtrue def testdebugtrueself self assertequalbase checkdebugnone base w018 overridesettingsdebugfalse def testdebugfalseself self assertequalbase checkdebugnone class checkallowedhoststestsimpletestcase overridesettingsallowedhosts def testallowedhostsemptyself self assertequalbase checkallowedhostsnone base w020 overridesettingsallowedhosts example com def testallowedhostssetself self assertequalbase checkallowedhostsnone class checkreferrerpolicytestsimpletestcase overridesettings middlewaredjango middleware security securitymiddleware securereferrerpolicynone def testnoreferrerpolicyself self assertequalbase checkreferrerpolicynone base w022 overridesettingsmiddleware securereferrerpolicynone def testnoreferrerpolicynomiddlewareself self assertequalbase checkreferrerpolicynone overridesettingsmiddlewaredjango middleware security securitymiddleware def testwithreferrerpolicyself tests strictorigin strictorigin origin strictorigin origin strictorigin origin strictorigin origin for value in tests with self subtestvaluevalue overridesettings securereferrerpolicyvalue self assertequalbase checkreferrerpolicynone overridesettings middlewaredjango middleware security securitymiddleware securereferrerpolicyinvalidvalue def testwithinvalidreferrerpolicyself self assertequalbase checkreferrerpolicynone base e023 def failureviewwithinvalidsignature pass goodclassbasedcsrffailureview view asview class csrffailureviewtestsimpletestcase overridesettingscsrffailureview def testfailureviewimporterrorself self assertequal csrf checkcsrffailureviewnone error the csrf failure view could not be imported idsecurity e102 overridesettings csrffailureview checkframework testsecurity failureviewwithinvalidsignature def testfailureviewinvalidsignatureself msg the csrf failure view checkframework testsecurity failureviewwithinvalidsignature does not take the correct number of arguments self assertequal csrf checkcsrffailureviewnone errormsg idsecurity e101 overridesettings csrffailureview checkframework testsecurity goodclassbasedcsrffailureview def testfailureviewvalidclassbasedself self assertequalcsrf checkcsrffailureviewnone class checkcrossoriginopenerpolicytestsimpletestcase overridesettings middlewaredjango middleware security securitymiddleware securecrossoriginopenerpolicynone def testnocoopself self assertequalbase checkcrossoriginopenerpolicynone overridesettingsmiddlewaredjango middleware security securitymiddleware def testwithcoopself tests sameorigin sameoriginallowpopups unsafenone for value in tests with self subtestvaluevalue overridesettings securecrossoriginopenerpolicyvalue self assertequalbase checkcrossoriginopenerpolicynone overridesettings middlewaredjango middleware security securitymiddleware securecrossoriginopenerpolicyinvalidvalue def testwithinvalidcoopself self assertequalbase checkcrossoriginopenerpolicynone base e024 warn if session_cookie_secure is off and django contrib sessions is in installed_apps session_cookie_secure must be boolean warn if session_cookie_secure is off and django contrib sessions middleware sessionmiddleware is in middleware if session_cookie_secure is off and we find both the session app and the middleware provide one common warning if session_cookie_secure is on there s no warning about it warn if session_cookie_httponly is off and django contrib sessions is in installed_apps session_cookie_httponly must be boolean warn if session_cookie_httponly is off and django contrib sessions middleware sessionmiddleware is in middleware if session_cookie_httponly is off and we find both the session app and the middleware provide one common warning if session_cookie_httponly is on there s no warning about it warn if csrfviewmiddleware isn t in middleware warn if csrfviewmiddleware is in middleware but csrf_cookie_secure isn t true csrf_cookie_secure must be boolean no warning if csrf_cookie_secure isn t true while csrf_use_sessions is true no warning if csrfviewmiddleware isn t in middleware even if csrf_cookie_secure is false warn if securitymiddleware isn t in middleware warn if secure_hsts_seconds isn t 0 don t warn if secure_hsts_seconds isn t 0 and securitymiddleware isn t installed warn if secure_hsts_include_subdomains isn t true don t warn if securitymiddleware isn t installed don t warn if secure_hsts_seconds isn t set warn if secure_hsts_preload isn t true don t warn if securitymiddleware isn t installed don t warn if secure_hsts_seconds isn t set warn if xframeoptionsmiddleware isn t in middleware warn if xframeoptionsmiddleware is in middleware but x_frame_options isn t deny no error if xframeoptionsmiddleware isn t in middleware even if x_frame_options isn t deny warn if secure_content_type_nosniff isn t true don t warn if secure_content_type_nosniff isn t true and securitymiddleware isn t in middleware warn if secure_ssl_redirect isn t true don t warn if secure_ssl_redirect is false and securitymiddleware isn t installed warn if debug is true don t warn if secure_referrer_policy is none and securitymiddleware isn t in middleware
from django.conf import settings
from django.core.checks.messages import Error, Warning
from django.core.checks.security import base, csrf, sessions
from django.core.management.utils import get_random_secret_key
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.views.generic import View


class CheckSessionCookieSecureTest(SimpleTestCase):
    @override_settings(
        SESSION_COOKIE_SECURE=False,
        INSTALLED_APPS=["django.contrib.sessions"],
        MIDDLEWARE=[],
    )
    def test_session_cookie_secure_with_installed_app(self):
        
        self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010])

    @override_settings(
        SESSION_COOKIE_SECURE="1",
        INSTALLED_APPS=["django.contrib.sessions"],
        MIDDLEWARE=[],
    )
    def test_session_cookie_secure_with_installed_app_truthy(self):
        
        self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010])

    @override_settings(
        SESSION_COOKIE_SECURE=False,
        INSTALLED_APPS=[],
        MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
    )
    def test_session_cookie_secure_with_middleware(self):
        
        self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W011])

    @override_settings(
        SESSION_COOKIE_SECURE=False,
        INSTALLED_APPS=["django.contrib.sessions"],
        MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
    )
    def test_session_cookie_secure_both(self):
        
        self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W012])

    @override_settings(
        SESSION_COOKIE_SECURE=True,
        INSTALLED_APPS=["django.contrib.sessions"],
        MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
    )
    def test_session_cookie_secure_true(self):
        
        self.assertEqual(sessions.check_session_cookie_secure(None), [])


class CheckSessionCookieHttpOnlyTest(SimpleTestCase):
    @override_settings(
        SESSION_COOKIE_HTTPONLY=False,
        INSTALLED_APPS=["django.contrib.sessions"],
        MIDDLEWARE=[],
    )
    def test_session_cookie_httponly_with_installed_app(self):
        
        self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W013])

    @override_settings(
        SESSION_COOKIE_HTTPONLY="1",
        INSTALLED_APPS=["django.contrib.sessions"],
        MIDDLEWARE=[],
    )
    def test_session_cookie_httponly_with_installed_app_truthy(self):
        
        self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W013])

    @override_settings(
        SESSION_COOKIE_HTTPONLY=False,
        INSTALLED_APPS=[],
        MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
    )
    def test_session_cookie_httponly_with_middleware(self):
        
        self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W014])

    @override_settings(
        SESSION_COOKIE_HTTPONLY=False,
        INSTALLED_APPS=["django.contrib.sessions"],
        MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
    )
    def test_session_cookie_httponly_both(self):
        
        self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W015])

    @override_settings(
        SESSION_COOKIE_HTTPONLY=True,
        INSTALLED_APPS=["django.contrib.sessions"],
        MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"],
    )
    def test_session_cookie_httponly_true(self):
        
        self.assertEqual(sessions.check_session_cookie_httponly(None), [])


class CheckCSRFMiddlewareTest(SimpleTestCase):
    @override_settings(MIDDLEWARE=[])
    def test_no_csrf_middleware(self):
        
        self.assertEqual(csrf.check_csrf_middleware(None), [csrf.W003])

    @override_settings(MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"])
    def test_with_csrf_middleware(self):
        self.assertEqual(csrf.check_csrf_middleware(None), [])


class CheckCSRFCookieSecureTest(SimpleTestCase):
    @override_settings(
        MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"],
        CSRF_COOKIE_SECURE=False,
    )
    def test_with_csrf_cookie_secure_false(self):
        
        self.assertEqual(csrf.check_csrf_cookie_secure(None), [csrf.W016])

    @override_settings(
        MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"],
        CSRF_COOKIE_SECURE="1",
    )
    def test_with_csrf_cookie_secure_truthy(self):
        
        self.assertEqual(csrf.check_csrf_cookie_secure(None), [csrf.W016])

    @override_settings(
        MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"],
        CSRF_USE_SESSIONS=True,
        CSRF_COOKIE_SECURE=False,
    )
    def test_use_sessions_with_csrf_cookie_secure_false(self):
        
        self.assertEqual(csrf.check_csrf_cookie_secure(None), [])

    @override_settings(MIDDLEWARE=[], CSRF_COOKIE_SECURE=False)
    def test_with_csrf_cookie_secure_false_no_middleware(self):
        
        self.assertEqual(csrf.check_csrf_cookie_secure(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"],
        CSRF_COOKIE_SECURE=True,
    )
    def test_with_csrf_cookie_secure_true(self):
        self.assertEqual(csrf.check_csrf_cookie_secure(None), [])


class CheckSecurityMiddlewareTest(SimpleTestCase):
    @override_settings(MIDDLEWARE=[])
    def test_no_security_middleware(self):
        
        self.assertEqual(base.check_security_middleware(None), [base.W001])

    @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"])
    def test_with_security_middleware(self):
        self.assertEqual(base.check_security_middleware(None), [])


class CheckStrictTransportSecurityTest(SimpleTestCase):
    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_HSTS_SECONDS=0,
    )
    def test_no_sts(self):
        
        self.assertEqual(base.check_sts(None), [base.W004])

    @override_settings(MIDDLEWARE=[], SECURE_HSTS_SECONDS=0)
    def test_no_sts_no_middleware(self):
        
        self.assertEqual(base.check_sts(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_HSTS_SECONDS=3600,
    )
    def test_with_sts(self):
        self.assertEqual(base.check_sts(None), [])


class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase):
    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_HSTS_INCLUDE_SUBDOMAINS=False,
        SECURE_HSTS_SECONDS=3600,
    )
    def test_no_sts_subdomains(self):
        
        self.assertEqual(base.check_sts_include_subdomains(None), [base.W005])

    @override_settings(
        MIDDLEWARE=[],
        SECURE_HSTS_INCLUDE_SUBDOMAINS=False,
        SECURE_HSTS_SECONDS=3600,
    )
    def test_no_sts_subdomains_no_middleware(self):
        
        self.assertEqual(base.check_sts_include_subdomains(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_SSL_REDIRECT=False,
        SECURE_HSTS_SECONDS=None,
    )
    def test_no_sts_subdomains_no_seconds(self):
        
        self.assertEqual(base.check_sts_include_subdomains(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_HSTS_INCLUDE_SUBDOMAINS=True,
        SECURE_HSTS_SECONDS=3600,
    )
    def test_with_sts_subdomains(self):
        self.assertEqual(base.check_sts_include_subdomains(None), [])


class CheckStrictTransportSecurityPreloadTest(SimpleTestCase):
    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_HSTS_PRELOAD=False,
        SECURE_HSTS_SECONDS=3600,
    )
    def test_no_sts_preload(self):
        
        self.assertEqual(base.check_sts_preload(None), [base.W021])

    @override_settings(
        MIDDLEWARE=[], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600
    )
    def test_no_sts_preload_no_middleware(self):
        
        self.assertEqual(base.check_sts_preload(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_SSL_REDIRECT=False,
        SECURE_HSTS_SECONDS=None,
    )
    def test_no_sts_preload_no_seconds(self):
        
        self.assertEqual(base.check_sts_preload(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_HSTS_PRELOAD=True,
        SECURE_HSTS_SECONDS=3600,
    )
    def test_with_sts_preload(self):
        self.assertEqual(base.check_sts_preload(None), [])


class CheckXFrameOptionsMiddlewareTest(SimpleTestCase):
    @override_settings(MIDDLEWARE=[])
    def test_middleware_not_installed(self):
        
        self.assertEqual(base.check_xframe_options_middleware(None), [base.W002])

    @override_settings(
        MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"]
    )
    def test_middleware_installed(self):
        self.assertEqual(base.check_xframe_options_middleware(None), [])


class CheckXFrameOptionsDenyTest(SimpleTestCase):
    @override_settings(
        MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"],
        X_FRAME_OPTIONS="SAMEORIGIN",
    )
    def test_x_frame_options_not_deny(self):
        
        self.assertEqual(base.check_xframe_deny(None), [base.W019])

    @override_settings(MIDDLEWARE=[], X_FRAME_OPTIONS="SAMEORIGIN")
    def test_middleware_not_installed(self):
        
        self.assertEqual(base.check_xframe_deny(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"],
        X_FRAME_OPTIONS="DENY",
    )
    def test_xframe_deny(self):
        self.assertEqual(base.check_xframe_deny(None), [])


class CheckContentTypeNosniffTest(SimpleTestCase):
    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_CONTENT_TYPE_NOSNIFF=False,
    )
    def test_no_content_type_nosniff(self):
        
        self.assertEqual(base.check_content_type_nosniff(None), [base.W006])

    @override_settings(MIDDLEWARE=[], SECURE_CONTENT_TYPE_NOSNIFF=False)
    def test_no_content_type_nosniff_no_middleware(self):
        
        self.assertEqual(base.check_content_type_nosniff(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_CONTENT_TYPE_NOSNIFF=True,
    )
    def test_with_content_type_nosniff(self):
        self.assertEqual(base.check_content_type_nosniff(None), [])


class CheckSSLRedirectTest(SimpleTestCase):
    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_SSL_REDIRECT=False,
    )
    def test_no_ssl_redirect(self):
        
        self.assertEqual(base.check_ssl_redirect(None), [base.W008])

    @override_settings(MIDDLEWARE=[], SECURE_SSL_REDIRECT=False)
    def test_no_ssl_redirect_no_middleware(self):
        
        self.assertEqual(base.check_ssl_redirect(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_SSL_REDIRECT=True,
    )
    def test_with_ssl_redirect(self):
        self.assertEqual(base.check_ssl_redirect(None), [])


class CheckSecretKeyTest(SimpleTestCase):
    @override_settings(SECRET_KEY=("abcdefghijklmnopqrstuvwx" * 2) + "ab")
    def test_okay_secret_key(self):
        self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH)
        self.assertGreater(
            len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS
        )
        self.assertEqual(base.check_secret_key(None), [])

    @override_settings(SECRET_KEY="")
    def test_empty_secret_key(self):
        self.assertEqual(base.check_secret_key(None), [base.W009])

    @override_settings(SECRET_KEY=None)
    def test_missing_secret_key(self):
        del settings.SECRET_KEY
        self.assertEqual(base.check_secret_key(None), [base.W009])

    @override_settings(SECRET_KEY=None)
    def test_none_secret_key(self):
        self.assertEqual(base.check_secret_key(None), [base.W009])

    @override_settings(
        SECRET_KEY=base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key()
    )
    def test_insecure_secret_key(self):
        self.assertEqual(base.check_secret_key(None), [base.W009])

    @override_settings(SECRET_KEY=("abcdefghijklmnopqrstuvwx" * 2) + "a")
    def test_low_length_secret_key(self):
        self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH - 1)
        self.assertEqual(base.check_secret_key(None), [base.W009])

    @override_settings(SECRET_KEY="abcd" * 20)
    def test_low_entropy_secret_key(self):
        self.assertGreater(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH)
        self.assertLess(
            len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS
        )
        self.assertEqual(base.check_secret_key(None), [base.W009])


class CheckSecretKeyFallbacksTest(SimpleTestCase):
    @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "ab"])
    def test_okay_secret_key_fallbacks(self):
        self.assertEqual(
            len(settings.SECRET_KEY_FALLBACKS[0]),
            base.SECRET_KEY_MIN_LENGTH,
        )
        self.assertGreater(
            len(set(settings.SECRET_KEY_FALLBACKS[0])),
            base.SECRET_KEY_MIN_UNIQUE_CHARACTERS,
        )
        self.assertEqual(base.check_secret_key_fallbacks(None), [])

    def test_no_secret_key_fallbacks(self):
        with self.settings(SECRET_KEY_FALLBACKS=None):
            del settings.SECRET_KEY_FALLBACKS
            self.assertEqual(
                base.check_secret_key_fallbacks(None),
                [
                    Warning(base.W025.msg % "SECRET_KEY_FALLBACKS", id=base.W025.id),
                ],
            )

    @override_settings(
        SECRET_KEY_FALLBACKS=[base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key()]
    )
    def test_insecure_secret_key_fallbacks(self):
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id),
            ],
        )

    @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "a"])
    def test_low_length_secret_key_fallbacks(self):
        self.assertEqual(
            len(settings.SECRET_KEY_FALLBACKS[0]),
            base.SECRET_KEY_MIN_LENGTH - 1,
        )
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id),
            ],
        )

    @override_settings(SECRET_KEY_FALLBACKS=["abcd" * 20])
    def test_low_entropy_secret_key_fallbacks(self):
        self.assertGreater(
            len(settings.SECRET_KEY_FALLBACKS[0]),
            base.SECRET_KEY_MIN_LENGTH,
        )
        self.assertLess(
            len(set(settings.SECRET_KEY_FALLBACKS[0])),
            base.SECRET_KEY_MIN_UNIQUE_CHARACTERS,
        )
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id),
            ],
        )

    @override_settings(
        SECRET_KEY_FALLBACKS=[
            ("abcdefghijklmnopqrstuvwx" * 2) + "ab",
            "badkey",
        ]
    )
    def test_multiple_keys(self):
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id),
            ],
        )

    @override_settings(
        SECRET_KEY_FALLBACKS=[
            ("abcdefghijklmnopqrstuvwx" * 2) + "ab",
            "badkey1",
            "badkey2",
        ]
    )
    def test_multiple_bad_keys(self):
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id),
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[2]", id=base.W025.id),
            ],
        )


class CheckDebugTest(SimpleTestCase):
    @override_settings(DEBUG=True)
    def test_debug_true(self):
        
        self.assertEqual(base.check_debug(None), [base.W018])

    @override_settings(DEBUG=False)
    def test_debug_false(self):
        self.assertEqual(base.check_debug(None), [])


class CheckAllowedHostsTest(SimpleTestCase):
    @override_settings(ALLOWED_HOSTS=[])
    def test_allowed_hosts_empty(self):
        self.assertEqual(base.check_allowed_hosts(None), [base.W020])

    @override_settings(ALLOWED_HOSTS=[".example.com"])
    def test_allowed_hosts_set(self):
        self.assertEqual(base.check_allowed_hosts(None), [])


class CheckReferrerPolicyTest(SimpleTestCase):
    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_REFERRER_POLICY=None,
    )
    def test_no_referrer_policy(self):
        self.assertEqual(base.check_referrer_policy(None), [base.W022])

    @override_settings(MIDDLEWARE=[], SECURE_REFERRER_POLICY=None)
    def test_no_referrer_policy_no_middleware(self):
        
        self.assertEqual(base.check_referrer_policy(None), [])

    @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"])
    def test_with_referrer_policy(self):
        tests = (
            "strict-origin",
            "strict-origin,origin",
            "strict-origin, origin",
            ["strict-origin", "origin"],
            ("strict-origin", "origin"),
        )
        for value in tests:
            with self.subTest(value=value), override_settings(
                SECURE_REFERRER_POLICY=value
            ):
                self.assertEqual(base.check_referrer_policy(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_REFERRER_POLICY="invalid-value",
    )
    def test_with_invalid_referrer_policy(self):
        self.assertEqual(base.check_referrer_policy(None), [base.E023])


def failure_view_with_invalid_signature():
    pass


good_class_based_csrf_failure_view = View.as_view()


class CSRFFailureViewTest(SimpleTestCase):
    @override_settings(CSRF_FAILURE_VIEW="")
    def test_failure_view_import_error(self):
        self.assertEqual(
            csrf.check_csrf_failure_view(None),
            [
                Error(
                    "The CSRF failure view '' could not be imported.",
                    id="security.E102",
                )
            ],
        )

    @override_settings(
        CSRF_FAILURE_VIEW=(
            "check_framework.test_security.failure_view_with_invalid_signature"
        ),
    )
    def test_failure_view_invalid_signature(self):
        msg = (
            "The CSRF failure view "
            "'check_framework.test_security.failure_view_with_invalid_signature' "
            "does not take the correct number of arguments."
        )
        self.assertEqual(
            csrf.check_csrf_failure_view(None),
            [Error(msg, id="security.E101")],
        )

    @override_settings(
        CSRF_FAILURE_VIEW=(
            "check_framework.test_security.good_class_based_csrf_failure_view"
        ),
    )
    def test_failure_view_valid_class_based(self):
        self.assertEqual(csrf.check_csrf_failure_view(None), [])


class CheckCrossOriginOpenerPolicyTest(SimpleTestCase):
    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_CROSS_ORIGIN_OPENER_POLICY=None,
    )
    def test_no_coop(self):
        self.assertEqual(base.check_cross_origin_opener_policy(None), [])

    @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"])
    def test_with_coop(self):
        tests = ["same-origin", "same-origin-allow-popups", "unsafe-none"]
        for value in tests:
            with self.subTest(value=value), override_settings(
                SECURE_CROSS_ORIGIN_OPENER_POLICY=value,
            ):
                self.assertEqual(base.check_cross_origin_opener_policy(None), [])

    @override_settings(
        MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
        SECURE_CROSS_ORIGIN_OPENER_POLICY="invalid-value",
    )
    def test_with_invalid_coop(self):
        self.assertEqual(base.check_cross_origin_opener_policy(None), [base.E024])