Skip to content

Commit

Permalink
Refactor ScriptTestBase
Browse files Browse the repository at this point in the history
Althought the code `template.render(context)` looked similar, mypy
complained that Django's Template could not take a dict. Rather than
switch on types, refactor `make_context` and `make_template` into
`render`, which hides the typing details between Django templates and
extension templates like Jinja2.
  • Loading branch information
jwhitlock committed Jun 24, 2024
1 parent 3b0b947 commit de4374d
Showing 1 changed file with 11 additions and 21 deletions.
32 changes: 11 additions & 21 deletions csp/tests/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, Optional, TYPE_CHECKING, Callable, Any, Tuple, Union
from typing import Dict, Optional, TYPE_CHECKING, Callable, Any, Tuple

from django.http import HttpResponse
from django.template import Context, Template, engines
Expand All @@ -11,7 +11,6 @@

if TYPE_CHECKING:
from django.http import HttpRequest
from django.template.backends.base import _EngineTemplate


def response(*args: Any, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Callable[[HttpRequest], HttpResponse]:
Expand Down Expand Up @@ -41,30 +40,21 @@ def process_templates(self, tpl: str, expected: str) -> Tuple[str, str]:
mw.process_request(request)
nonce = getattr(request, "csp_nonce")
assert isinstance(nonce, SimpleLazyObject)
ctx = self.make_context(request)
return (
self.make_template(tpl).render(ctx).strip(), # type: ignore
expected.format(nonce),
)
return (self.render(tpl, request).strip(), expected.format(nonce))

@abstractmethod
def make_context(self, request: HttpRequest) -> Union[dict[str, Any], Context]: ...

@abstractmethod
def make_template(self, tpl: str) -> Union[_EngineTemplate, Template]: ...
def render(self, template_string: str, request: HttpRequest) -> str: ...


class ScriptTagTestBase(ScriptTestBase):
def make_context(self, request: HttpRequest) -> Context:
return Context({"request": request})

def make_template(self, tpl: str) -> Template:
return Template(tpl)
def render(self, template_string: str, request: HttpRequest) -> str:
context = Context({"request": request})
template = Template(template_string)
return template.render(context)


class ScriptExtensionTestBase(ScriptTestBase):
def make_context(self, request: HttpRequest) -> dict[str, HttpRequest]:
return {"request": request}

def make_template(self, tpl: str) -> _EngineTemplate:
return JINJA_ENV.from_string(tpl)
def render(self, template_string: str, request: HttpRequest) -> str:
context = {"request": request}
template = JINJA_ENV.from_string(template_string)
return template.render(context)

0 comments on commit de4374d

Please sign in to comment.