File: test_basic.py

package info (click to toggle)
python-minijinja 2.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 468 kB
  • sloc: python: 723; makefile: 40; sh: 31
file content (536 lines) | stat: -rw-r--r-- 14,743 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
import binascii
import pytest
import posixpath
import random
import types
import sys
from functools import total_ordering

from minijinja import (
    Environment,
    TemplateError,
    safe,
    pass_state,
    eval_expr,
    render_str,
    load_from_path,
)


class catch_unraisable_exception:
    def __init__(self) -> None:
        self.unraisable = None
        self._old_hook = None

    def _hook(self, unraisable):
        self.unraisable = unraisable

    def __enter__(self):
        self._old_hook = sys.unraisablehook
        sys.unraisablehook = self._hook
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        assert self._old_hook is not None
        sys.unraisablehook = self._old_hook
        self._old_hook = None
        del self.unraisable


def test_expression():
    env = Environment()
    rv = env.eval_expr("1 + b", b=42)
    assert rv == 43
    rv = env.eval_expr("range(n)", n=10)
    assert rv == list(range(10))


def test_pass_callable():
    def magic():
        return [1, 2, 3]

    env = Environment()
    rv = env.eval_expr("x()", x=magic)
    assert rv == [1, 2, 3]


def test_callable_attrs():
    def hmm():
        pass

    hmm.public_attr = 42
    env = Environment()
    rv = env.eval_expr("[hmm.public_attr, hmm.__module__]", hmm=hmm)
    assert rv == [42, None]


def test_generator():
    def hmm():
        yield 1
        yield 2
        yield 3

    hmm.public_attr = 42
    env = Environment()
    rv = env.eval_expr("values", values=hmm())
    assert isinstance(rv, types.GeneratorType)

    rv = env.eval_expr("values|list", values=hmm())
    assert rv == [1, 2, 3]


def test_method_calling():
    class MyClass(object):
        def my_method(self):
            return 23

        def __repr__(self):
            return "This is X"

    env = Environment()
    rv = env.eval_expr("[x ~ '', x.my_method()]", x=MyClass())
    assert rv == ["This is X", 23]
    rv = env.eval_expr("x.items()|list", x={"a": "b"})
    assert rv == [("a", "b")]


def test_types_passthrough():
    tup = (1, 2, 3)
    assert eval_expr("x", x=tup) == tup
    assert render_str("{{ x }}", x=tup) == "(1, 2, 3)"
    assert eval_expr("x is sequence", x=tup) == True
    assert render_str("{{ x }}", x=(1, True)) == "(1, True)"
    assert eval_expr("x[0] == 42", x=[42]) == True


def test_custom_filter():
    def my_filter(value):
        return "<%s>" % value.upper()

    env = Environment()
    env.add_filter("myfilter", my_filter)
    rv = env.eval_expr("'hello'|myfilter")
    assert rv == "<HELLO>"


def test_custom_filter_kwargs():
    def my_filter(value, x):
        return "<%s %s>" % (value.upper(), x)

    env = Environment()
    env.add_filter("myfilter", my_filter)
    rv = env.eval_expr("'hello'|myfilter(x=42)")
    assert rv == "<HELLO 42>"


def test_custom_test():
    def my_test(value, arg):
        return value == arg

    env = Environment()
    env.add_filter("mytest", my_test)
    rv = env.eval_expr("'hello'|mytest(arg='hello')")
    assert rv == True
    rv = env.eval_expr("'hello'|mytest(arg='hellox')")
    assert rv == False


def test_basic_types():
    env = Environment()
    rv = env.eval_expr("{'a': 42, 'b': 42.5, 'c': 'blah'}")
    assert rv == {"a": 42, "b": 42.5, "c": "blah"}


def test_loader():
    called = []

    def my_loader(name):
        called.append(name)
        return "Hello from " + name

    env = Environment(loader=my_loader)
    assert env.render_template("index.html") == "Hello from index.html"
    assert env.render_template("index.html") == "Hello from index.html"
    assert env.render_template("other.html") == "Hello from other.html"
    assert env.loader is my_loader
    assert called == ["index.html", "other.html"]
    env.loader = my_loader
    assert env.render_template("index.html") == "Hello from index.html"
    assert called == ["index.html", "other.html"]
    env.reload()
    assert env.render_template("index.html") == "Hello from index.html"
    assert called == ["index.html", "other.html", "index.html"]


def test_loader_reload():
    called = []

    def my_loader(name):
        called.append(name)
        return "Hello from " + name

    env = Environment(loader=my_loader)
    env.reload_before_render = True
    assert env.render_template("index.html") == "Hello from index.html"
    assert env.render_template("index.html") == "Hello from index.html"
    assert env.render_template("other.html") == "Hello from other.html"
    assert called == ["index.html", "index.html", "other.html"]


def test_autoescape():
    assert Environment().auto_escape_callback is None

    def auto_escape(name):
        assert name == "foo.html"
        return "html"

    env = Environment(
        auto_escape_callback=auto_escape,
        loader=lambda x: "Hello {{ foo }}",
    )
    assert env.auto_escape_callback is auto_escape

    rv = env.render_template("foo.html", foo="<x>")
    assert rv == "Hello &lt;x&gt;"

    with catch_unraisable_exception() as cm:
        rv = env.render_template("invalid.html", foo="<x>")
        assert rv == "Hello <x>"
        assert cm.unraisable[0] is AssertionError


def test_finalizer():
    assert Environment().finalizer is None

    @pass_state
    def my_finalizer(state, value):
        assert state.name == "<string>"
        if value is None:
            return ""
        elif isinstance(value, bytes):
            return binascii.b2a_hex(value).decode("utf-8")
        return NotImplemented

    env = Environment(finalizer=my_finalizer)

    rv = env.render_str("[{{ foo }}]")
    assert rv == "[]"
    rv = env.render_str("[{{ foo }}]", foo=None)
    assert rv == "[]"
    rv = env.render_str("[{{ foo }}]", foo="test")
    assert rv == "[test]"
    rv = env.render_str("[{{ foo }}]", foo=b"test")
    assert rv == "[74657374]"

    def raising_finalizer(value):
        1 / 0

    env = Environment(finalizer=raising_finalizer)

    with pytest.raises(ZeroDivisionError):
        env.render_str("{{ whatever }}")


def test_globals():
    env = Environment(globals={"x": 23, "y": lambda: 42})
    rv = env.eval_expr("[x, y(), z]", z=11)
    assert rv == [23, 42, 11]


def test_honor_safe():
    env = Environment(auto_escape_callback=lambda x: True)
    rv = env.render_str("{{ x }} {{ y }}", x=safe("<foo>"), y="<bar>")
    assert rv == "<foo> &lt;bar&gt;"


def test_full_object_transfer():
    class X(object):
        def __init__(self):
            self.x = 1
            self.y = 2

    def test_filter(value):
        assert isinstance(value, X)
        return value

    env = Environment(filters=dict(testfilter=test_filter))
    rv = env.eval_expr("x|testfilter", x=X())
    assert isinstance(rv, X)
    assert rv.x == 1
    assert rv.y == 2


def test_markup_transfer():
    env = Environment()
    rv = env.eval_expr("value", value=safe("<foo>"))
    assert hasattr(rv, "__html__")
    assert rv.__html__() == "<foo>"

    rv = env.eval_expr("'<test>'|escape")
    assert hasattr(rv, "__html__")
    assert rv.__html__() == "&lt;test&gt;"


def test_error():
    env = Environment()
    try:
        env.eval_expr("1 +")
    except TemplateError as e:
        assert e.name == "<expression>"
        assert "unexpected end of input" in e.message
        assert "1 > 1 +" not in e.message
        assert "1 > 1 +" in str(e)
        assert e.line == 1
        assert e.kind == "SyntaxError"
        assert e.range == (2, 3)
        assert e.template_source == "1 +"
        assert "unexpected end of input" in e.detail
    else:
        assert False, "expected error"


def test_custom_syntax():
    env = Environment(
        block_start_string="[%",
        block_end_string="%]",
        variable_start_string="{",
        variable_end_string="}",
        comment_start_string="/*",
        comment_end_string="*/",
    )
    rv = env.render_str("[% if true %]{value}[% endif %]/* nothing */", value=42)
    assert rv == "42"


def test_path_join():
    def join_path(name, parent):
        return posixpath.join(posixpath.dirname(parent), name)

    env = Environment(
        path_join_callback=join_path,
        templates={
            "foo/bar.txt": "{% include 'baz.txt' %}",
            "foo/baz.txt": "I am baz!",
        },
    )

    with catch_unraisable_exception() as cm:
        rv = env.render_template("foo/bar.txt")
        assert rv == "I am baz!"
        assert cm.unraisable is None


def test_keep_trailing_newline():
    env = Environment(keep_trailing_newline=False)
    assert env.render_str("foo\n") == "foo"
    env = Environment(keep_trailing_newline=True)
    assert env.render_str("foo\n") == "foo\n"


def test_trim_blocks():
    env = Environment(trim_blocks=False)
    assert env.render_str("{% if true %}\nfoo{% endif %}") == "\nfoo"
    env = Environment(trim_blocks=True)
    assert env.render_str("{% if true %}\nfoo{% endif %}") == "foo"


def test_lstrip_blocks():
    env = Environment(lstrip_blocks=False)
    assert env.render_str("  {% if true %}\nfoo{% endif %}") == "  \nfoo"
    env = Environment(lstrip_blocks=True)
    assert env.render_str("  {% if true %}\nfoo{% endif %}") == "\nfoo"


def test_trim_and_lstrip_blocks():
    env = Environment(lstrip_blocks=False, trim_blocks=False)
    assert env.render_str("  {% if true %}\nfoo{% endif %}") == "  \nfoo"
    env = Environment(lstrip_blocks=True, trim_blocks=True)
    assert env.render_str("  {% if true %}\nfoo{% endif %}") == "foo"


def test_line_statements():
    env = Environment()
    assert env.line_statement_prefix is None
    assert env.line_comment_prefix is None

    env = Environment(line_statement_prefix="#", line_comment_prefix="##")
    assert env.line_statement_prefix == "#"
    assert env.line_comment_prefix == "##"

    rv = env.render_str("# for x in range(3)\n{{ x }}\n# endfor")
    assert rv == "0\n1\n2\n"


def test_custom_delimiters():
    env = Environment(
        variable_start_string="${",
        variable_end_string="}",
        block_start_string="<%",
        block_end_string="%>",
        comment_start_string="<!--",
        comment_end_string="-->",
    )
    rv = env.render_str("<% if true %>${ value }<% endif %><!-- nothing -->", value=42)
    assert rv == "42"


def test_undeclared_variables():
    env = Environment(
        templates={
            "foo.txt": "{{ foo }} {{ bar.x }}",
            "bar.txt": "{{ x }}",
        }
    )

    assert env.undeclared_variables_in_str("{{ foo }}") == {"foo"}
    assert env.undeclared_variables_in_str("{{ foo }} {{ bar.x }}") == {"foo", "bar"}
    assert env.undeclared_variables_in_str("{{ foo }} {{ bar.x }}", nested=True) == {
        "foo",
        "bar.x",
    }

    assert env.undeclared_variables_in_template("foo.txt") == {"foo", "bar"}
    assert env.undeclared_variables_in_template("bar.txt") == {"x"}
    assert env.undeclared_variables_in_template("foo.txt", nested=True) == {
        "foo",
        "bar.x",
    }


def test_loop_controls():
    env = Environment()
    rv = env.render_str("""
    {% for x in [1, 2, 3, 4, 5] %}
      {% if x == 1 %}
        {% continue %}
      {% elif x == 3 %}
        {% break %}
      {% endif %}
      {{ x }}
    {% endfor %}
    """)
    assert rv.split() == ["2"]


def test_pass_through_sort():
    @total_ordering
    class X(object):
        def __init__(self, value):
            self.value = value

        def __eq__(self, other):
            if type(self) is not type(other):
                return NotImplemented
            return self.value == other.value

        def __lt__(self, other):
            if type(self) is not type(other):
                return NotImplemented
            return self.value < other.value

        def __str__(self):
            return str(self.value)

    values = [X(4), X(23), X(42), X(-1)]
    env = Environment()
    rv = env.render_str("{{ values|sort|join(',') }}", values=values)
    assert rv == "-1,4,23,42"


def test_fucked_up_object():
    @total_ordering
    class X:
        __lt__ = __eq__ = lambda s, o: random.random() > 0.5

    values = [X()] * 500
    env = Environment()
    with pytest.raises(
        TemplateError,
        match="invalid operation: failed to sort: user-provided comparison function does not correctly implement a total order",
    ):
        env.eval_expr("values|sort", values=values)


def test_threading_interactions():
    from time import time
    from concurrent.futures import ThreadPoolExecutor

    done = []

    def busy_wait(value, seconds: float):
        start = time()
        while time() - start < seconds:
            continue
        done.append(value)
        return value

    env = Environment(filters={"busy_wait": busy_wait})
    executor = ThreadPoolExecutor()

    for _ in range(4):
        executor.submit(lambda: env.render_str("{{ 'something' | busy_wait(0.1) }}"))

    executor.shutdown(wait=True)
    assert done == ["something"] * 4


def test_truthy():
    class Custom:
        def __init__(self, is_true):
            self.is_true = is_true

        def __bool__(self):
            return bool(self.is_true)

    env = Environment()
    assert env.eval_expr("x|bool", x=Custom(True)) is True
    assert env.eval_expr("x|bool", x=Custom(False)) is False
    assert env.eval_expr("x|bool", x=Custom(None)) is False
    assert env.eval_expr("x|bool", x=Custom("")) is False
    assert env.eval_expr("x|bool", x=Custom("foo")) is True

    class Fallback:
        def __bool__(self):
            raise RuntimeError("swallowed but true")

    assert env.eval_expr("x|bool", x=Fallback()) is True


def test_load_from_path():
    env = Environment(loader=load_from_path("tests/templates"))
    rv = env.render_template("base.txt", woot="woot")
    assert rv.strip() == "I am from foo! woot!"

    with pytest.raises(TemplateError) as e:
        env.render_template("missing.txt")
    assert e.value.kind == "TemplateNotFound"

    with pytest.raises(TemplateError) as e:
        env.render_template("../test_basic.py")
    assert e.value.kind == "TemplateNotFound"


def test_pycompat():
    env = Environment()
    assert env.eval_expr("{'x': 42}.get('x')") == 42

    env.pycompat = False
    with pytest.raises(TemplateError) as e:
        assert env.eval_expr("{'x': 42}.get('x')")
    assert "unknown method: map has no method named get" in e.value.message


def test_striptags():
    env = Environment()
    assert env.eval_expr("'<a>foo</a>'|striptags") == "foo"
    assert env.eval_expr("'<a>&auml;</a>'|striptags") == "รค"


def test_attribute_lookups():
    class X:
        def __getattr__(self, _):
            raise RuntimeError('boom')

    env = Environment()
    with pytest.raises(RuntimeError, match="boom"):
        env.eval_expr("x.foo", x=X())