Skip to content
Myr

test_debug.py

This file

Path

tests/test_debug.py

117 lines · 3.6 KiB · Python

Last changed by

Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7

History of this file

Take it

1# -*- coding: utf-8 -*-2import pickle3import re4from traceback import format_exception56import pytest78from jinja2 import ChoiceLoader9from jinja2 import DictLoader10from jinja2 import Environment11from jinja2 import TemplateSyntaxError121314@pytest.fixture15def fs_env(filesystem_loader):16    """returns a new environment."""17    return Environment(loader=filesystem_loader)181920@pytest.mark.debug21class TestDebug(object):22    def assert_traceback_matches(self, callback, expected_tb):23        with pytest.raises(Exception) as exc_info:24            callback()2526        tb = format_exception(exc_info.type, exc_info.value, exc_info.tb)27        m = re.search(expected_tb.strip(), "".join(tb))28        assert m is not None, "Traceback did not match:\n\n%s\nexpected:\n%s" % (29            "".join(tb),30            expected_tb,31        )3233    def test_runtime_error(self, fs_env):34        def test():35            tmpl.render(fail=lambda: 1 / 0)3637        tmpl = fs_env.get_template("broken.html")38        self.assert_traceback_matches(39            test,40            r"""41  File ".*?broken.html", line 2, in (top-level template code|<module>)42    \{\{ fail\(\) \}\}43  File ".*debug?.pyc?", line \d+, in <lambda>44    tmpl\.render\(fail=lambda: 1 / 0\)45ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero46""",47        )4849    def test_syntax_error(self, fs_env):50        # The trailing .*? is for PyPy 2 and 3, which don't seem to51        # clear the exception's original traceback, leaving the syntax52        # error in the middle of other compiler frames.53        self.assert_traceback_matches(54            lambda: fs_env.get_template("syntaxerror.html"),55            """(?sm)56  File ".*?syntaxerror.html", line 4, in (template|<module>)57    \\{% endif %\\}.*?58(jinja2\\.exceptions\\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja \59was looking for the following tags: 'endfor' or 'else'. The innermost block that needs \60to be closed is 'for'.61    """,62        )6364    def test_regular_syntax_error(self, fs_env):65        def test():66            raise TemplateSyntaxError("wtf", 42)6768        self.assert_traceback_matches(69            test,70            r"""71  File ".*debug.pyc?", line \d+, in test72    raise TemplateSyntaxError\("wtf", 42\)73(jinja2\.exceptions\.)?TemplateSyntaxError: wtf74  line 42""",75        )7677    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.name8283    def test_include_syntax_error_source(self, filesystem_loader):84        e = Environment(85            loader=ChoiceLoader(86                [87                    filesystem_loader,88                    DictLoader({"inc": "a\n{% include 'syntaxerror.html' %}\nb"}),89                ]90            )91        )92        t = e.get_template("inc")9394        with pytest.raises(TemplateSyntaxError) as exc_info:95            t.render()9697        assert exc_info.value.source is not None9899    def test_local_extraction(self):100        from jinja2.debug import get_template_locals101        from jinja2.runtime import missing102103        locals = get_template_locals(104            {105                "l_0_foo": 42,106                "l_1_foo": 23,107                "l_2_foo": 13,108                "l_0_bar": 99,109                "l_1_bar": missing,110                "l_0_baz": missing,111            }112        )113        assert locals == {"foo": 13, "bar": 99}114115    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