Skip to content
Myr

test_runtime.py

This file

Path

tests/test_runtime.py

75 lines · 2.1 KiB · Python

Last changed by

Merge pull request #1146 from tomaskrizek/stricter-getattr-checksDavid Lordbefore adoption9fe06d8

History of this file

Take it

1import itertools23from jinja2 import Template4from jinja2.runtime import LoopContext56TEST_IDX_TEMPLATE_STR_1 = (7    "[{% for i in lst|reverse %}(len={{ loop.length }},"8    " revindex={{ loop.revindex }}, index={{ loop.index }}, val={{ i }}){% endfor %}]"9)10TEST_IDX0_TEMPLATE_STR_1 = (11    "[{% for i in lst|reverse %}(len={{ loop.length }},"12    " revindex0={{ loop.revindex0 }}, index0={{ loop.index0 }}, val={{ i }})"13    "{% endfor %}]"14)151617def test_loop_idx():18    t = Template(TEST_IDX_TEMPLATE_STR_1)19    lst = [10]20    excepted_render = "[(len=1, revindex=1, index=1, val=10)]"21    assert excepted_render == t.render(lst=lst)222324def test_loop_idx0():25    t = Template(TEST_IDX0_TEMPLATE_STR_1)26    lst = [10]27    excepted_render = "[(len=1, revindex0=0, index0=0, val=10)]"28    assert excepted_render == t.render(lst=lst)293031def test_loopcontext0():32    in_lst = []33    lc = LoopContext(reversed(in_lst), None)34    assert lc.length == len(in_lst)353637def test_loopcontext1():38    in_lst = [10]39    lc = LoopContext(reversed(in_lst), None)40    assert lc.length == len(in_lst)414243def test_loopcontext2():44    in_lst = [10, 11]45    lc = LoopContext(reversed(in_lst), None)46    assert lc.length == len(in_lst)474849def test_iterator_not_advanced_early():50    t = Template("{% for _, g in gs %}{{ loop.index }} {{ g|list }}\n{% endfor %}")51    out = t.render(52        gs=itertools.groupby([(1, "a"), (1, "b"), (2, "c"), (3, "d")], lambda x: x[0])53    )54    # groupby groups depend on the current position of the iterator. If55    # it was advanced early, the lists would appear empty.56    assert out == "1 [(1, 'a'), (1, 'b')]\n2 [(2, 'c')]\n3 [(3, 'd')]\n"575859def test_mock_not_contextfunction():60    """If a callable class has a ``__getattr__`` that returns True-like61    values for arbitrary attrs, it should not be incorrectly identified62    as a ``contextfunction``.63    """6465    class Calc(object):66        def __getattr__(self, item):67            return object()6869        def __call__(self, *args, **kwargs):70            return len(args) + len(kwargs)7172    t = Template("{{ calc() }}")73    out = t.render(calc=Calc())74    # Would be "1" if context argument was passed.75    assert out == "0"