Skip to content

Commit

Permalink
Issue pallets#276: wrap undefined with str() to produce the correct l…
Browse files Browse the repository at this point in the history
…ineno in the traceback
  • Loading branch information
Bruno P. Kinoshita committed Jul 22, 2019
1 parent f76c3ed commit 0a129be
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
2 changes: 1 addition & 1 deletion jinja2/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1409,7 +1409,7 @@ def visit_Name(self, node, frame):
load = frame.symbols.find_load(ref)
if not (load is not None and load[0] == VAR_LOAD_PARAMETER and \
not self.parameter_is_undeclared(ref)):
self.write('(undefined(name=%r) if %s is missing else %s)' %
self.write('(str(undefined(name=%r)) if %s is missing else %s)' %
(node.name, ref, ref))
return

Expand Down
11 changes: 11 additions & 0 deletions tests/res/templates/undefined.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
This is a text with
one
{{ two }} (error happens here first!)
three
{{ four }} (error here as well)
five
{{ six }} (no error)
and more lines.

The line using the "two" variable must be the one to appear in the
traceback with a matching 'two' is missing message.
26 changes: 25 additions & 1 deletion tests/test_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
import sys
from traceback import format_exception

from jinja2 import Environment, TemplateSyntaxError
from jinja2 import Environment, TemplateSyntaxError, StrictUndefined
from jinja2.debug import make_traceback


@pytest.fixture
Expand Down Expand Up @@ -82,3 +83,26 @@ def test_local_extraction(self):
'l_0_baz': missing,
})
assert locals == {'foo': 13, 'bar': 99}

def test_traceback_lineno(self, fs_env):
'''Test for issue #276 to confirm we get the correct line number.
The undefined.html template tries to access an undefined variable
at line 3, but also accesses another undefined at line five,
and an existing variable at line seven.'''
# set strict undefined to raise an error if it tries to access an
# undefined value
fs_env.undefined = StrictUndefined
exc_info = None
try:
fs_env.get_template('undefined.html').render(six='SIX')
except:
exc_info = sys.exc_info()
traceback = make_traceback(exc_info)
exc_type, exc_value, tb = traceback.standard_exc_info
lineno = -1
while tb is not None:
if tb.tb_frame.f_code.co_filename.endswith('undefined.html'):
lineno = tb.tb_lineno
tb = tb.tb_next
assert lineno == 3

0 comments on commit 0a129be

Please sign in to comment.