Example #1
0
def test_basics_9():
    template = '''
    {% set xs = items|batch(3, ' ') %}
    {{ xs[0][0] }}
    '''
    struct = infer(template)
    expected_struct = Dictionary({
        'items':
        List(Unknown(), label='items',
             linenos=[2]),  # TODO it should be Scalar
    })
    assert struct == expected_struct
Example #2
0
def test_slice():
    template = '''{{ xs[a:2:b] }}'''
    ast = parse(template).find(nodes.Getitem)
    rtype, struct = visit_getitem(ast, get_scalar_context(ast))
    assert struct == Dictionary({
        'xs':
        List(Scalar(linenos=[1]), label='xs', linenos=[1]),
        'a':
        Number(label='a', linenos=[1]),
        'b':
        Number(label='b', linenos=[1]),
    })
Example #3
0
def test_compare_2():
    template = '{{ a + b[1] - c == 4 == x }}'
    ast = parse(template).find(nodes.Compare)
    rtype, struct = visit_compare(ast, get_scalar_context(ast))
    # TODO make customizable
    expected_struct = Dictionary({
        'a': Unknown(label='a', linenos=[1]),
        'b': List(Unknown(linenos=[1]), label='b', linenos=[1]),
        'c': Unknown(label='c', linenos=[1]),
        'x': Unknown(label='x', linenos=[1]),
    })
    assert struct == expected_struct
Example #4
0
def test_getattr_3():
    template = '''{{ a[z][1:\nn][1].x }}'''
    ast = parse(template).find(nodes.Getattr)
    config = Config()
    config.TYPE_OF_VARIABLE_INDEXED_WITH_VARIABLE_TYPE = 'list'
    rtype, struct = visit_getattr(ast, get_scalar_context(ast), {}, config)

    expected_struct = Dictionary({
        'a':
        List(List(List(Dictionary({'x': Scalar(label='x', linenos=[2])},
                                  linenos=[2]),
                       linenos=[2]),
                  linenos=[1]),
             label='a',
             linenos=[1]),
        'z':
        Scalar(label='z', linenos=[1]),
        'n':
        Number(label='n', linenos=[2])
    })
    assert struct == expected_struct
Example #5
0
def test_getattr_2():
    template = '{{ data.field.subfield }}'
    ast = parse(template).find(nodes.Getattr)
    rtype, struct = visit_getattr(ast, get_scalar_context(ast))

    expected_struct = Dictionary({
        'data':
        Dictionary(
            {
                'field':
                Dictionary(
                    {
                        'subfield': Scalar(label='subfield', linenos=[1]),
                    },
                    label='field',
                    linenos=[1]),
            },
            label='data',
            linenos=[1]),
    })
    assert struct == expected_struct
def test_range_call():
    template = '{{ range(n) }}'
    ast = parse(template).find(nodes.Call)

    rtype, struct = visit_call(ast, Context(predicted_struct=Unknown()))

    expected_rtype = List(Number())
    assert rtype == expected_rtype

    expected_struct = Dictionary({
        'n': Number(label='n', linenos=[1]),
    })
    assert struct == expected_struct
def test_join_filter():
    ast = parse('{{ xs|join(separator|default("|")) }}').find(nodes.Filter)
    rtype, struct = visit_filter(ast, get_scalar_context(ast))
    assert rtype == String(label='xs', linenos=[1])
    assert struct == Dictionary({
        'xs':
        List(String(), label='xs', linenos=[1]),
        'separator':
        String(label='separator',
               linenos=[1],
               used_with_default=True,
               value='|'),
    })
Example #8
0
def test_test_1():
    template = '''{{ x is divisibleby data.field }}'''
    ast = parse(template).find(nodes.Test)
    rtype, struct = visit_test(ast, get_scalar_context(ast))

    expected_struct = Dictionary({
        'x': Scalar(label='x', linenos=[1]),
        'data': Dictionary({
            'field': Number(label='field', linenos=[1]),
        }, label='data', linenos=[1])
    })

    assert struct == expected_struct

    template = '''{{ x is divisibleby 3 }}'''
    ast = parse(template).find(nodes.Test)
    rtype, struct = visit_test(ast, get_scalar_context(ast))

    expected_struct = Dictionary({
        'x': Scalar(label='x', linenos=[1]),
    })
    assert struct == expected_struct
Example #9
0
def test_boolean_conditions_setting_2():
    config = Config(BOOLEAN_CONDITIONS=True)

    template = '''
    {% if x == 'test' %}
        Hello!
    {% endif %}
    '''
    struct = infer(template, config)
    expected_struct = Dictionary({
        'x': Unknown(label='x', linenos=[2]),
    })
    assert struct == expected_struct
Example #10
0
def test_basics_11():
    template = '''
    {{ a|xmlattr }}
    {{ a.attr1|join(',') }}
    {{ a.attr2|default([])|first }}
    {{ a.attr3|default('gsom') }}
    {% for x in xs|rejectattr('is_active') %}
        {{ x }}
    {% endfor %}
    '''
    struct = infer(template)
    expected_struct = Dictionary({
        'a':
        Dictionary(
            {
                'attr1':
                List(String(), label='attr1', linenos=[3]),
                'attr2':
                List(Scalar(linenos=[4]),
                     label='attr2',
                     linenos=[4],
                     used_with_default=True),
                'attr3':
                String(label='attr3',
                       linenos=[5],
                       used_with_default=True,
                       value='gsom')
            },
            label='a',
            linenos=[2, 3, 4, 5]),
        'xs':
        List(
            Scalar(label='x', linenos=[
                7
            ]),  # TODO it should be Dictionary({'is_active': Unknown()})
            label='xs',
            linenos=[6]),
    })
    assert struct == expected_struct
Example #11
0
def test_test_2():
    template = '''{{ x is string }}'''
    ast = parse(template).find(nodes.Test)
    rtype, struct = visit_test(ast, get_scalar_context(ast))

    expected_struct = Dictionary({'x': Unknown(label='x', linenos=[1])})
    assert struct == expected_struct

    template = '{{ x is unknown_filter }}'
    ast = parse(template).find(nodes.Test)
    with pytest.raises(InvalidExpression) as e:
        visit_test(ast, get_scalar_context(ast))
    assert 'line 1: unknown test "unknown_filter"' in str(e.value)
Example #12
0
def test_lipsum_call():
    template = '{{ lipsum(n) }}'
    ast = parse(template).find(nodes.Call)

    rtype, struct = visit_call(ast, Context(predicted_struct=Unknown()))

    expected_rtype = String()
    assert rtype == expected_rtype

    expected_struct = Dictionary({
        'n': Scalar(label='n', linenos=[1]),  # TODO must be Number
    })
    assert struct == expected_struct
def test_tuple_as_list():
    template = '''
{% macro selectinputtuple(name, values, value='') -%}
    <select class="form-control" name="{{ name }}" id="{{ name }}">
    {% for v2 in values %}
        <option value="{{ v2[0] }}"  {{ 'selected' if value==v2[0] }}>{{ v2[1] }}</option>
    {% endfor %}
    </select>
{%- endmacro %}
    </td><td style="padding-right: 5px;">{{ selectinputtuple("ipp",[('0','Fit'),('1','1'),('1000','1000')],data.ipp) }}
    '''

    struct = infer(template)
    expected_struct = Dictionary({
        'data':
        Dictionary(label="data",
                   data={
                       'ipp': String(label="ipp", linenos=[2, 9], value=""),
                   },
                   linenos=[9]),
    })
    assert struct == expected_struct
Example #14
0
def test_basics_1():
    template = '''
    {% set d = {'x': 123, a: z.qwerty} %}
    {{ d.x }}
    '''
    struct = infer(template)
    expected_struct = Dictionary({
        'a':
        Scalar(label='a', linenos=[2]),
        'z':
        Dictionary(label='z',
                   data={
                       'qwerty': Unknown(label='qwerty', linenos=[2]),
                   },
                   linenos=[2]),
    })
    assert struct == expected_struct

    template = '''
    {% set d = {'x': 123, a: z.qwerty} %}
    {{ d.x.field }}
    '''
    with pytest.raises(MergeException):
        infer(template)

    template = '''
    {% set x = '123' %}
    {{ x.test }}
    '''
    with pytest.raises(MergeException):
        infer(template)

    template = '''
    {% set a = {'x': 123} %}
    {% set b = {a: 'test'} %}
    '''
    with pytest.raises(MergeException):
        infer(template)
Example #15
0
def test_ignore_all_unknown_filter():
    template = '{{ x|foo|bar|baz }}'

    cfg = config.default_config
    cfg.IGNORE_UNKNOWN_FILTERS = True

    ast = parse(template).find(nodes.Filter)
    rtype, struct = visit_filter(ast, get_scalar_context(ast), None, cfg)

    assert rtype == Unknown(label='x', linenos=[1])
    expected_struct = Dictionary({
        'x': Unknown(label='x', linenos=[1]),
    })
    assert struct == expected_struct
Example #16
0
def test_extend_with_block_override_3():
    env = Environment(loader=PackageLoader('tests', 'templates'))
    struct = infer(
        env.loader.get_source(env, 'inner_override_3.html')[0],
        Config(PACKAGE_NAME='tests'))
    expected_struct = Dictionary({
        'location':
        Scalar(label='location', linenos=[6]),
        'mood':
        Scalar(label='mood', linenos=[9]),
        'name':
        Scalar(label='name', linenos=[3]),
    })
    assert struct == expected_struct
def test_if_1():
    template = '''
    {% if (x or y) and not z %}
        {{ x }}
        {{ z.field }}
    {% endif %}
    '''
    ast = parse(template).find(nodes.If)
    struct = visit_if(ast)

    expected_struct = Dictionary({
        'z':
        Dictionary({
            'field': Scalar(label='field', linenos=[4]),
        },
                   label='z',
                   linenos=[2, 4]),
        'x':
        Scalar(label='x', linenos=[2, 3]),
        'y':
        Unknown(label='y', linenos=[2]),
    })
    assert struct == expected_struct
Example #18
0
def test_assignment():
    template = '''
    {% set args = ['foo'] if foo else [] %}
    {% set args = args + ['bar'] %}
    {% set args = args + (['zork'] if zork else []) %}
    f({{ args|join(sep) }});
    '''
    struct = infer(template)
    expected_struct = Dictionary({
        'foo': Unknown(label='foo', linenos=[2]),
        'zork': Unknown(label='zork', linenos=[4]),
        'sep': String(label='sep', linenos=[5])
    })
    assert struct == expected_struct
def test_if_2():
    template = '''
    {% if z > x > y %}
    {% endif %}
    {% if x == y and x == 'asd' and z == 5 %}
    {% endif %}
    {{ x }}
    '''
    struct = infer_from_ast(parse(template))
    expected_struct = Dictionary({
        'x': Scalar(label='x', linenos=[2, 4, 6]),
        'y': Unknown(label='y', linenos=[2, 4]),
        'z': Unknown(label='z', linenos=[2, 4]),
    })
    assert struct == expected_struct
def test_assign_5():
    template = '''
    {%- set weights = [
        ('A', {'data': 0.3}),
        ('B', {'data': 0.9}),
    ] %}
    '''
    ast = parse(template).find(nodes.Assign)
    struct = visit_assign(ast)
    expected_struct = Dictionary({
        'weights':
        List(Tuple([
            String(linenos=[3, 4], constant=True),
            Dictionary({'data': Number(linenos=[3, 4], constant=True)},
                       linenos=[3, 4],
                       constant=True),
        ],
                   linenos=[3, 4],
                   constant=True),
             label='weights',
             linenos=[2],
             constant=True)
    })
    assert struct == expected_struct
Example #21
0
def test_filter_chaining():
    template = '''{{ (xs|first|last).gsom|sort|length }}'''
    ast = parse(template).find(nodes.Filter)
    rtype, struct = visit_filter(ast, get_scalar_context(ast))

    expected_struct = Dictionary({
        'xs':
        List(List(Dictionary(
            {
                'gsom': List(Unknown(), label='gsom', linenos=[1]),
            },
            linenos=[1]),
                  linenos=[1]),
             label='xs',
             linenos=[1]),
    })
    assert struct == expected_struct

    template = '''{{ x|list|sort|first }}'''
    ast = parse(template).find(nodes.Filter)
    rtype, struct = visit_filter(ast, get_scalar_context(ast))

    expected_struct = Dictionary({
        'x': Scalar(label='x', linenos=[1]),
    })
    assert struct == expected_struct

    template = '''{{ x|first|list }}'''
    ast = parse(template).find(nodes.Filter)
    with pytest.raises(UnexpectedExpression) as e:
        visit_filter(ast, get_scalar_context(ast))
    expected = "conflict on the line 1\n\
got: AST node jinja2.nodes.Filter of structure [<scalar>]\n\
expected structure: <scalar>"

    assert expected == str(e.value)
def test_string_filters():
    for filter in ('striptags', 'capitalize', 'title', 'upper', 'urlize'):
        template = '{{ x|' + filter + ' }}'
        ast = parse(template).find(nodes.Filter)

        ctx = Context(return_struct_cls=Scalar,
                      predicted_struct=Scalar.from_ast(ast))
        rtype, struct = visit_filter(ast, ctx)

        expected_rtype = String(label='x', linenos=[1])
        expected_struct = Dictionary({
            'x': String(label='x', linenos=[1]),
        })
        assert rtype == expected_rtype
        assert struct == expected_struct
Example #23
0
def test_splitlines():
    template = '''
{% macro NL2BR (text) -%}
  {% for line in (text or '').splitlines() %}
    {{line}}<br>
  {% endfor %}
{%- endmacro %}
    {{ NL2BR(vin) }}
    '''

    struct = infer(template)
    expected_struct = Dictionary({
        'vin': String(label="vin", linenos=[2, 7]),
    })
    assert struct == expected_struct
Example #24
0
def test_block_1():
    config = Config()

    template = '''
        {% block test %}
            {{ x }}
            {{ y }}
        {% endblock %}
    '''
    struct = infer(template, config)
    expected_struct = Dictionary({
        'x': Scalar(label='x', linenos=[3]),
        'y': Scalar(label='y', linenos=[4]),
    })
    assert struct == expected_struct
Example #25
0
def test_basics_14():
    template = '''
    {{ section.FILTERS.test }}
    {%- for f in section.FILTERS.keys() %}
        {{ section.GEO }}
        {{ loop.index }}
    {%- endfor %}
    '''
    struct = infer(template)
    expected_struct = Dictionary({
        'section':
        Dictionary(
            {
                'FILTERS':
                Dictionary({'test': Scalar(label='test', linenos=[2])},
                           label='FILTERS',
                           linenos=[2, 3]),
                'GEO':
                Scalar(label='GEO', linenos=[4]),
            },
            label='section',
            linenos=[2, 3, 4])
    })
    assert struct == expected_struct
Example #26
0
def test_getitem_3():
    template = '''{{ a[3] }}'''
    ast = parse(template).find(nodes.Getitem)
    config = Config()
    config.TYPE_OF_VARIABLE_INDEXED_WITH_INTEGER_TYPE = 'tuple'
    rtype, struct = visit_getitem(ast, get_scalar_context(ast), {}, config)

    expected_struct = Dictionary({
        'a': Tuple([
            Unknown(),
            Unknown(),
            Unknown(),
            Scalar(linenos=[1]),
        ], label='a', linenos=[1]),
    })
    assert struct == expected_struct
Example #27
0
def test_extend_with_block_override_4(env, config):
    struct = infer(
        env.loader.get_source(env, 'inner_extend_override_4.html')[0], config)
    expected_struct = Dictionary({
        'noblock':
        Scalar(label='noblock', linenos=[1]),
        'brake':
        Scalar(label='brake', linenos=[3]),
        'location':
        Scalar(label='location', linenos=[6]),
        'mood':
        Scalar(label='mood', linenos=[9]),
        'name':
        Scalar(label='name', linenos=[3]),
    })
    assert struct == expected_struct
Example #28
0
def test_for_2():
    template = '''
    {% for x in xs %}
        {{ x }}
        {% for y in ys %}
            {{ loop.index0 }}
        {% endfor %}
        {{ loop.length }}
    {% endfor %}
    '''
    ast = parse(template)
    struct = infer_from_ast(ast)

    expected_struct = Dictionary({
        'xs': List(Scalar(label='x', linenos=[3]), label='xs', linenos=[2]),
        'ys': List(Unknown(linenos=[4]), label='ys', linenos=[4]),
    })
    assert struct == expected_struct
Example #29
0
def test_basics_8():
    template = '''
    {% for row in items|batch(3, '&nbsp;')|batch(1) %}
        {{ row[1].name }}
    {% endfor %}
    '''
    with pytest.raises(UnexpectedExpression) as excinfo:
        infer(template)
    e = excinfo.value

    assert isinstance(e.actual_ast, nodes.Filter)
    assert e.expected_struct == List(
        Dictionary({
            'name': Scalar(label='name', constant=False, linenos=[3])
        }, constant=False, linenos=[3]),
        label='row', constant=False, linenos=[2, 3]
    )
    assert e.actual_struct == List(List(Unknown()))
Example #30
0
def test_basics_13():
    config = Config()
    config.TYPE_OF_VARIABLE_INDEXED_WITH_INTEGER_TYPE = 'tuple'

    template = '''
    {% for x in xs %}
        {{ x[2] }}
        {{ x[3] }}
    {% endfor %}
    '''
    struct = infer(template, config)
    expected_struct = Dictionary({
        'xs': List(Tuple((
            Unknown(label=None, linenos=[]),
            Unknown(label=None, linenos=[]),
            Scalar(label=None, linenos=[3]),
            Scalar(label=None, linenos=[4]),
        ), label='x', linenos=[3, 4]), label='xs', linenos=[2])
    })
    assert struct == expected_struct