Skip to content

Commit

Permalink
fail-on-template-vars: be more discreet with ignore_template_errors
Browse files Browse the repository at this point in the history
  • Loading branch information
xavfernandez committed Apr 25, 2024
1 parent 11f613d commit f5c5f37
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
11 changes: 8 additions & 3 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,8 +644,9 @@ def _fail_for_invalid_template_variable():
class InvalidVarException:
"""Custom handler for invalid strings in templates."""

def __init__(self) -> None:
def __init__(self, *, origin_value="") -> None:
self.fail = True
self.origin_value = origin_value

def __contains__(self, key: str) -> bool:
return key == "%s"
Expand Down Expand Up @@ -696,7 +697,7 @@ def __mod__(self, var: str) -> str:
if self.fail:
pytest.fail(msg)
else:
return msg
return self.origin_value

with pytest.MonkeyPatch.context() as mp:
if (
Expand All @@ -709,7 +710,11 @@ def __mod__(self, var: str) -> str:
mp.setitem(
dj_settings.TEMPLATES[0]["OPTIONS"],
"string_if_invalid",
InvalidVarException(),
InvalidVarException(
origin_value=dj_settings.TEMPLATES[0]["OPTIONS"].get(
"string_if_invalid", ""
)
),
)
yield

Expand Down
44 changes: 44 additions & 0 deletions tests/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,50 @@ def test_for_invalid_template(client):
)


@pytest.mark.django_project(
extra_settings="""
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
TEMPLATES[0]["OPTIONS"]["string_if_invalid"] = "Something clever"
"""
)
def test_invalid_template_variable_behaves_normally_when_ignored(
django_pytester: DjangoPytester
) -> None:
django_pytester.create_app_file(
"<div>{{ invalid_var }}</div>", "templates/invalid_template_base.html"
)
django_pytester.create_app_file(
"{% include 'invalid_template_base.html' %}", "templates/invalid_template.html"
)
django_pytester.create_test_module(
"""
from django.template.loader import render_to_string
import pytest
@pytest.mark.ignore_template_errors
def test_ignore(client):
assert render_to_string('invalid_template.html') == "<div>Something clever</div>"
def test_for_invalid_template(client):
render_to_string('invalid_template.html')
"""
)
result = django_pytester.runpytest_subprocess("-s", "--fail-on-template-vars")

origin = "'*/tpkg/app/templates/invalid_template_base.html'"
result.stdout.fnmatch_lines_random(
[
"tpkg/test_the_test.py .F*",
f"E * Failed: Undefined template variable 'invalid_var' in {origin}",
]
)


@pytest.mark.django_project(
extra_settings="""
TEMPLATE_LOADERS = (
Expand Down

0 comments on commit f5c5f37

Please sign in to comment.