Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Aug 1, 2024
1 parent d077bf4 commit c3dc4bb
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 45 deletions.
6 changes: 2 additions & 4 deletions debug_toolbar/toolbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@
from django.urls import include, path, re_path, resolve
from django.urls.exceptions import Resolver404
from django.utils.module_loading import import_string
from django.utils.translation import get_language
from django.utils.translation import override as lang_override
from django.utils.translation import get_language, override as lang_override

from debug_toolbar import APP_NAME
from debug_toolbar import settings as dt_settings
from debug_toolbar import APP_NAME, settings as dt_settings
from debug_toolbar.panels import Panel


Expand Down
3 changes: 1 addition & 2 deletions tests/panels/test_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,7 @@ def test_custom_context_processor(self):
)

def test_disabled(self):
config = {"DISABLE_PANELS": {
"debug_toolbar.panels.templates.TemplatesPanel"}}
config = {"DISABLE_PANELS": {"debug_toolbar.panels.templates.TemplatesPanel"}}
self.assertTrue(self.panel.enabled)
with self.settings(DEBUG_TOOLBAR_CONFIG=config):
self.assertFalse(self.panel.enabled)
Expand Down
74 changes: 35 additions & 39 deletions tests/test_csp_rendering.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,89 +15,85 @@ def _get_ns(element: Element) -> Dict[str, str]:
Return the default `xmlns`. See
https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces
"""
if not element.tag.startswith('{'):
if not element.tag.startswith("{"):
return {}
return {'': element.tag[1:].split('}', maxsplit=1)[0]}
return {"": element.tag[1:].split("}", maxsplit=1)[0]}


class CspRenderingTestCase(BaseTestCase):
'Testing if `csp-nonce` renders.'
"Testing if `csp-nonce` renders."

panel_id = "StaticFilesPanel"

# def setUp(self):
# self.factory = RequestFactory()
# self.async_factory = AsyncRequestFactory()

def _fail_if_missing(
self, root: Element, path: str, namespaces: Dict[str, str],
nonce: str):
self, root: Element, path: str, namespaces: Dict[str, str], nonce: str
):
"""
Search elements, fail if a `nonce` attribute is missing on them.
"""
elements = root.findall(path=path, namespaces=namespaces)
for item in elements:
if item.attrib.get('nonce') != nonce:
raise self.failureException(f'{item} has no nonce attribute.')
if item.attrib.get("nonce") != nonce:
raise self.failureException(f"{item} has no nonce attribute.")

def _fail_if_found(
self, root: Element, path: str, namespaces: Dict[str, str]):
def _fail_if_found(self, root: Element, path: str, namespaces: Dict[str, str]):
"""
Search elements, fail if a `nonce` attribute is found on them.
"""
elements = root.findall(path=path, namespaces=namespaces)
for item in elements:
if 'nonce' in item.attrib:
raise self.failureException(f'{item} has no nonce attribute.')
if "nonce" in item.attrib:
raise self.failureException(f"{item} has no nonce attribute.")

def _fail_on_invalid_html(self, content: bytes, parser: HTMLParser):
'Fail if the passed HTML is invalid.'
"Fail if the passed HTML is invalid."
if parser.errors:
default_msg = ['Content is invalid HTML:']
lines = content.split(b'\n')
default_msg = ["Content is invalid HTML:"]
lines = content.split(b"\n")
for position, errorcode, datavars in parser.errors:
default_msg.append(' %s' % E[errorcode] % datavars)
default_msg.append(' %r' % lines[position[0] - 1])
msg = self._formatMessage(None, '\n'.join(default_msg))
default_msg.append(" %s" % E[errorcode] % datavars)
default_msg.append(" %r" % lines[position[0] - 1])
msg = self._formatMessage(None, "\n".join(default_msg))
raise self.failureException(msg)

@override_settings(
DEBUG=True, MIDDLEWARE=settings.MIDDLEWARE + [
'csp.middleware.CSPMiddleware'
])
DEBUG=True, MIDDLEWARE=settings.MIDDLEWARE + ["csp.middleware.CSPMiddleware"]
)
def test_exists(self):
'A `nonce` should exists when using the `CSPMiddleware`.'
response = self.client.get(path='/regular/basic/')
"A `nonce` should exists when using the `CSPMiddleware`."
response = self.client.get(path="/regular/basic/")
if not isinstance(response, HttpResponse):
raise self.failureException(f'{response!r} is not a HttpResponse')
raise self.failureException(f"{response!r} is not a HttpResponse")
self.assertEqual(response.status_code, 200)
parser = HTMLParser()
el_htmlroot: Element = parser.parse(stream=response.content)
self._fail_on_invalid_html(content=response.content, parser=parser)
self.assertContains(response, 'djDebug')
self.assertContains(response, "djDebug")
namespaces = _get_ns(element=el_htmlroot)
context: ContextList = \
response.context # pyright: ignore[reportAttributeAccessIssue]
nonce = str(context['toolbar'].request.csp_nonce)
context: ContextList = response.context # pyright: ignore[reportAttributeAccessIssue]
nonce = str(context["toolbar"].request.csp_nonce)
self._fail_if_missing(
root=el_htmlroot, path='.//link', namespaces=namespaces,
nonce=nonce)
root=el_htmlroot, path=".//link", namespaces=namespaces, nonce=nonce
)
self._fail_if_missing(
root=el_htmlroot, path='.//script', namespaces=namespaces,
nonce=nonce)
root=el_htmlroot, path=".//script", namespaces=namespaces, nonce=nonce
)

@override_settings(DEBUG=True)
def test_missing(self):
'A `nonce` should not exist when not using the `CSPMiddleware`.'
response = self.client.get(path='/regular/basic/')
"A `nonce` should not exist when not using the `CSPMiddleware`."
response = self.client.get(path="/regular/basic/")
if not isinstance(response, HttpResponse):
raise self.failureException(f'{response!r} is not a HttpResponse')
raise self.failureException(f"{response!r} is not a HttpResponse")
self.assertEqual(response.status_code, 200)
parser = HTMLParser()
el_htmlroot: Element = parser.parse(stream=response.content)
self._fail_on_invalid_html(content=response.content, parser=parser)
self.assertContains(response, 'djDebug')
self.assertContains(response, "djDebug")
namespaces = _get_ns(element=el_htmlroot)
self._fail_if_found(
root=el_htmlroot, path='.//link', namespaces=namespaces)
self._fail_if_found(
root=el_htmlroot, path='.//script', namespaces=namespaces)
self._fail_if_found(root=el_htmlroot, path=".//link", namespaces=namespaces)
self._fail_if_found(root=el_htmlroot, path=".//script", namespaces=namespaces)
1 change: 1 addition & 0 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def title(self):
def content(self):
raise Exception


@override_settings(DEBUG=True)
class DebugToolbarTestCase(BaseTestCase):
def test_show_toolbar(self):
Expand Down

0 comments on commit c3dc4bb

Please sign in to comment.