3
from traceback import format_exception
7
from jinja2 import ChoiceLoader
8
from jinja2 import DictLoader
9
from jinja2 import Environment
10
from jinja2 import TemplateSyntaxError
14
def fs_env(filesystem_loader):
15
"""returns a new environment."""
16
return Environment(loader=filesystem_loader)
20
def assert_traceback_matches(self, callback, expected_tb):
21
with pytest.raises(Exception) as exc_info:
24
tb = format_exception(exc_info.type, exc_info.value, exc_info.tb)
25
m = re.search(expected_tb.strip(), "".join(tb))
28
), f"Traceback did not match:\n\n{''.join(tb)}\nexpected:\n{expected_tb}"
30
def test_runtime_error(self, fs_env):
32
tmpl.render(fail=lambda: 1 / 0)
34
tmpl = fs_env.get_template("broken.html")
35
self.assert_traceback_matches(
38
File ".*?broken.html", line 2, in (top-level template code|<module>)
41
File ".*debug?.pyc?", line \d+, in <lambda>
42
tmpl\.render\(fail=lambda: 1 / 0\)(
44
ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero
48
def test_syntax_error(self, fs_env):
49
# The trailing .*? is for PyPy 2 and 3, which don't seem to
50
# clear the exception's original traceback, leaving the syntax
51
# error in the middle of other compiler frames.
52
self.assert_traceback_matches(
53
lambda: fs_env.get_template("syntaxerror.html"),
55
File ".*?syntaxerror.html", line 4, in (template|<module>)
57
(jinja2\\.exceptions\\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja \
58
was looking for the following tags: 'endfor' or 'else'. The innermost block that needs \
63
def test_regular_syntax_error(self, fs_env):
65
raise TemplateSyntaxError("wtf", 42)
67
self.assert_traceback_matches(
70
File ".*debug.pyc?", line \d+, in test
71
raise TemplateSyntaxError\("wtf", 42\)(
73
(jinja2\.exceptions\.)?TemplateSyntaxError: wtf
77
def test_pickleable_syntax_error(self, fs_env):
78
original = TemplateSyntaxError("bad template", 42, "test", "test.txt")
79
unpickled = pickle.loads(pickle.dumps(original))
80
assert str(original) == str(unpickled)
81
assert original.name == unpickled.name
83
def test_include_syntax_error_source(self, filesystem_loader):
88
DictLoader({"inc": "a\n{% include 'syntaxerror.html' %}\nb"}),
92
t = e.get_template("inc")
94
with pytest.raises(TemplateSyntaxError) as exc_info:
97
assert exc_info.value.source is not None
99
def test_local_extraction(self):
100
from jinja2.debug import get_template_locals
101
from jinja2.runtime import missing
103
locals = get_template_locals(
113
assert locals == {"foo": 13, "bar": 99}
115
def test_get_corresponding_lineno_traceback(self, fs_env):
116
tmpl = fs_env.get_template("test.html")
117
assert tmpl.get_corresponding_lineno(1) == 1