Beispiel #1
0
def test_forloop():
    tpl = """
    {% for product in products %}
        {% if forloop.first == true %}
            First time through!
        {% else %}
            Not the first time.
        {% endif %}
    {% endfor %}
    """
    rendered = Liquid(tpl).render(products=range(5)).splitlines()
    rendered = [ren.strip() for ren in rendered if ren.strip()]
    assert rendered == [
        'First time through!',
        'Not the first time.',
        'Not the first time.',
        'Not the first time.',
        'Not the first time.',
    ]

    tpl = """
    {% for product in products %}
        {{ forloop.index }}
    {% else %}
        // no products in your frontpage collection
    {% endfor %}
    """
    assert Liquid(tpl).render(products=range(5)).split() == [
        "1", "2", "3", "4", "5"
    ]
Beispiel #2
0
def test_for_params():
    tpl = """
    {% for item in array limit:2 %}
      {{ item }}
    {% endfor %}
    """
    assert Liquid(tpl).render(array=[1, 2, 3, 4, 5, 6]).split() == ["1", "2"]

    tpl = """
    {% for item in array offset:2 %}
      {{ item }}
    {% endfor %}
    """
    assert Liquid(tpl).render(array=[1, 2, 3, 4, 5, 6]).split() == [
        "3", "4", "5", "6"
    ]

    tpl = """
    {% for item in array limit:2 offset:2 %}
      {{ item }}
    {% endfor %}
    """
    assert Liquid(tpl).render(array=[1, 2, 3, 4, 5, 6]).split() == ["3", "4"]

    tpl = """
    {% for i in (3..5) %}
      {{ i }}
    {% endfor %}

    {% assign num = 4 %}
    {% for i in (1..num) %}
      {{ i }}
    {% endfor %}
    """
    assert Liquid(tpl).render().split() == ["3", "4", "5", "1", "2", "3", "4"]
Beispiel #3
0
def test_operators():
    tpl = """
    {%- if product.title == "Awesome Shoes" -%}
      These shoes are awesome!
    {%- endif -%}
    """
    assert Liquid(tpl).render(
        product={'title': 'Awesome Shoes'}) == ('These shoes are awesome!')

    tpl = """
    {%- if product.type == "Shirt" or product.type == "Shoes" -%}
      This is a shirt or a pair of shoes.
    {%- endif -%}
    """
    assert Liquid(tpl).render(
        product={'type': 'Shirt'}) == ('This is a shirt or a pair of shoes.')

    tpl = """
    {%- if product.title contains "Pack" -%}
      This product's title contains the word Pack.
    {%- endif -%}
    """
    assert Liquid(tpl).render(product={'title': 'Show Pack'}) == (
        "This product's title contains the word Pack.")

    tpl = """
    {%- if product.tags contains "Hello" -%}
      This product has been tagged with "Hello".
    {%- endif -%}
    """
    assert Liquid(tpl).render(product={'tags': 'Hello Pack'}) == (
        'This product has been tagged with "Hello".')
Beispiel #4
0
def test_case_when_error(set_default_standard):
    with pytest.raises(TemplateSyntaxError, match="Expected nothing"):
        Liquid("{% case a %}0{% when 1 %}1{% endcase %}")

    with pytest.raises(TemplateSyntaxError,
                       match="Expected 'begin of statement block'"):
        Liquid("{% case a %}")
Beispiel #5
0
def test_concat():
    tpl = """
    {%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
    {%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}

    {%- assign everything = fruits | concat: vegetables -%}

    {%- for item in everything %}
    - {{ item }}
    {%- endfor %}
    """
    assert Liquid(tpl).render() == """
    - apples
    - oranges
    - peaches
    - carrots
    - turnips
    - potatoes
    """

    tpl = """
    {%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
    {%- assign furniture = "chairs, tables, shelves" | split: ", " -%}
    {%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}

    {%- assign everything = fruits | concat: vegetables | concat: furniture -%}

    {%- for item in everything %}
    - {{ item }}
    {%- endfor %}
    """
    assert Liquid(tpl).render() == """
Beispiel #6
0
def test_newline_filters(set_default_standard):
    assert Liquid("{{ x | newline_to_br }}").render(x="apple\nwatch") == (
        "apple<br />watch"
    )
    assert Liquid("{{ x | strip_newlines }}").render(x="apple\nwatch") == (
        "applewatch"
    )
Beispiel #7
0
def test_for_cycle():
    tpl = """
    {% for i in (1..4) %}
        {% cycle "one", "two", "three" %}
    {% endfor %}
    """
    assert Liquid(tpl).render().split() == [
        'one',
        'two',
        'three',
        'one',
    ]

    tpl = """
    {% for i in (1..2) %}
        {% cycle "first": "one", "two", "three" %}
        {% cycle "second": "one", "two", "three" %}
    {% endfor %}
    """
    assert Liquid(tpl).render().split() == [
        'one',
        'one',
        'two',
        'two',
    ]
Beispiel #8
0
def test_comments():

    liq = Liquid("""{% mode compact %}
4
{% comment %}
1
2
{% endcomment %}
5
""",
                 liquid_loglevel='debug')
    assert liq.render() == '4# 1\n# 25'

    liq = Liquid("""{% mode compact %}
4
{% comment // %}
1
2
{% endcomment %}
5
""")
    assert liq.render() == '4// 1\n// 25'

    liq = Liquid("""{% mode compact %}
4{# aa #}
{% comment /* */ %}
1
2
{% endcomment %}
5
""")
    assert liq.render() == '4/* 1 */\n/* 2 */5'
Beispiel #9
0
def test_extends():
    liquid = Liquid("""{{% mode compact %}}
    {{% extends {}/templates/parent1.liq %}}
    {{% block x %}}
    {{{{x * 10}}}}
    {{% endblock %}}
    """.format(HERE))
    liquid.render(x=1) == '10'

    liquid = Liquid("""{{% mode compact %}}
    {{% extends {}/templates/parent2.liq %}}
    {{% block y %}}
    {{{{x * 10}}}}
    {{% endblock %}}
    """.format(HERE))
    liquid.render(x=1) == '3'

    with pytest.raises(LiquidSyntaxError):  # not exists
        Liquid("{% extends 'xxx' %}")

    # only blocks, ignored
    liquid = Liquid("""{{% mode compact %}}
    {{% block x %}}
    {{{{x * 10}}}}
    {{% endblock %}}
    """.format(HERE))
    liquid.render(x=1) == '10'
Beispiel #10
0
def test_wscontrol(set_default_standard):
    tpl = """
{% assign my_variable = "tomato" %}
{{ my_variable }}"""

    assert Liquid(tpl).render() == "\n\ntomato"
    tpl = """
{%- assign my_variable = "tomato" -%}
{{ my_variable }}"""

    assert Liquid(tpl).render() == "tomato"

    tpl = """{% assign username = "******" %}
{% if username and username.size > 10 %}
  Wow, {{ username }}, you have a long name!
{% else %}
  Hello there!
{% endif %}"""
    assert (
        Liquid(tpl).render()
        == "\n\n  Wow, John G. Chalmers-Smith, you have a long name!\n"
    )

    tpl = """{%- assign username = "******" -%}
{%- if username and username.size > 10 -%}
  Wow, {{ username }}, you have a long name!
{%- else -%}
  Hello there!
{%- endif -%}"""
    assert (
        Liquid(tpl).render()
        == "Wow, John G. Chalmers-Smith, you have a long name!"
    )
Beispiel #11
0
def test_include(set_default_wild):
    subtpl = Path(__file__).parent.joinpath("subtpl.liq")

    # default
    tpl = f"""
    {{% assign variable = 8525 %}}
    {{% include "{subtpl}" %}}
    """
    out = Liquid(tpl).render().strip()
    assert out == "|8525|"

    # with context
    tpl = f"""
    {{% assign variable = 8525 %}}
    {{% include "{subtpl}" with context %}}
    """
    out = Liquid(tpl).render().strip()
    assert out == "|8525|"

    # without context
    tpl = f"""
    {{% assign variable = 8525 %}}
    {{% include "{subtpl}" without context %}}
    """
    out = Liquid(tpl).render().strip()
    assert out == "||"
Beispiel #12
0
def test_for_cycle(set_default_standard):
    tpl = """
    {% for i in (1..4) %}
        {% cycle "one", "two", "three" %}
    {% endfor %}
    """
    assert Liquid(tpl).render().split() == [
        "one",
        "two",
        "three",
        "one",
    ]

    tpl = """
    {% for i in (1..2) %}
        {% cycle "first": "one", "two", "three" %}
        {% cycle "second": "one", "two", "three" %}
    {% endfor %}
    """
    assert Liquid(tpl).render().split() == [
        "one",
        "one",
        "two",
        "two",
    ]
Beispiel #13
0
def test_sort_error(set_default_jekyll):
    template = Liquid("{{ x | sort }}")
    with pytest.raises(ValueError):
        template.render(x=None)

    template = Liquid("{{ x | sort: p, n }}")
    with pytest.raises(ValueError):
        template.render(x=[], p=None, n=None)
Beispiel #14
0
def test_init(HERE):
    with pytest.raises(FileNotFoundError):
        Liquid("a", liquid_from_file=True)

    tpl = HERE / 'templates' / 'parent5.liq'
    with tpl.open() as f:
        liq = Liquid(f, liquid_from_stream=True)

    assert liq.render() == "empty block"
Beispiel #15
0
def test_regex_replace(set_default_standard):
    assert Liquid('{{1 | regex_replace: "a"}}').render() == "1"
    assert Liquid('{{"abc" | regex_replace: "a", "b"}}').render() == "bbc"
    assert (
        Liquid(
            '{{"abc" | regex_replace: "A", "b", case_sensitive=False}}'
        ).render()
        == "bbc"
    )
Beispiel #16
0
def test_uri_escape(set_default_jekyll):
    assert (Liquid("{{ x | uri_escape }}").render(
        x="my things") == "my%20things")
    assert (Liquid("{{ x | uri_escape }}").render(
        x="foo!*'();:@&=+$,/?#[]bar") == "foo!*'();:@&=+$,/?#[]bar")
    assert (Liquid("{{ x | uri_escape }}").render(
        x="foo bar!*'();:@&=+$,/?#[]baz") == "foo%20bar!*'();:@&=+$,/?#[]baz")
    assert (Liquid("{{ x | uri_escape }}").render(
        x="http://foo.com/?q=foo, \\bar?") ==
            "http://foo.com/?q=foo,%20%5Cbar?")
Beispiel #17
0
def test_ifelse(set_default_wild):
    tpl = """{{ a | ifelse: isinstance, (int, ),
               "plus", (1, ),
               "append", (".html", ) }}"""

    out = Liquid(tpl).render(a=1)
    assert out == "2"

    out = Liquid(tpl).render(a="a")
    assert out == "a.html"
Beispiel #18
0
def test_relative_url(set_default_jekyll):
    with pytest.raises(ValueError, match="Global variables"):
        Liquid('{{"b/c" | relative_url}}').render()

    out = Liquid('{{"b/c" | relative_url}}',
                 globals={
                     "site": {
                         "baseurl": "/a"
                     }
                 }).render()
    assert out == "/a/b/c"
Beispiel #19
0
def test_filters(set_default_standard):
    assert Liquid('{{ "/my/fancy/url" | append: ".html" }}').render() == (
        "/my/fancy/url.html"
    )

    assert Liquid(
        '{{ "adam!" | capitalize | prepend: "Hello " }}'
    ).render() == ("Hello Adam!")
    # test keyword argument
    assert Liquid(
        '{{ "hello adam!" | replace_first: "adam", new:"Adam" | remove: "hello "}}'
    ).render() == ("Adam!")
Beispiel #20
0
def test_unless_elif(set_default_standard):
    tpl = """
    {% unless a == 1 %}
    11
    {% elif a == 2 %}
    22
    {% else %}
    33
    {% endunless %}
    """
    assert Liquid(tpl).render(a=1).strip() == "22"
    assert Liquid(tpl).render(a=2).strip() == "11"
Beispiel #21
0
def test_python():
    liq = Liquid("{% python _liquid_ret_append('123') %}",
                 liquid_loglevel='debug')
    assert liq.render() == '123'

    liq = Liquid("""
{%- python -%}
import math
_liquid_ret_append(math.ceil(1.1))
{%- endpython -%}""",
                 liquid_loglevel='debug')
    assert liq.render() == '2'
Beispiel #22
0
def test_include():
    liq = Liquid(f"{{% include {HERE}/templates/include1.liq x=x %}}{{{{x}}}}")
    assert liq.render(x=1) == '81'

    with pytest.raises(LiquidRenderError):
        Liquid(f"{{% include {HERE}/templates/include1.liq %}}{{{{x}}}}"
               ).render()

    with pytest.raises(LiquidSyntaxError):
        Liquid(f"{{% include {HERE}/templates/include1.liq , %}}").render()

    with pytest.raises(LiquidSyntaxError):
        Liquid(f"{{% include {HERE}/templates/include1.liq 9 %}}").render()
Beispiel #23
0
def test_emptydrop(set_default_standard):
    assert Liquid("{{ obj | sort_natural}}").render(obj=[]) == ""
    assert (
        Liquid("{{ obj | sort | bool}}", mode="wild").render(obj=[]) == "False"
    )
    assert (
        Liquid("{{ slice(obj, 0) == False}}", mode="wild").render(obj=[])
        == "True"
    )
    assert (
        Liquid("{{ uniq(obj) != False}}", mode="wild").render(obj=[])
        == "False"
    )
Beispiel #24
0
def test_extends():
    with pytest.raises(LiquidSyntaxError):
        liq = Liquid("{% extends %}")

    with pytest.raises(LiquidSyntaxError) as exc:
        liq = Liquid(
            f"{{% extends {HERE}/templates/extends.liq %}}{{%extends {HERE}/templates/extends.liq%}}"
        )
    assert "Only one 'extends' node allowed" in str(exc.value)

    # File not exists
    with pytest.raises(LiquidSyntaxError) as exc:
        liq = Liquid(f"{{% extends {HERE}/templates %}}")
Beispiel #25
0
def test_unless():
    tpl = """
    {% unless product.title == "Awesome Shoes" %}
      These shoes are not awesome.
    {% endunless %}
    """
    assert Liquid(tpl).render(product={
        "title": "Not Awesome Shoes"
    }).strip() == "These shoes are not awesome."

    assert Liquid('{% unless "" %}1{% endunless %}').render() == ""
    assert Liquid('{% unless 0.0 %}1{% endunless %}').render() == ""
    assert Liquid('{% unless empty %}1{% endunless %}').render() == "1"
Beispiel #26
0
def test_xcrement(set_default_standard):
    tpl = """
    {% increment my_counter %}
    {% increment my_counter %}
    {% increment my_counter %}
    """
    assert Liquid(tpl).render().split() == ["0", "1", "2"]

    tpl = """
    {% decrement my_counter %}
    {% decrement my_counter %}
    {% decrement my_counter %}
    """
    assert Liquid(tpl).render().split() == ["-1", "-2", "-3"]
Beispiel #27
0
def test_include(debug_on):
    liquid = Liquid("""{{% mode compact %}}
    {{% assign x = x + 1 %}}
    {{% include {}/templates/include1.liq x %}}
    {{{{x}}}}
    """.format(HERE),
                    liquid_loglevel='debug')
    assert liquid.render(x=1) == '82'

    with pytest.raises(LiquidSyntaxError):
        # include self
        Liquid(from_file=HERE.joinpath('templates', 'include2.liq'))

    with pytest.raises(LiquidSyntaxError):  # not exists
        Liquid('{% include xxx.liquid %}')
Beispiel #28
0
def test_comment_with_prefix(set_default_standard):
    tpl = """{% comment "#" %}
    a
    b
    {%endcomment%}
    """
    Liquid(tpl).render() == """# a\n# b\n"""
Beispiel #29
0
def test_number_of_words(sen, mode, out, set_default_jekyll):
    if mode is None:
        template = f"{{{{ {sen!r} | number_of_words }}}}"
    else:
        template = f"{{{{ {sen!r} | number_of_words: {mode!r} }}}}"

    assert Liquid(template).render() == str(out)
Beispiel #30
0
def render_md(books):
    # load template from a file
    liq = Liquid('template/README.template.md', liquid_from_file=True)
    md = liq.render(books=books)

    with open("README.md", 'w') as f:
        f.write(md)