Skip to content
Myr

test_forloop.py

This file

Path

tests/test_forloop.py

81 lines · 2.6 KiB · Python

Last changed by

[svn] again some jinja updates, some minor performance and doc improvementsArmin Ronacherbefore adoption9bcd411

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    unit test for loop functions4    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~56    :copyright: 2007 by Armin Ronacher.7    :license: BSD, see LICENSE for more details.8"""910SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}'''11ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}'''12EMPTYBLOCKS = '''<{% for item in seq %}{% else %}{% endfor %}>'''13CONTEXTVARS = '''{% for item in seq %}\14{{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{15   loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{16   loop.even }}|{{ loop.odd }}|{{ loop.length }}###{% endfor %}'''17CYCLING = '''{% for item in seq %}{% cycle '<1>', '<2>' %}{% endfor %}\18{% for item in seq %}{% cycle through %}{% endfor %}'''19SCOPE = '''{% for item in seq %}{% endfor %}{{ item }}'''20VARLEN = '''{% for item in iter %}{{ item }}{% endfor %}'''21NONITER = '''{% for item in none %}...{% endfor %}'''222324def test_simple(env):25    tmpl = env.from_string(SIMPLE)26    assert tmpl.render(seq=range(10)) == '0123456789'272829def test_else(env):30    tmpl = env.from_string(ELSE)31    assert tmpl.render() == '...'323334def test_empty_blocks(env):35    tmpl = env.from_string(EMPTYBLOCKS)36    assert tmpl.render() == '<>'373839def test_context_vars(env):40    tmpl = env.from_string(CONTEXTVARS)41    one, two, _ = tmpl.render(seq=[0, 1]).split('###')42    (one_index, one_index0, one_revindex, one_revindex0, one_first,43     one_last, one_even, one_odd, one_length) = one.split('|')44    (two_index, two_index0, two_revindex, two_revindex0, two_first,45     two_last, two_even, two_odd, two_length) = two.split('|')4647    assert int(one_index) == 1 and int(two_index) == 248    assert int(one_index0) == 0 and int(two_index0) == 149    assert int(one_revindex) == 2 and int(two_revindex) == 150    assert int(one_revindex0) == 1 and int(two_revindex0) == 051    assert one_first == 'True' and two_first == 'False'52    assert one_last == 'False' and two_last == 'True'53    assert one_even == 'False' and two_even == 'True'54    assert one_odd == 'True' and two_odd == 'False'55    assert one_length == two_length == '2'565758def test_cycling(env):59    tmpl = env.from_string(CYCLING)60    output = tmpl.render(seq=range(4), through=('<1>', '<2>'))61    assert output == '<1><2>' * 4626364def test_scope(env):65    tmpl = env.from_string(SCOPE)66    output = tmpl.render(seq=range(10))67    assert not output686970def test_varlen(env):71    def inner():72        for item in range(5):73            yield item74    tmpl = env.from_string(VARLEN)75    output = tmpl.render(iter=inner())76    assert output == '01234'777879def test_noniter(env):80    tmpl = env.from_string(NONITER)81    assert not tmpl.render()