Debian Codegraph @

test/units/_internal/templating/test_lazy_containers.py

raw
1 # DTFIX5: more thorough tests are needed here, this is just a starting point
2
3 from __future__ import annotations
4
5 import collections.abc as c
6 import copy
7 import re
8 import sys
9 import typing as t
10
11 import pytest
12
13 from ansible.errors import AnsibleTemplateError, AnsibleUndefinedVariable
14 from ansible._internal._templating._jinja_bits import is_possibly_template
15 from ansible._internal._templating._jinja_common import CapturedExceptionMarker, MarkerError, JinjaCallContext, Marker
16 from ansible._internal._datatag._tags import Origin, TrustedAsTemplate
17 from ansible._internal._templating._utils import TemplateContext, LazyOptions
18 from ansible._internal._templating._engine import TemplateEngine, TemplateOptions
19 from ansible._internal._templating._lazy_containers import _AnsibleLazyTemplateMixin, _AnsibleLazyTemplateList, _AnsibleLazyTemplateDict, _LazyValue, \
20 _AnsibleLazyAccessTuple, UnsupportedConstructionMethodError
21 from ansible.module_utils._internal._datatag import AnsibleTaggedObject
22
23 from ...module_utils.datatag.test_datatag import ExampleSingletonTag
24 from ...test_utils.controller.display import emits_warnings
25
26 TRUST = TrustedAsTemplate()
27
28 VALUE_TO_TEMPLATE = TRUST.tag("{{ 'hello' | default('goodbye') }}")
29
30 CONTAINER_VALUES = (
31 dict(hello=VALUE_TO_TEMPLATE),
32 [VALUE_TO_TEMPLATE],
33 )
34
35
36 @pytest.mark.parametrize("value", CONTAINER_VALUES, ids=[type(value).__name__ for value in CONTAINER_VALUES])
37 def test_container_equality(value: t.Any) -> None:
38 templar = TemplateEngine()
39
40 rendered = templar.template(value)
41
42 with TemplateContext(template_value=None, templar=templar, options=TemplateOptions(), stop_on_template=False):
43 # NOTE: Assertion failure helper text may be misleading, since repr() will show rendered templates, which will appear to match expected values.
44
45 lazy = _AnsibleLazyTemplateMixin._try_create(value)
46
47 assert lazy == lazy # pylint: disable=comparison-with-itself
48
49 assert lazy == rendered
50 assert rendered == lazy
51
52 assert lazy != value
53 assert value != lazy
54
55
56 @pytest.mark.parametrize("value", CONTAINER_VALUES, ids=[type(value).__name__ for value in CONTAINER_VALUES])
57 def test_container_format(value: t.Any) -> None:
58 templar = TemplateEngine()
59
60 rendered = templar.template(value)
61
62 with TemplateContext(template_value=None, templar=templar, options=TemplateOptions(), stop_on_template=False):
63 # NOTE: Assertion failure helper text may be misleading, since repr() will show rendered templates, which will appear to match expected values.
64
65 lazy = _AnsibleLazyTemplateMixin._try_create(value)
66
67 assert "{0}".format(lazy) == "{0}".format(rendered)
68
69
70 @pytest.mark.parametrize("container_type", (
71 list,
72 ))
73 def test_container_contains(container_type: type) -> None:
74 templar = TemplateEngine()
75
76 # including default('goodbye') as canary for flattening to a string
77 value = container_type([VALUE_TO_TEMPLATE])
78 rendered = templar.template(value)
79
80 with TemplateContext(template_value=None, templar=templar, options=TemplateOptions(), stop_on_template=False):
81 # NOTE: Assertion failure helper text may be misleading, since repr() will show rendered templates, which will appear to match expected values.
82
83 lazy = _AnsibleLazyTemplateMixin._try_create(value)
84
85 for src in (lazy, rendered):
86 assert 'hello' in src
87 assert 'goodbye' not in src
88
89
90 @pytest.mark.parametrize("container_type", (
91 list,
92 # no need to test a tuple, it's just converted to a list
93 ))
94 def test_container_comparison(container_type: type) -> None:
95 templar = TemplateEngine()
96
97 # including default('goodbye') as canary for flattening to a string
98 value = container_type([VALUE_TO_TEMPLATE])
99 rendered = templar.template(value)
100
101 with TemplateContext(template_value=None, templar=templar, options=TemplateOptions(), stop_on_template=False):
102 # NOTE: Assertion failure helper text may be misleading, since repr() will show rendered templates, which will appear to match expected values.
103
104 lazy = _AnsibleLazyTemplateMixin._try_create(value)
105
106 assert value > rendered
107 assert not (lazy > rendered) # pylint: disable=unnecessary-negation
108
109 assert value >= rendered
110 assert lazy >= rendered
111
112 assert rendered < value
113 assert not (rendered < lazy) # pylint: disable=unnecessary-negation
114
115 assert rendered <= value
116 assert rendered <= lazy
117
118
119 def test_list_sort() -> None:
120 templar = TemplateEngine()
121
122 with TemplateContext(template_value=None, templar=templar, options=TemplateOptions(), stop_on_template=False):
123 lazy: list = _AnsibleLazyTemplateMixin._try_create([TRUST.tag('{{ 2 }}'), TRUST.tag('{{ 1 }}')])
124 lazy.sort()
125
126 assert lazy == [1, 2]
127
128
129 def test_list_index() -> None:
130 templar = TemplateEngine()
131
132 rendered = templar.template(VALUE_TO_TEMPLATE)
133
134 with TemplateContext(template_value=None, templar=templar, options=TemplateOptions(), stop_on_template=False):
135 lazy: list = _AnsibleLazyTemplateMixin._try_create([VALUE_TO_TEMPLATE])
136
137 assert lazy.index(rendered) == 0
138
139
140 def test_list_remove() -> None:
141 templar = TemplateEngine()
142
143 rendered = templar.template(VALUE_TO_TEMPLATE)
144
145 with TemplateContext(template_value=None, templar=templar, options=TemplateOptions(), stop_on_template=False):
146 lazy: list = _AnsibleLazyTemplateMixin._try_create([VALUE_TO_TEMPLATE])
147
148 assert rendered in lazy
149
150 lazy.remove(rendered)
151
152 assert lazy == []
153
154
155 def test_dict_get_with_default(template_context) -> None:
156 """Ensure getting a default value does not result in templating or storage of the default."""
157 my_dict = _AnsibleLazyTemplateMixin._try_create({})
158 value = TrustedAsTemplate().tag("{{ 1 }}")
159
160 my_dict['x'] = TrustedAsTemplate().tag("{{ 2 }}")
161
162 result = my_dict.get('a', value)
163
164 assert result is value
165 assert 'a' not in my_dict
166
167
168 def test_dict_setdefault(template_context) -> None:
169 """Ensure that setdefault templates existing values, but not defaults."""
170 my_dict = _AnsibleLazyTemplateMixin._try_create(dict(invalid_template=TRUST.tag("{{ 1/0 }}"), valid_template=TRUST.tag("{{ 1 }}")))
171 value_for_default = TrustedAsTemplate().tag("{{ 'default' }}")
172
173 assert my_dict.setdefault('valid_template') == 1
174 assert my_dict.setdefault('valid_template', value_for_default) == 1
175 assert my_dict.setdefault('nonexistent_key', value_for_default) is value_for_default
176
177 result = my_dict.setdefault('invalid_template', value_for_default)
178 assert isinstance(result, CapturedExceptionMarker)
179 assert isinstance(result._marker_captured_exception, AnsibleTemplateError)
180
181 # repeat to ensure we didn't record any change
182 result = my_dict.setdefault('invalid_template', value_for_default)
183 assert isinstance(result, CapturedExceptionMarker)
184 assert isinstance(result._marker_captured_exception, AnsibleTemplateError)
185
186
187 def test_dict_pop(template_context) -> None:
188 """Ensure that pop does not template or store its default, and that templating occurs before the collection is mutated."""
189 my_dict = _AnsibleLazyTemplateMixin._try_create(dict(busted_template=TRUST.tag("{{ 1 / 0 }}")))
190 value_for_default = TRUST.tag("{{ 1 }}")
191
192 result = my_dict.pop("boguskey", value_for_default)
193
194 assert result is value_for_default
195 assert "boguskey" not in my_dict
196
197 with JinjaCallContext(accept_lazy_markers=False):
198 with pytest.raises(MarkerError):
199 my_dict.pop('busted_template')
200
201 assert 'busted_template' in my_dict
202
203 result = my_dict.pop('busted_template')
204
205 assert isinstance(result, CapturedExceptionMarker)
206 assert isinstance(result._marker_captured_exception, AnsibleTemplateError)
207
208 assert 'busted_template' not in my_dict
209
210
211 def test_dict_popitem(template_context):
212 """Ensure popitem respects insertion order, templating of values, and that templating occurs before the collection is mutated."""
213 my_dict = _AnsibleLazyTemplateMixin._try_create(dict(
214 also_valid_template=TRUST.tag("{{ 0 }}"),
215 busted_template=TRUST.tag("{{ 1 / 0 }}"),
216 valid_template=TRUST.tag("{{ 1 }}"),
217 ))
218
219 assert my_dict.popitem() == ('valid_template', 1)
220
221 with JinjaCallContext(accept_lazy_markers=False):
222 with pytest.raises(MarkerError):
223 my_dict.popitem()
224
225 assert 'busted_template' in my_dict
226
227 raw_result = my_dict.popitem()
228
229 assert isinstance(raw_result, tuple)
230
231 key, result = raw_result
232
233 assert key == 'busted_template'
234 assert isinstance(result, CapturedExceptionMarker)
235 assert isinstance(result._marker_captured_exception, AnsibleTemplateError)
236
237 assert my_dict.popitem() == ('also_valid_template', 0)
238
239 with pytest.raises(KeyError):
240 my_dict.popitem()
241
242
243 @pytest.mark.parametrize("native_value, expression", (
244 ({}, 'obj.popitem()'),
245 ([], 'obj.pop()'),
246 ({}, 'obj.pop("missing")'),
247 ([], 'obj.pop(1)'),
248 ))
249 def test_get_errors(template_context, native_value: object, expression: str) -> None:
250 """Verify getting a value from a lazy container fails the same as the native container when the requested key/index is missing or the container is empty."""
251 lazy_value = _AnsibleLazyTemplateMixin._try_create(native_value)
252
253 with pytest.raises(Exception) as native_error:
254 eval(expression, dict(obj=native_value))
255
256 with pytest.raises(type(native_error.value), match=f'^{re.escape(str(native_error.value))}$'):
257 eval(expression, dict(obj=lazy_value))
258
259
260 def test_dict_items_and_values() -> None:
261 templar = TemplateEngine()
262
263 value = dict(key=VALUE_TO_TEMPLATE)
264 rendered = templar.template(value)
265
266 with TemplateContext(template_value=None, templar=templar, options=TemplateOptions(), stop_on_template=False):
267 lazy: dict = _AnsibleLazyTemplateMixin._try_create(value)
268
269 assert list(lazy.items()) == list(rendered.items())
270 assert list(lazy.values()) == list(rendered.values())
271
272
273 @pytest.mark.parametrize("template, variables, expected", [
274 ("{{ (d1 | items) + (d2 | items) }}", dict(d1=dict(a=1), d2=dict(b=2)), [['a', 1], ['b', 2]]),
275 ("{{ (d1 | items) + [('c', 3)] }}", dict(d1=dict(a=1)), [['a', 1], ['c', 3]]),
276 ("{{ [('c', 3)] + (d1 | items) }}", dict(d1=dict(a=1)), [['c', 3], ['a', 1]]),
277 ("{{ (d1 | items) * 2 }}", dict(d1=dict(a=1)), [['a', 1], ['a', 1]]),
278 ("{{ 2 * (d1 | items) }}", dict(d1=dict(a=1)), [['a', 1], ['a', 1]]),
279 ("{{ (1, 2) }}", dict(), [1, 2]),
280 ])
281 def test_lazy_list_adapter_operators(template, variables, expected) -> None:
282 templar = TemplateEngine(variables=variables)
283
284 assert templar.template(TRUST.tag(template)) == expected
285
286
287 @pytest.mark.parametrize("expression, expected_value, expected_type", [
288 ("l1 + l2", [_LazyValue(1), _LazyValue(2)], _AnsibleLazyTemplateList), # __add__
289 ("l1 + l2f()", [1, 2], list), # __add__ (different lazy options)
290 ("l1 + [2]", [_LazyValue(1), 2], _AnsibleLazyTemplateList), # __add__
291 ("[1] + l2", [1, _LazyValue(2)], _AnsibleLazyTemplateList), # __radd__
292 ("l1 * 3", [_LazyValue(1), _LazyValue(1), _LazyValue(1)], _AnsibleLazyTemplateList), # __mul__
293 ("3 * l2", [_LazyValue(2), _LazyValue(2), _LazyValue(2)], _AnsibleLazyTemplateList), # __rmul__
294 ("d1 | d2", dict(a=1, b=2, c=2), dict), # __or__
295 ("d1 | {'b': 2, 'c': 2}", dict(a=1, b=2, c=2), dict), # __or__
296 ("{'a': 1} | d2", dict(a=1, b=2, c=2), dict), # __ror__
297 ("d1 |= d2", dict(d1=dict(a=_LazyValue(1), b=2, c=2)), _AnsibleLazyTemplateDict), # __ior__
298 ("d1 |= {'b': 2, 'c': 2}", dict(d1=dict(a=_LazyValue(1), b=2, c=2)), _AnsibleLazyTemplateDict), # __ior__
299 ('d1.copy()', dict(a=_LazyValue(1), c=_LazyValue(1)), _AnsibleLazyTemplateDict), # _AnsibleLazyTemplateDict.copy
300 ('type(d1)(d1)', dict(a=_LazyValue(1), c=_LazyValue(1)), _AnsibleLazyTemplateDict), # _AnsibleLazyTemplateDict.__init__ copy
301 ('l1.copy()', [_LazyValue(1)], _AnsibleLazyTemplateList), # _AnsibleLazyTemplateList.copy
302 ('type(l1)(l1)', [_LazyValue(1)], _AnsibleLazyTemplateList), # _AnsibleLazyTemplateList.__init__ copy
303 ('type(t1)(t1)', (1,), _AnsibleLazyAccessTuple),
304 ('copy.copy(l1)', [_LazyValue(1)], _AnsibleLazyTemplateList),
305 ('copy.copy(d1)', dict(a=_LazyValue(1), c=_LazyValue(1)), _AnsibleLazyTemplateDict),
306 ('copy.deepcopy(l1)', [_LazyValue(1)], _AnsibleLazyTemplateList), # __AnsibleLazyTemplateList.__deepcopy__
307 ('copy.deepcopy(d1)', dict(a=_LazyValue(1), c=_LazyValue(1)), _AnsibleLazyTemplateDict), # __AnsibleLazyTemplateDict.__deepcopy__
308 ('ExampleSingletonTag().tag(l1)', [_LazyValue(1)], _AnsibleLazyTemplateList),
309 ('ExampleSingletonTag().tag(d1)', dict(a=_LazyValue(1), c=_LazyValue(1)), _AnsibleLazyTemplateDict),
310 ('list(reversed(l1))', [1], list), # _AnsibleLazyTemplateList.__reversed__
311 ('list(reversed(d1))', ['c', 'a'], list), # dict.__reversed__ - keys only
312 ('l1[:]', [_LazyValue(1)], _AnsibleLazyTemplateList), # __getitem__ (slice)
313 ('t1[:]', (1,), _AnsibleLazyAccessTuple), # __getitem__ (slice)
314 ('d1["a"]', 1, int), # __getitem__
315 ('d1.get("a")', 1, int), # get
316 ('l1[0]', 1, int), # __getitem__
317 ('d1.pop("a")', 1, int), # dict.pop (check returned value)
318 ('d1.pop("a");', dict(d1=dict(c=_LazyValue(1))), _AnsibleLazyTemplateDict), # dict.pop (check mutated source)
319 ('list(d1.items())', [('a', 1), ('c', 1)], list), # items
320 ('d1.popitem()', ('c', 1), tuple), # dict.popitem (check returned value)
321 ('d1.popitem();', dict(d1=dict(a=_LazyValue(1))), _AnsibleLazyTemplateDict), # dict.popitem (check mutated source)
322 ('d1.clear(); d1["d"] = 4', dict(d1=dict(d=4)), _AnsibleLazyTemplateDict), # dict.clear (clear + mutate)
323 ('d1["d"] = 4; d1.clear()', dict(d1=dict()), _AnsibleLazyTemplateDict), # dict.clear (mutate + clear)
324 ('d1.update(d2);', dict(d1=dict(a=_LazyValue(1), b=2, c=2)), _AnsibleLazyTemplateDict), # dict.update
325 ('d1.setdefault("d", 4)', 4, int), # dict.setdefault (return value check only)
326 ('d1.setdefault("d", 4);', dict(d1=dict(a=_LazyValue(1), c=_LazyValue(1), d=4)), _AnsibleLazyTemplateDict), # dict.setdefault
327 ('l1.clear(); l1.append(4)', dict(l1=[4]), _AnsibleLazyTemplateList), # list.clear (clear + mutate)
328 ('l1.append(4); l1.clear()', dict(l1=[]), _AnsibleLazyTemplateList), # list.clear (mutate + clear)
329 ('l1.pop()', 1, int), # list.pop (check returned value)
330 ('l1.pop();', dict(l1=[]), _AnsibleLazyTemplateList), # list.pop (check returned value)
331 ('l1.insert(0, 4);', dict(l1=[4, _LazyValue(1)]), _AnsibleLazyTemplateList), # list.insert (check mutated source)
332 ('l1.extend(l2);', dict(l1=[_LazyValue(1), 2]), _AnsibleLazyTemplateList), # list.extend (check mutated source)
333 ('l1[0] = 2;', dict(l1=[2]), _AnsibleLazyTemplateList), # list.__setitem__ (check mutated source)
334 ('l1 > [1]', False, bool), # __gt__ (lazy vs constant)
335 ('l1 > l1x', False, bool), # __gt__ (lazy vs lazy)
336 ('l1 >= [1]', True, bool), # __ge__ (lazy vs constant)
337 ('l1 >= l1x', True, bool), # __ge__ (lazy vs lazy)
338 ('l1 < [1]', False, bool), # __lt__ (lazy vs constant)
339 ('l1 < l1x', False, bool), # __lt__ (lazy vs lazy)
340 ('l1 <= [1]', True, bool), # __le__ (lazy vs constant)
341 ('l1 <= l1x', True, bool), # __le__ (lazy vs lazy)
342 ('l1 == [1]', True, bool), # __eq__ (lazy vs constant)
343 ('l1 == l1x', True, bool), # __eq__ (lazy vs lazy)
344 ('l1 != [1]', False, bool), # __ne__ (lazy vs constant)
345 ('l1 != l1x', False, bool), # __ne__ (lazy vs lazy)
346 ('d1 == {"a": 1, "c": 1}', True, bool), # __eq__ (lazy vs constant)
347 ('d1 == d1x', True, bool), # __eq__ (lazy vs lazy)
348 ('d1 != {"a": 1, "c": 1}', False, bool), # __ne__ (lazy vs constant)
349 ('d1 != d1x', False, bool), # __eq__ (lazy vs lazy)
350 ('1 in l1', True, bool), # __contains__
351 ('str(d1)', str(dict(a=1, c=1)), str), # __str__
352 ('str(l1)', str([1]), str), # __str__
353 ('repr(d1)', repr(dict(a=1, c=1)), str), # __repr__
354 ('repr(l1)', repr([1]), str), # __repr__
355 ('"{}".format(l1)', repr([1]), str), # __format__ [no override required]
356 ('list(l1)', [1], list), # _AnsibleLazyTemplateList.__iter__
357 ('list(d1)', ['a', 'c'], list), # _AnsibleLazyTemplateDict.__iter__
358 ('l1._native_copy()', [1], list), # native_copy
359 ('dict(d1)', dict(a=1, c=1), dict), # __iter__
360 ('d1._native_copy()', dict(a=1, c=1), dict), # native_copy
361 ('{} + l1', "unsupported operand type(s) for +: 'dict' and '_AnsibleLazyTemplateList'", TypeError), # __radd__
362 ('d1 + l1', "unsupported operand type(s) for +: '_AnsibleLazyTemplateDict' and '_AnsibleLazyTemplateList'", TypeError), # __radd__
363 ('d1 + []', "unsupported operand type(s) for +: '_AnsibleLazyTemplateDict' and 'list'", TypeError), # python operator dispatch
364 ('set() + l1', "unsupported operand type(s) for +: 'set' and '_AnsibleLazyTemplateList'", TypeError), # python operator dispatch
365 ('set() + d1', "unsupported operand type(s) for +: 'set' and '_AnsibleLazyTemplateDict'", TypeError), # python operator dispatch
366 ('l1 + {}', 'can only concatenate list (not "dict") to list', TypeError), # __add__ (relies on list.__add__)
367 ('l1 + set()', 'can only concatenate list (not "set") to list', TypeError), # __add__ (relies on list.__add__)
368 ('l1 + tuple()', 'can only concatenate list (not "tuple") to list', TypeError), # __add__ (relies on list.__add__)
369 ('tuple() + l1', 'can only concatenate tuple (not "_AnsibleLazyTemplateList") to tuple', TypeError), # __radd__ (relies on tuple.__add__)
370 ('tuple() + d1', 'can only concatenate tuple (not "_AnsibleLazyTemplateDict") to tuple', TypeError), # relies on tuple.__add__
371 ('l1.pop(42)', "pop index out of range", IndexError),
372 ('type(l1)([])', 'Direct construction of lazy containers is not supported.', UnsupportedConstructionMethodError),
373 ('type(t1)([])', 'Direct construction of lazy containers is not supported.', UnsupportedConstructionMethodError),
374 ('type(d1)({})', 'Direct construction of lazy containers is not supported.', UnsupportedConstructionMethodError),
375 ], ids=str)
376 def test_lazy_container_operators(expression: str, expected_value: t.Any, expected_type: type) -> None:
377 """
378 Verify that lazy container operators and methods properly implement lazy behavior.
379 Results are checked both for expected types and expected values.
380 When the result is a container, items in the container are checked to see if they're lazy as appropriate.
381 This test uses a function to simulate Jinja plugin behavior, since plugins can use operators and methods that Jinja expressions cannot.
382 """
383 # DTFIX5: add a unit test to ensure every list/dict method has been overridden or on a list we can safely ignore
384 def l2f() -> list:
385 """Return a lazy list that uses different lazy options, to ensure it cannot be lazy combined."""
386 return TemplateContext.current().templar.template([2], lazy_options=LazyOptions.SKIP_TEMPLATES)
387
388 variables = dict(
389 one=1,
390 two=2,
391 data=dict(
392 l1=[TRUST.tag('{{ one }}')],
393 l1x=[TRUST.tag('{{ one }}')],
394 l2=[TRUST.tag('{{ two }}')],
395 l2f=l2f,
396 t1=(TRUST.tag('{{ one }}'),),
397 d1=dict(a=TRUST.tag('{{ one }}'), c=TRUST.tag('{{ one }}')),
398 d1x=dict(a=TRUST.tag('{{ one }}'), c=TRUST.tag('{{ one }}')),
399 d2=dict(b=TRUST.tag('{{ two }}'), c=TRUST.tag('{{ two }}')),
400 ),
401 )
402
403 def run_test(data: dict[str, t.Any]) -> t.Any:
404 nonlocal expected_value
405
406 secondary_templar = TemplateEngine()
407
408 # Run under a secondary context using a templar with no variables; this allows us to test the correct propagation and use of the
409 # embedded templar in lazy containers. Templated values will not render correctly if they pick up the ambient (no-vars) templar during
410 # various copy/operator scenarios.
411 with TemplateContext(template_value='', templar=secondary_templar, options=TemplateOptions.DEFAULT, stop_on_template=False):
412 code_globals = dict(
413 copy=copy,
414 ExampleSingletonTag=ExampleSingletonTag,
415 )
416
417 try:
418 result = eval(expression, code_globals, data)
419 except SyntaxError:
420 # some expressions use a semicolon to force exec instead of eval, even if they only need a single statement
421 exec(expression, code_globals, data)
422
423 var_name = list(expected_value)[0]
424 expected_value = expected_value[var_name]
425 result = data[var_name]
426 except Exception as ex:
427 if type(ex) is not expected_type: # pylint: disable=unidiomatic-typecheck
428 # we weren't expecting an exception, or got one of the wrong type; re-raise it now for the traceback instead of just a failed assertion
429 raise
430
431 result = ex
432
433 assert type(result) is expected_type # pylint: disable=unidiomatic-typecheck
434
435 expected_result: t.Any # avoid type narrowing
436
437 if issubclass(expected_type, list):
438 assert isinstance(result, list) # redundant, but assists mypy in understanding the type
439
440 expected_list_types = [type(value) for value in expected_value]
441 expected_result = [value.value if isinstance(value, _LazyValue) else value for value in expected_value]
442
443 actual_list_types: list[type] = [type(value) for value in list.__iter__(result)]
444
445 assert actual_list_types == expected_list_types
446 elif issubclass(expected_type, tuple):
447 assert isinstance(result, tuple) # redundant, but assists mypy in understanding the type
448
449 expected_tuple_types = [type(value) for value in expected_value]
450 expected_result = expected_value
451
452 actual_tuple_types: list[type] = [type(value) for value in tuple.__iter__(result)]
453
454 assert actual_tuple_types == expected_tuple_types
455 elif issubclass(expected_type, dict):
456 assert isinstance(result, dict) # redundant, but assists mypy in understanding the type
457
458 expected_dict_types = {key: type(value) for key, value in expected_value.items()}
459 expected_result = {key: value.value if isinstance(value, _LazyValue) else value for key, value in expected_value.items()}
460
461 actual_dict_types: dict[str, type] = {key: type(value) for key, value in dict.items(result)}
462
463 assert actual_dict_types == expected_dict_types
464 elif issubclass(expected_type, Exception):
465 result = str(result) # unfortunately exceptions can't be compared for equality, so use the string representation instead
466 expected_result = expected_value
467 else:
468 expected_result = expected_value
469
470 assert result == expected_result
471
472 templar = TemplateEngine(variables=variables)
473 templar.environment.globals['run_test'] = run_test
474 templar.template(TRUST.tag('{{ run_test(data=data) }}'))
475
476
477 def test_range_templating():
478 """
479 Verify special handling for Range objects.
480 They are usually listified like other iterables when returned from a Jinja filter or method/function call, except when calling the Python `range()`
481 global function directly, which allows the range object to be returned and used directly.
482 """
483 templar = TemplateEngine(variables=dict(
484 large_value=min(1000000000000, sys.maxsize - 1) # ensure we don't exceed ssize_t on 32-bit systems
485 ))
486
487 # ensure that an insanely large range is not listified
488 assert templar.evaluate_conditional(TRUST.tag("range(large_value) | type_debug == 'range'"))
489 assert isinstance(templar.template(TRUST.tag("{{ range(large_value) | random }}")), int)
490 assert templar.template(TRUST.tag("{{ range(3) | reverse }}")) == [2, 1, 0]
491
492
493 @pytest.mark.parametrize("value", [
494 "{{ range(10000) }}",
495 "{{ [range(10000)] }}",
496 "{{ {'a': range(10000)} }}",
497 ])
498 def test_range_template_fail(value):
499 """Verify unsupported range object usages."""
500 with pytest.raises(AnsibleTemplateError):
501 TemplateEngine().template(TRUST.tag(value))
502
503
504 LISTIFIED_ITERATOR_VALUES_AND_EXPECTED = (
505 ("{'a': 1, 'b': 2}.items()", [('a', 1), ('b', 2)]),
506 ("['hi'] | map('upper')", ["HI"]),
507 )
508
509 LISTIFIED_ITERATOR_VALUES = tuple(item[0] for item in LISTIFIED_ITERATOR_VALUES_AND_EXPECTED)
510 LISTIFIED_ITERATOR_TEMPLATES = tuple(TRUST.tag(f'{{{{ {value} }}}}') for value in LISTIFIED_ITERATOR_VALUES)
511
512
513 @pytest.mark.parametrize("value, expected", LISTIFIED_ITERATOR_VALUES_AND_EXPECTED)
514 def test_list_adapter_equality(value: str, expected: list) -> None:
515 origin = Origin(path='/test') # here to make sure it doesn't trigger an exception, it won't be in the result
516
517 assert TemplateEngine().evaluate_expression(TRUST.tag(origin.tag(f"{value} == {expected}")))
518
519
520 @pytest.mark.parametrize("value", LISTIFIED_ITERATOR_VALUES)
521 def test_list_adapter_source_propagation(value: t.Any) -> None:
522 origin = Origin(path='/test')
523
524 assert Origin.get_tag(TemplateEngine().template(TRUST.tag(origin.tag(f"{{{{ {value} }}}}")))) is origin
525
526
527 @pytest.mark.parametrize("value", t.cast(tuple, CONTAINER_VALUES) + LISTIFIED_ITERATOR_TEMPLATES, ids=str)
528 def test_lazy_containers_to_yaml(value: t.Any) -> None:
529 TemplateEngine(variables=dict(value=value)).template(TRUST.tag("{{ value | to_yaml }}"))
530
531
532 @pytest.mark.parametrize("value", t.cast(tuple, CONTAINER_VALUES) + LISTIFIED_ITERATOR_TEMPLATES, ids=str)
533 def test_lazy_containers_to_json(value: t.Any) -> None:
534 TemplateEngine(variables=dict(value=value)).template(TRUST.tag("{{ value | to_json }}"))
535
536
537 @pytest.mark.parametrize("value", (_AnsibleLazyTemplateDict, _AnsibleLazyTemplateList))
538 def test_lazy_interface(value: type[_AnsibleLazyTemplateMixin]) -> None:
539 """Ensure that lazy containers implement all the methods that their native types provide."""
540 missing = set(dir(value._native_type)) - set(dir(value))
541 assert not missing
542
543
544 @pytest.mark.parametrize("expression, expected", (
545 ("l1[0]", [0]), # _AnsibleLazyTemplateList.__getitem__ and _ansible_finalize (list to lazy list)
546 ("l1[1]", [1]), # _AnsibleLazyTemplateList.__getitem__
547 ("l1[2]", 'hello'), # _AnsibleLazyTemplateList.__getitem__
548 ("[v for v in l1][0]", [0]), # _AnsibleLazyTemplateList.__iter__ and _ansible_finalize (list to lazy list)
549 ("[v for v in l1][1]", [1]), # _AnsibleLazyTemplateList.__iter__
550 ("[v for v in l1][2]", 'hello'), # _AnsibleLazyTemplateList.__iter__
551 ("d1['a']", [0]), # _AnsibleLazyTemplateDict.__getitem__ and _ansible_finalize (dict to lazy dict)
552 ("d1['b']", [1]), # _AnsibleLazyTemplateDict.__getitem__
553 ("d1['c']", 'hello'), # _AnsibleLazyTemplateDict.__getitem__
554 ("{k: v for k, v in d1.items()}['a']", [0]), # _AnsibleLazyTemplateDict.items and _ansible_finalize (dict to lazy dict)
555 ("{k: v for k, v in d1.items()}['b']", [1]), # _AnsibleLazyTemplateDict.items
556 ("{k: v for k, v in d1.items()}['c']", 'hello'), # _AnsibleLazyTemplateDict.items
557 ), ids=str)
558 def test_lazy_persistence(expression: str, expected: t.Any) -> None:
559 """
560 Verify that values returned from lazy containers are persistent, regardless of whether templating is involved or not.
561 A global function is used to simulate the behavior that would occur in a Jinja plugin.
562 """
563 variables = dict(
564 data=dict(
565 l1=[TRUST.tag('{{ [0] }}'), [1], 'hello'],
566 d1=dict(a=TRUST.tag('{{ [0] }}'), b=[1], c='hello'),
567 ),
568 )
569
570 def run_test(data: dict[str, t.Any]) -> None:
571 first = eval(expression, data)
572 second = eval(expression, data)
573
574 assert first == expected
575 assert first is second
576
577 templar = TemplateEngine(variables=variables)
578 templar.environment.globals['run_test'] = run_test
579
580 templar.template(TRUST.tag("{{ run_test(data=data) }}"))
581
582
583 @pytest.mark.parametrize("expression", (
584 "data['l1'][0]",
585 "data['d1']['a']",
586 ))
587 def test_lazy_mutation_persistence(expression: str) -> None:
588 """Verify that lazy containers persist values added after creation and return them as-is without modification, even if they contain trusted templates."""
589 # DTFIX5: investigate relevance of this test now that mutation/dirty tracking is toast
590 variables = dict(
591 data=dict(
592 l1=[None],
593 d1=dict(a=None),
594 ),
595 )
596
597 def run_test(data: dict[str, t.Any]) -> None:
598 assert data
599
600 value = [TRUST.tag('{{ "hi" }}')]
601
602 exec(f'{expression} = value')
603
604 result = eval(expression)
605
606 assert result is value
607
608 templar = TemplateEngine(variables=variables)
609 templar.environment.globals['run_test'] = run_test
610
611 templar.template(TRUST.tag("{{ run_test(data=data) }}"))
612
613
614 @pytest.mark.parametrize("expr, new_value, some_var, expected_value", [
615 ("access_and_mutate_dict(mutate_dict(some_var))", TRUST.tag("{{ 'mom' }}"), dict(one="one"), dict(one="one", new="{{ 'mom' }}", secondnew="{{ 'mom' }}")),
616 ("access_and_mutate_list(mutate_list(some_var))", TRUST.tag("{{ 'mom' }}"), ["one"], ["one", "{{ 'mom' }}", "{{ 'mom' }}"]),
617 ])
618 def test_lazy_mutation_cross_plugin_dirty_container(expr: str, new_value: t.Any, some_var: t.Any, expected_value: t.Any):
619 """Ensure that new templates sourced from a plugin are not processed by subsequent plugins or template finalization."""
620 # DTFIX5: investigate relevance of this test now that mutation/dirty tracking is toast
621 def mutate_list(value: list) -> list:
622 value.append(new_value)
623
624 assert value[1] is new_value
625
626 return value
627
628 def access_and_mutate_list(value: list) -> list:
629 value.append(new_value)
630
631 assert value[2] is new_value
632 assert value[1] == expected_value[1]
633
634 return value
635
636 def mutate_dict(value: dict) -> dict:
637 value['new'] = new_value
638
639 assert value['new'] is new_value
640
641 return value
642
643 def access_and_mutate_dict(value: t.Any) -> list:
644 value['secondnew'] = new_value
645
646 assert value['secondnew'] is new_value
647 assert value['new'] == expected_value['new']
648
649 return value
650
651 available_vars = dict(some_var=some_var,
652 access_and_mutate_list=access_and_mutate_list,
653 mutate_list=mutate_list,
654 access_and_mutate_dict=access_and_mutate_dict,
655 mutate_dict=mutate_dict)
656
657 res = TemplateEngine(variables=available_vars).evaluate_expression(TRUST.tag(expr))
658 assert res == expected_value
659
660
661 def test_undefined_in_jinja_constant_container():
662 """
663 Retrieval of an undefined value in a plugin which does not declare undefined support should internally raise AnsibleUndefinedVariable, which, if
664 unhandled by the plugin, will be converted to an AnsibleUndefined and returned as the result of that plugin's invocation, allowing the template
665 to continue execution.
666 """
667
668 plugin_retrieved_the_value = False
669
670 def demo(_input, arg):
671 nonlocal plugin_retrieved_the_value
672 _x = arg[0]
673 plugin_retrieved_the_value = True
674 return []
675
676 templar = TemplateEngine()
677 templar.environment.filters['demo'] = demo
678
679 with pytest.raises(AnsibleUndefinedVariable):
680 x = templar.template(TRUST.tag("{{ True | demo([bogus_var]) }}"))
681 pass
682 assert not plugin_retrieved_the_value
683
684 assert templar.template(TRUST.tag("{{ True | demo([bogus_var]) | default('nope') }}")) == 'nope'
685 assert not plugin_retrieved_the_value
686
687
688 class CustomSequence(c.Sequence):
689 def __init__(self, values) -> None:
690 self._content = list(values)
691
692 def __getitem__(self, item) -> t.Any:
693 return self._content[item]
694
695 def __len__(self) -> int:
696 return len(self._content)
697
698
699 @pytest.mark.parametrize("expression, expected_result", (
700 # verify templates sourced by plugins are not auto-templated
701 ("list_with_bad_template() | pass_through is first_item_unrendered", True), # plain list return values are lazy wrapped, but not templated
702 ("tuple_with_bad_template() | pass_through is first_item_unrendered", True), # tuples are not lazified, but suppressed unsupported type warning
703 # verify markers are tripped on managed access, but not unmanaged access (they will still trip on use, which is not tested here)
704 ("list_with_undefined() | pass_through is first_item_trips", True), # managed access trips
705 ("tuple_with_undefined() | pass_through is first_item_trips", True), # managed access trips
706 ("custom_sequence_with_undefined() | pass_through is first_item_trips", False), # unmanaged access doesn't trip
707 # verify that Jinja constant containers are wrapped where possible
708 ("['{{ 1 }}'] | pass_through is first_item_unrendered", True),
709 ("[bogusvar] | pass_through is first_item_trips", True),
710 ("{'k': bogusvar} | pass_through is first_item_trips", True),
711 ("(bogusvar,) | pass_through is first_item_trips", True),
712 # verify that plugins directly invoking tests and filters do not trigger auto-templating
713 ('call_filter_with_native_args_kwargs()', True), # `call_filter` invocations with plain list/dict should be lazy non-templating
714 ('call_test_with_native_args_kwargs()', True), # `call_test` invocations with plain list/dict should be lazy non-templating
715 ))
716 def test_plugin_result_wrapping(expression: str, expected_result: t.Any, _ignore_untrusted_template) -> None:
717 """
718 Validate various intra-plugin container behaviors:
719 * A plain list/dict returned by a Jinja call/plugin gets lazified, but with templating disabled (feature parity with pre-2.19).
720 * Tuple/set returned by a Jinja call/plugin receives no special behavior.
721 * Jinja plugins that do not accept markers should raise when accessing one from a lazy container.
722 The default test "untrusted template as error" behavior is disabled, since some test cases involve accessing untrusted templates.
723 """
724 templar = TemplateEngine()
725
726 def list_with_bad_template() -> list[str]:
727 return [TRUST.tag('{{ 1 / 0 }}')]
728
729 def list_with_undefined() -> list[Marker]:
730 return [TemplateEngine().template(TRUST.tag('{{ bogusvar }}'))]
731
732 def tuple_with_bad_template() -> tuple[str, ...]:
733 return (TRUST.tag('{{ 1 / 0 }}'),)
734
735 def tuple_with_undefined() -> tuple[Marker, ...]:
736 return (TemplateEngine().template(TRUST.tag('{{ bogusvar }}')),)
737
738 def custom_sequence_with_undefined() -> CustomSequence:
739 return CustomSequence((TemplateEngine().template(TRUST.tag('{{ bogusvar }}')),))
740
741 def pass_through(value: t.Any) -> t.Any:
742 return value
743
744 def first_item_trips(value: c.Sequence | c.Mapping) -> bool:
745 if isinstance(value, c.Mapping):
746 key_or_idx = list(value.keys())[0]
747 else:
748 key_or_idx = 0
749
750 try:
751 value[key_or_idx]
752 except MarkerError:
753 return True
754
755 return False
756
757 def first_item_unrendered(value: c.Sequence) -> bool:
758 return isinstance(value[0], str) and is_possibly_template(value[0])
759
760 def call_filter_with_native_args_kwargs() -> t.Any:
761 return templar.environment.call_filter('args_and_kwargs_are_non_templating_lazy', value=42, args=[[1]], kwargs=dict(kwarg=[2]))
762
763 def call_test_with_native_args_kwargs() -> t.Any:
764 return templar.environment.call_test('args_and_kwargs_are_non_templating_lazy', value=42, args=[[1]], kwargs=dict(kwarg=[2]))
765
766 def args_and_kwargs_are_non_templating_lazy(value: t.Any, arg, *, kwarg) -> bool:
767 return (
768 value == 42 and
769 isinstance(arg, _AnsibleLazyTemplateList) and
770 not arg._lazy_options.template and
771 isinstance(kwarg, _AnsibleLazyTemplateList) and
772 not kwarg._lazy_options.template
773 )
774
775 templar.environment.globals.update(
776 list_with_bad_template=list_with_bad_template,
777 list_with_undefined=list_with_undefined,
778 tuple_with_bad_template=tuple_with_bad_template,
779 tuple_with_undefined=tuple_with_undefined,
780 custom_sequence_with_undefined=custom_sequence_with_undefined,
781 call_filter_with_native_args_kwargs=call_filter_with_native_args_kwargs,
782 call_test_with_native_args_kwargs=call_test_with_native_args_kwargs,
783 )
784
785 templar.environment.filters.update(
786 pass_through=pass_through,
787 args_and_kwargs_are_non_templating_lazy=args_and_kwargs_are_non_templating_lazy,
788 )
789
790 templar.environment.tests.update(
791 first_item_unrendered=first_item_unrendered,
792 first_item_trips=first_item_trips,
793 args_and_kwargs_are_non_templating_lazy=args_and_kwargs_are_non_templating_lazy,
794 )
795
796 expression = TRUST.tag(expression)
797
798 with emits_warnings(warning_pattern=[], deprecation_pattern=[]):
799 result = templar.evaluate_expression(expression)
800
801 assert result == expected_result
802
803
804 def test_lazy_options_propagation(template_context):
805 """Ensure that lazy collections propagate lazy options to child lazies."""
806 src_template = "{{ 1 / 0 }}"
807
808 def nested_container_with_template() -> t.Any:
809 return [[TRUST.tag(src_template)]]
810
811 templar = TemplateEngine()
812 templar.environment.globals.update(nested_container_with_template=nested_container_with_template)
813
814 res = templar.template(TRUST.tag('{{ nested_container_with_template() }}'))
815
816 assert isinstance(res, _AnsibleLazyTemplateList)
817 assert not res._lazy_options.template # ensure call output skips templating
818 assert isinstance(res[0], _AnsibleLazyTemplateList)
819 assert res[0]._lazy_options is res._lazy_options # ensure the parent options are propagated
820 assert res[0][0] == src_template
821
822
823 def test_subclass_dispatch_collision():
824 """Simulate a developer error by creating a new lazy container subclass with colliding base and/or tagged type dispatch entries."""
825
826 class _TestBaseType: ...
827 class _TaggedTestBaseType(_TestBaseType, AnsibleTaggedObject): ...
828 class _LazyTaggedTestBaseType(_TaggedTestBaseType, _AnsibleLazyTemplateMixin): ...
829
830 with pytest.raises(
831 TypeError,
832 match=f"Lazy mixin '_OopsConflictingLazyTaggedTestBaseType' type '_TaggedTestBaseType' conflicts with {_LazyTaggedTestBaseType.__name__!r}.",
833 ):
834 class _OopsConflictingLazyTaggedTestBaseType(_TaggedTestBaseType, _AnsibleLazyTemplateMixin): ...
835 assert _OopsConflictingLazyTaggedTestBaseType # pragma: nocover
836
837 with pytest.raises(
838 TypeError,
839 match=f"Lazy mixin '_OopsConflictingTestBaseType' type '_TestBaseType' conflicts with {_LazyTaggedTestBaseType.__name__!r}.",
840 ):
841 class _OopsConflictingTestBaseType(_TestBaseType, _AnsibleLazyTemplateMixin): ...
842 assert _OopsConflictingTestBaseType # pragma: nocover
843
844
845 _L = ['a']
846 _D = dict(B='b')
847 _T = ('c',)
848
849
850 @pytest.mark.parametrize("value, deep", (
851 ([_L, _D, _T], False),
852 ([_L, _D, _T], True),
853 (dict(L=_L, D=_D, T=_T), False),
854 (dict(L=_L, D=_D, T=_T), True),
855 ((_L, _D, _T), False),
856 ((_L, _D, _T), True),
857 ), ids=str)
858 def test_lazy_copies(value: list | dict, deep: bool, template_context: TemplateContext) -> None:
859 """Verify that `copy.copy` and `copy.deepcopy` make lazy copies of lazy containers."""
860 # pylint: disable=unnecessary-dunder-call
861 original = _AnsibleLazyTemplateMixin._try_create(value)
862 base_type = type(value)
863 pseudo_lazy = base_type is tuple # tuples do not wrap their values in `_LazyValue`
864
865 keys: list
866
867 if base_type is list or base_type is tuple:
868 keys = list(range(len(original)))
869 else:
870 keys = list(original)
871
872 assert all(isinstance(base_type.__getitem__(original, key), _LazyValue) != pseudo_lazy for key in keys) # lazy before copy
873
874 if deep:
875 copied = copy.deepcopy(original)
876 else:
877 copied = copy.copy(original)
878
879 assert copied is not original
880 assert len(copied) == len(original)
881 assert pseudo_lazy or all(isinstance(base_type.__getitem__(original, key), _LazyValue) != pseudo_lazy for key in keys) # still lazy after copy
882
883 assert all((base_type.__getitem__(copied, key) is base_type.__getitem__(original, key)) != deep for key in keys)
884 assert (copied._templar is original._templar) != deep
885 assert (copied._lazy_options is original._lazy_options) != deep
886
887
888 def test_lazy_template_mixin_init() -> None:
889 """
890 Verify `_AnsibleLazyTemplateMixin` checks the __init__ arg type.
891 This code path is not normally reachable, since types which use it perform the same check before invoking the mixin.
892 """
893 with pytest.raises(UnsupportedConstructionMethodError):
894 _AnsibleLazyTemplateMixin(t.cast(t.Any, None))