1import itertools 2 3from jinja2 import Template 4from jinja2.runtime import LoopContext 5 6TEST_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) 15 16 17def 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) 22 23 24def 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) 29 30 31def test_loopcontext0(): 32 in_lst = [] 33 lc = LoopContext(reversed(in_lst), None) 34 assert lc.length == len(in_lst) 35 36 37def test_loopcontext1(): 38 in_lst = [10] 39 lc = LoopContext(reversed(in_lst), None) 40 assert lc.length == len(in_lst) 41 42 43def test_loopcontext2(): 44 in_lst = [10, 11] 45 lc = LoopContext(reversed(in_lst), None) 46 assert lc.length == len(in_lst) 47 48 49def 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. If 55 # it was advanced early, the lists would appear empty. 56 assert out == "1 [(1, 'a'), (1, 'b')]\n2 [(2, 'c')]\n3 [(3, 'd')]\n" 57 58 59def test_mock_not_contextfunction(): 60 """If a callable class has a ``__getattr__`` that returns True-like 61 values for arbitrary attrs, it should not be incorrectly identified 62 as a ``contextfunction``. 63 """ 64 65 class Calc: 66 def __getattr__(self, item): 67 return object() 68 69 def __call__(self, *args, **kwargs): 70 return len(args) + len(kwargs) 71 72 t = Template("{{ calc() }}") 73 out = t.render(calc=Calc()) 74 # Would be "1" if context argument was passed. 75 assert out == "0" 76