Debian Codegraph @

test/units/_internal/templating/test_templar.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import itertools
21 import pathlib
22 import sys
23
24 import unittest.mock
25 import typing as t
26
27 import pytest_mock
28
29 from jinja2.runtime import Context
30 from jinja2.loaders import DictLoader
31
32 import unittest
33
34 from ansible._internal import _display_utils
35 from ansible._internal._templating._datatag import _JinjaConstTemplate
36 from ansible.errors import (
37 AnsibleError, AnsibleUndefinedVariable, AnsibleTemplateSyntaxError, AnsibleBrokenConditionalError, AnsibleTemplateError, AnsibleTemplateTransformLimitError,
38 TemplateTrustCheckFailedError,
39 )
40 from ansible._internal._templating._errors import AnsibleTemplatePluginRuntimeError, AnsibleTemplatePluginLoadError, AnsibleTemplatePluginNotFoundError
41 from ansible._internal._errors._handler import ErrorAction, ErrorHandler
42 from ansible.module_utils._internal._datatag import AnsibleTagHelper, AnsibleDatatagBase
43 from ansible.module_utils._internal._datatag._tags import Deprecated
44 from ansible._internal._templating import _transform
45 from ansible.utils.collection_loader._collection_finder import _AnsibleCollectionFinder
46 from ansible._internal._datatag._tags import Origin, TrustedAsTemplate
47 from ansible.plugins.loader import init_plugin_loader
48 from ansible._internal._templating._jinja_common import _TemplateConfig, _SandboxMode
49 from ansible._internal._templating._jinja_plugins import _lookup
50 from ansible._internal._templating import _jinja_plugins
51 from ansible._internal._templating._engine import TemplateEngine, TemplateOptions
52 from ansible._internal._templating._jinja_bits import AnsibleEnvironment, AnsibleContext, is_possibly_template, is_possibly_all_template
53 from ansible._internal._templating._marker_behaviors import ReplacingMarkerBehavior
54 from ansible._internal._templating._utils import TemplateContext
55 from ansible.module_utils._internal import _event_utils
56 from ansible.utils.display import Display
57 from units.mock.loader import DictDataLoader
58 from units.test_utils.controller.display import emits_warnings
59
60 import pytest
61
62 TRUST = TrustedAsTemplate()
63
64 origin = Origin(path="/some/path/for/testing", line_num=1, col_num=2)
65
66
67 class BaseTemplar(object):
68 def setUp(self):
69 init_plugin_loader()
70 self.test_vars = dict(
71 foo="bar",
72 bam=TrustedAsTemplate().tag("{{foo}}"),
73 num=1,
74 var_true=True,
75 var_false=False,
76 var_dict=dict(a="b"),
77 bad_dict="{a='b'",
78 var_list=[1],
79 recursive=TrustedAsTemplate().tag("{{recursive}}"),
80 some_var="blip",
81 some_keyword=TrustedAsTemplate().tag("{{ foo }}"),
82 some_unsafe_var="unsafe_blip",
83 some_unsafe_keyword=TrustedAsTemplate().tag("{{ foo }}"),
84 str_with_error=TrustedAsTemplate().tag("{{ 'str' | from_json }}"),
85 template_dict={TrustedAsTemplate().tag("{{ a_keyword }}"): TrustedAsTemplate().tag("{{ some_var }}")},
86 template_var=TrustedAsTemplate().tag('{{ some_var }}'),
87 )
88 self.fake_loader = DictDataLoader({
89 "/path/to/my_file.txt": "foo\n",
90 })
91 self.templar = TemplateEngine(loader=self.fake_loader, variables=self.test_vars)
92 self._ansible_context = AnsibleContext(self.templar.environment, {}, {}, {})
93
94 def tearDown(self):
95 _AnsibleCollectionFinder._remove()
96 nuke_module_prefix('ansible_collections')
97
98
99 class TestTemplarTemplate(BaseTemplar, unittest.TestCase):
100 def test_trust_fail_raises_in_tests(self):
101 """Ensure template trust check failures default to fatal for unit tests (set in units/conftest.py)"""
102 from ansible._internal._templating._engine import TemplateTrustCheckFailedError
103
104 assert _TemplateConfig.untrusted_template_handler.action is ErrorAction.ERROR
105
106 with pytest.raises(TemplateTrustCheckFailedError):
107 self.templar.template("{{ i_am_not_trusted }}")
108
109 def test_trust_fail_warning_behavior(self):
110 """Validate that trust checks are non-fatal when TemplateConfig.untrusted_template_handler is set to `ErrorAction.WARNING`."""
111 untrusted_template = "{{ i_am_not_trusted }}"
112
113 assert hasattr(_TemplateConfig, 'untrusted_template_handler')
114
115 with (unittest.mock.patch.object(_TemplateConfig, 'untrusted_template_handler', ErrorHandler(ErrorAction.WARNING)),
116 unittest.mock.patch.object(Display, 'error_as_warning', return_value=None) as mock_warning):
117 assert self.templar.template(untrusted_template) is untrusted_template
118
119 assert mock_warning.call_count > 0
120 warning_value = mock_warning.call_args.kwargs['exception']
121 assert isinstance(warning_value, TemplateTrustCheckFailedError)
122 assert "Encountered untrusted template or expression" in warning_value.message
123 assert warning_value.obj == untrusted_template
124
125 def test_is_possible_template(self):
126 """This test ensures that a broken template still gets templated"""
127 # Purposefully invalid jinja
128 self.assertRaises(AnsibleError, self.templar.template, TrustedAsTemplate().tag('{{ foo|default(False)) }}'))
129
130 def test_is_template_raw_string(self):
131 res = self.templar.is_template('foo')
132 self.assertFalse(res)
133
134 def test_is_template_none(self):
135 res = self.templar.is_template(None)
136 self.assertFalse(res)
137
138 def test_template(self):
139 res = self.templar.template(TrustedAsTemplate().tag('{{foo}}'))
140 self.assertTrue(res)
141 self.assertEqual(res, 'bar')
142
143 def test_template_in_data(self):
144 res = self.templar.template(TrustedAsTemplate().tag('{{bam}}'))
145 self.assertTrue(res)
146 self.assertEqual(res, 'bar')
147
148 def test_template_bare(self):
149 res = self.templar.template('bam')
150 self.assertTrue(res)
151 self.assertEqual(res, 'bam')
152
153 def test_template_to_json(self):
154 res = self.templar.template(TrustedAsTemplate().tag('{{bam|to_json}}'))
155 self.assertTrue(res)
156 self.assertEqual(res, '"bar"')
157
158 def test_template_untagged_string(self):
159 unsafe_obj = "Hello"
160 res = self.templar.template(unsafe_obj)
161 assert not TrustedAsTemplate.is_tagged_on(res)
162
163 def test_weird(self):
164 data = TrustedAsTemplate().tag(u"""1 2 #}huh{# %}ddfg{% }}dfdfg{{ {%what%} {{#foo#}} {%{bar}%} {#%blip%#} {{asdfsd%} 3 4 {{foo}} 5 6 7""")
165 self.assertRaisesRegex(AnsibleError,
166 'Syntax error in template',
167 self.templar.template,
168 data)
169
170 def test_template_with_error(self):
171 """Check that AnsibleError is raised, fail if an unhandled exception is raised"""
172 self.assertRaises(AnsibleError, self.templar.template, TrustedAsTemplate().tag("{{ str_with_error }}"))
173
174
175 class TestTemplarMisc(BaseTemplar, unittest.TestCase):
176 def test_templar_simple(self):
177
178 templar = self.templar
179 # test some basic templating
180 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{foo}}")), "bar")
181 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{foo}}\n")), "bar\n")
182 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{foo}}\n"), options=TemplateOptions(preserve_trailing_newlines=True)), "bar\n")
183 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{foo}}\n"), options=TemplateOptions(preserve_trailing_newlines=False)), "bar")
184 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{bam}}")), "bar")
185 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{num}}")), 1)
186 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{var_true}}")), True)
187 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{var_false}}")), False)
188 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{var_dict}}")), dict(a="b"))
189 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{bad_dict}}")), "{a='b'")
190 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{var_list}}")), [1])
191
192 # force errors
193 self.assertRaises(AnsibleUndefinedVariable, templar.template, TrustedAsTemplate().tag("{{bad_var}}"))
194 self.assertRaises(AnsibleUndefinedVariable, templar.template, TrustedAsTemplate().tag("{{lookup('file', bad_var)}}"))
195 self.assertRaises(AnsibleError, templar.template, TrustedAsTemplate().tag("{{lookup('bad_lookup')}}"))
196 self.assertRaises(AnsibleError, templar.template, TrustedAsTemplate().tag("{{recursive}}"))
197 self.assertRaises(AnsibleUndefinedVariable, templar.template, TrustedAsTemplate().tag("{{foo-bar}}"))
198
199 result = templar.extend(marker_behavior=ReplacingMarkerBehavior()).template(TrustedAsTemplate().tag("{{bad_var}}"))
200 assert "<< error 1 - 'bad_var' is undefined >>" in result
201
202 # test setting available_variables
203 templar.available_variables = dict(foo="bam")
204 self.assertEqual(templar.template(TrustedAsTemplate().tag("{{foo}}")), "bam")
205
206 def test_templar_escape_backslashes(self):
207 # Rule of thumb: If escape backslashes is True you should end up with
208 # the same number of backslashes as when you started.
209 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\t{{foo}}"), options=TemplateOptions(escape_backslashes=True)), "\tbar")
210 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\t{{foo}}"), options=TemplateOptions(escape_backslashes=False)), "\tbar")
211 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\\{{foo}}"), options=TemplateOptions(escape_backslashes=True)), "\\bar")
212 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\\{{foo}}"), options=TemplateOptions(escape_backslashes=False)), "\\bar")
213 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\\{{foo + '\t' }}"), options=TemplateOptions(escape_backslashes=True)), "\\bar\t")
214 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\\{{foo + '\t' }}"), options=TemplateOptions(escape_backslashes=False)), "\\bar\t")
215 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\\{{foo + '\\t' }}"), options=TemplateOptions(escape_backslashes=True)), "\\bar\\t")
216 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\\{{foo + '\\t' }}"), options=TemplateOptions(escape_backslashes=False)), "\\bar\t")
217 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\\{{foo + '\\\\t' }}"), options=TemplateOptions(escape_backslashes=True)), "\\bar\\\\t")
218 self.assertEqual(self.templar.template(TrustedAsTemplate().tag("\\{{foo + '\\\\t' }}"), options=TemplateOptions(escape_backslashes=False)), "\\bar\\t")
219
220
221 class TestTemplarLookup(BaseTemplar, unittest.TestCase):
222 @staticmethod
223 def lookup(name: str, /, *args, **kwargs) -> t.Any:
224 with TemplateContext(template_value=None, templar=TemplateEngine(), options=TemplateOptions(), stop_on_template=False):
225 return _lookup(name, *args, **kwargs)
226
227 def test_lookup_missing_plugin(self):
228 self.assertRaisesRegex(AnsibleTemplatePluginNotFoundError,
229 "The lookup plugin 'not_a_real_lookup_plugin' was not found.",
230 self.lookup,
231 'not_a_real_lookup_plugin',
232 'an_arg', a_keyword_arg='a_keyword_arg_value')
233
234 def test_lookup_list(self):
235 res = self.lookup('list', 'an_arg', 'another_arg')
236 self.assertEqual(res, 'an_arg,another_arg')
237
238 def test_lookup_jinja_undefined(self):
239 self.assertRaisesRegex(AnsibleUndefinedVariable,
240 "'an_undefined_jinja_var' is undefined",
241 self.templar.template,
242 TrustedAsTemplate().tag('{{ lookup("list", an_undefined_jinja_var) }}'))
243
244 def test_lookup_jinja_defined(self):
245 res = self.lookup('list', 'x')
246 assert not TrustedAsTemplate.is_tagged_on(res)
247
248 def test_lookup_jinja_dict_string_passed(self):
249 self.assertRaisesRegex(AnsibleError,
250 "lookup plugin expects a dictionary",
251 self.lookup,
252 'dict',
253 'x')
254
255 def test_lookup_jinja_dict_list_passed(self):
256 self.assertRaisesRegex(AnsibleError,
257 "lookup plugin expects a dictionary",
258 self.lookup,
259 'dict',
260 ['foo', 'bar'])
261
262 def test_lookup_jinja_kwargs(self):
263 res = self.lookup('list', 'blip', random_keyword='12345')
264 assert not TrustedAsTemplate.is_tagged_on(res)
265
266 def test_lookup_jinja_list_wantlist(self):
267 res = self.templar.template(TrustedAsTemplate().tag("{{ lookup('list', template_var, wantlist=True) }}"))
268 self.assertEqual(res, ["blip"])
269
270 def test_lookup_jinja_list_wantlist_undefined(self):
271 self.assertRaisesRegex(AnsibleUndefinedVariable,
272 "'some_undefined_var' is undefined",
273 self.templar.template,
274 TrustedAsTemplate().tag('{{ lookup("list", some_undefined_var, wantlist=True) }}'))
275
276 def test_lookup_jinja_list_wantlist_unsafe(self):
277 res = self.lookup('list', 'x', wantlist=True)
278 for lookup_result in res:
279 assert not TrustedAsTemplate.is_tagged_on(lookup_result)
280
281 assert not TrustedAsTemplate.is_tagged_on(res)
282
283 def test_lookup_jinja_dict(self):
284 res = self.templar.template(TrustedAsTemplate().tag('{{ lookup("list", template_dict) }}'))
285 self.assertEqual(res['{{ a_keyword }}'], "blip")
286 assert not TrustedAsTemplate.is_tagged_on(res)
287
288 def test_lookup_jinja_dict_unsafe(self):
289 res = self.lookup('list', {'x': 'x'})
290 assert not TrustedAsTemplate.is_tagged_on(res['x'])
291 assert not TrustedAsTemplate.is_tagged_on(res)
292
293 def test_lookup_jinja_dict_unsafe_value(self):
294 res = self.lookup('list', {'x': 'x'})
295 assert not TrustedAsTemplate.is_tagged_on(res['x'])
296 assert not TrustedAsTemplate.is_tagged_on(res)
297
298 def test_lookup_jinja_none(self):
299 res = self.lookup('list', None)
300 self.assertIsNone(res)
301
302
303 class TestAnsibleContext(BaseTemplar, unittest.TestCase):
304 def _context(self, variables=None):
305 variables = variables or {}
306
307 env = AnsibleEnvironment()
308 context = AnsibleContext(env, parent={}, name='some_context',
309 blocks={})
310
311 for key, value in variables.items():
312 context.vars[key] = value
313
314 return context
315
316 def test(self):
317 context = self._context()
318 self.assertIsInstance(context, AnsibleContext)
319 self.assertIsInstance(context, Context)
320
321 def test_resolve_unsafe(self):
322 context = self._context(variables={'some_unsafe_key': 'some_unsafe_string'})
323 res = context.resolve('some_unsafe_key')
324 assert not TrustedAsTemplate.is_tagged_on(res)
325
326 def test_resolve_unsafe_list(self):
327 context = self._context(variables={'some_unsafe_key': ['some unsafe string 1']})
328 res = context.resolve('some_unsafe_key')
329 assert not TrustedAsTemplate.is_tagged_on(res[0])
330 assert not TrustedAsTemplate.is_tagged_on(res)
331
332 def test_resolve_unsafe_dict(self):
333 context = self._context(variables={'some_unsafe_key':
334 {'an_unsafe_dict': 'some unsafe string 1'}
335 })
336 res = context.resolve('some_unsafe_key')
337 assert not TrustedAsTemplate.is_tagged_on(res['an_unsafe_dict'])
338
339 def test_resolve(self):
340 context = self._context(variables={'some_key': 'some_string'})
341 res = context.resolve('some_key')
342 self.assertEqual(res, 'some_string')
343
344 def test_resolve_none(self):
345 context = self._context(variables={'some_key': None})
346 res = context.resolve('some_key')
347 self.assertEqual(res, None)
348
349
350 def test_unsafe_lookup():
351 res = TemplateEngine(
352 None,
353 variables={
354 'var0': TrustedAsTemplate().tag('{{ var1 }}'),
355 'var1': ['unsafe'],
356 }
357 ).template(TrustedAsTemplate().tag('{{ lookup("list", var0) }}'))
358 assert not TrustedAsTemplate.is_tagged_on(res[0])
359
360
361 def test_unsafe_lookup_no_conversion():
362 res = TemplateEngine(
363 None,
364 variables={
365 'var0': TrustedAsTemplate().tag('{{ var1 }}'),
366 'var1': ['unsafe'],
367 }
368 ).template(
369 TrustedAsTemplate().tag('{{ lookup("list", var0) }}'),
370 )
371 assert not TrustedAsTemplate.is_tagged_on(res)
372
373
374 @pytest.mark.parametrize("tagged", (
375 False,
376 True,
377 ))
378 def test_dict_template(tagged: bool) -> None:
379 """Verify that templar.template can round-trip both tagged and untagged values in a dict."""
380 key1 = "key1"
381 val1 = "val1"
382
383 if tagged:
384 key1 = origin.tag(key1)
385 val1 = origin.tag(val1)
386
387 test1 = {
388 key1: val1,
389 }
390
391 variables = dict(
392 test1=test1,
393 )
394
395 templar = TemplateEngine(variables=variables)
396
397 result = templar.template(TrustedAsTemplate().tag('{{test1}}'))
398
399 assert result == test1
400 assert AnsibleTagHelper.tags(result) == AnsibleTagHelper.tags(test1)
401
402
403 @pytest.mark.parametrize("expr,expected,variables", [
404 ("'constant'", "constant", None),
405 ("a - b", 42, dict(a=100, b=58)),
406 ])
407 def test_evaluate_expression(expr: str, expected: t.Any, variables: dict[str, t.Any] | None):
408 assert TemplateEngine(variables=variables).evaluate_expression(TRUST.tag(expr)) == expected
409
410
411 @pytest.mark.parametrize("expr,error_type", [
412 ("fhdgsfk#$76&@#$&", AnsibleTemplateSyntaxError),
413 ("bogusvar", AnsibleUndefinedVariable),
414 ("untrusted expression", TemplateTrustCheckFailedError),
415 (dict(hi="{{'mom'}}"), TypeError),
416 ])
417 def test_evaluate_expression_errors(expr: str, error_type: type[Exception]):
418 if error_type is not TemplateTrustCheckFailedError:
419 expr = TRUST.tag(expr)
420
421 with pytest.raises(error_type):
422 TemplateEngine().evaluate_expression(expr)
423
424
425 @pytest.mark.parametrize("conditional,expected,variables", [
426 ("1 == 2", False, None),
427 ("test2_name | default(True)", True, None),
428 # DTFIX5: more success cases?
429 ])
430 def test_evaluate_conditional(conditional: str, expected: t.Any, variables: dict[str, t.Any] | None):
431 assert TemplateEngine().evaluate_conditional(TRUST.tag(conditional)) == expected
432
433
434 @pytest.mark.parametrize("conditional,error_type", [
435 ("fkjhs$#@^%$*& ldfkjds", AnsibleTemplateSyntaxError),
436 ("#jinja2:variable_start_string:2\n{{blah}}", AnsibleTemplateSyntaxError),
437 ("#jinja2:bogus_key:'val'\n{{blah}}", AnsibleTemplateSyntaxError),
438 ("bogusvar", AnsibleUndefinedVariable),
439 ("not trusted", TemplateTrustCheckFailedError),
440 ])
441 def test_evaluate_conditional_errors(conditional: t.Any, error_type: type[Exception], mocker: pytest_mock.MockerFixture):
442 mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since a number of cases need it
443
444 if error_type is not TemplateTrustCheckFailedError:
445 conditional = TRUST.tag(conditional)
446
447 with pytest.raises(error_type):
448 TemplateEngine().evaluate_conditional(conditional)
449
450
451 @pytest.mark.parametrize("value", (
452 '{{ foo }}',
453 '{% foo %}',
454 '{# foo #}',
455 '{# {{ foo }} #}',
456 '{# {{ nothing }} {# #}',
457 '{# {{ nothing }} {# #} #}',
458 '{% raw %}{{ foo }}{% endraw %}',
459 # in 2.16 and earlier these were not considered templates due to syntax errors
460 # now syntax errors in templates are still reported as templates, since is_template no longer compiles the template
461 '{{ foo',
462 '{% foo',
463 '{# foo',
464 '{{ foo %}',
465 '{{ foo #}',
466 '{% foo }}',
467 '{% foo #}',
468 '{# foo %}',
469 '{# foo }}',
470 '{{ foo {{',
471 '{% raw %}{% foo %}',
472 ))
473 def test_is_template_true(value: str) -> None:
474 assert TemplateEngine().is_template(TRUST.tag(value))
475
476
477 @pytest.mark.parametrize("value", (
478 'foo',
479 ))
480 def test_is_template_false(value: str) -> None:
481 assert not TemplateEngine().is_template(TRUST.tag(value))
482
483
484 @pytest.mark.parametrize("value", (
485 '{{ foo }}',
486 '{% foo %}',
487 '{# foo #}',
488 '{# {{ foo }} #}',
489 '{# {{ nothing }} {# #}',
490 '{# {{ nothing }} {# #} #}',
491 '{% raw %}{{ foo }}{% endraw %}',
492 '{{',
493 '{%',
494 '{#',
495 '{% raw',
496 ))
497 def test_is_possibly_template_true(value: str) -> None:
498 assert is_possibly_template(value)
499
500
501 @pytest.mark.parametrize("value", (
502 '{',
503 '%',
504 '#',
505 'foo',
506 '}}',
507 '%}',
508 'raw %}',
509 '#}',
510 ))
511 def test_is_possibly_template_false(value: str) -> None:
512 assert not is_possibly_template(value)
513
514
515 def test_stop_on_container() -> None:
516 # DTFIX5: add more test cases
517 assert TemplateEngine().resolve_to_container(TRUST.tag('{{ [ 1 ] }}')) == [1]
518
519
520 @pytest.mark.parametrize("value", [True, False])
521 def test_stripped_conditionals(value: bool, mocker: pytest_mock.MockerFixture) -> None:
522 mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since this case needs it
523
524 assert TemplateEngine().evaluate_conditional(TRUST.tag(f"""\n \r\n \t{{{{ {value} }}}} \n\n \t \t\t """)) == value
525
526
527 @pytest.mark.parametrize("template, variables, error", (
528 ("{{ undefined_var.undefined_attribute }}", {}, "'undefined_var' is undefined >>"),
529 ("{{ some_dict['undefined_key'] }}", dict(some_dict={}), "object of type 'dict' has no attribute 'undefined_key' >>"),
530 ("{{ some_dict.undefined_key }}", dict(some_dict={}), "object of type 'dict' has no attribute 'undefined_key' >>"),
531 ("{{ m1 }} {{ m2 }} here", {}, "<< error 1 - 'm1' is undefined >> << error 2 - 'm2' is undefined >> here"),
532 ("before {{ m1 + m2 }} after", {}, "before << error 1 - 'm1' is undefined >><< error 2 - template potentially truncated >>"),
533 ))
534 def test_jinja_sourced_undefined(template: str, variables: dict[str, t.Any], error: str) -> None:
535 """
536 Ensure when Jinja encounters a `Marker` and raises `MarkerError`,
537 that we turn it back into the original `Marker` so marker_behavior can handle it during finalization.
538 """
539 assert error in TemplateEngine(variables=variables, marker_behavior=ReplacingMarkerBehavior()).template(TRUST.tag(template))
540
541
542 def test_omit_concat() -> None:
543 assert TemplateEngine().template(TRUST.tag("{{ omit }}hi{{ omit }} mom")) == 'hi mom'
544
545
546 @pytest.mark.parametrize("conditional", (
547 # Jinja plugins
548 "'join' is filter",
549 "'join' is not test",
550 "'eq' is test",
551 "'eq' is not filter",
552
553 # Ansible plugins
554 "'comment' is filter",
555 "'comment' is not test",
556 "'version' is test",
557 "'version' is not filter",
558
559 # plugin not found
560 "'nope' is not filter",
561 "'nope' is not test",
562 ))
563 def test_plugin_found_not_found(conditional: str) -> None:
564 assert TemplateEngine().evaluate_conditional(TRUST.tag(conditional))
565
566
567 @pytest.mark.parametrize("value, expected", (
568 ("{{ {'a': 1}.items() }}", [['a', 1]]),
569 ("{{ {'a': 1}.keys() }}", ['a']),
570 ("{{ {'a': 1}.values() }}", [1]),
571 ("{{ yielder(2) }}", [0, 1]),
572 ("{% set y = yielder(2) %}{{ y | list }} | {{ y | list }}", "[0, 1] | [0, 1]"),
573 ), ids=str)
574 def test_finalize_generator(value: t.Any, expected: t.Any) -> None:
575 def yielder(count: int) -> t.Generator[int, None, None]:
576 yield from range(count)
577
578 templar = TemplateEngine(variables=dict(
579 yielder=yielder,
580 ))
581
582 # DTFIX5: we still need to deal with the "Encountered unsupported" warnings these generate
583 assert templar.template(TRUST.tag(value)) == expected
584
585
586 @pytest.mark.parametrize("template", (
587 "{{ lookup('my_lookup', some_var) }}",
588 "{{ some_var | my_filter }}",
589 "{{ some_var is my_test }}",
590 ))
591 def test_eager_trip_undefined(template: str, mocker: pytest_mock.MockerFixture) -> None:
592 """Verify that eager tripping of Marker works for template plugins which only perform isinstance checks on undefined values."""
593 from ansible.plugins.lookup import LookupBase
594
595 class MyLookup(LookupBase):
596 def run(self, terms, variables=None, **kwargs):
597 return [isinstance(value, bool) for value in itertools.chain(*terms)]
598
599 def my_filter(values):
600 return [isinstance(value, bool) for value in values]
601
602 def my_test(values):
603 return all(isinstance(value, bool) for value in values)
604
605 def mock_lookup_get(*_args, **_kwargs) -> t.Any:
606 return MyLookup()
607
608 mock_lookup_loader = mocker.MagicMock()
609 mock_lookup_loader.get = mock_lookup_get
610
611 mocker.patch.object(_jinja_plugins, 'lookup_loader', mock_lookup_loader)
612
613 def get_templar(variables: dict[str, t.Any]) -> TemplateEngine:
614 new_templar = TemplateEngine(variables=variables)
615 new_templar.environment.filters['my_filter'] = my_filter
616 new_templar.environment.tests['my_test'] = my_test
617
618 return new_templar
619
620 template = TRUST.tag(template)
621
622 # verify the template works when some_var is defined
623
624 templar = get_templar(dict(some_var=[True]))
625
626 result = templar.template(template)
627
628 assert result is True or result == [True]
629
630 # verify the template raises AnsibleUndefinedVariable when some_var contains a template that references an undefined variable
631
632 templar = get_templar(dict(some_var=[TRUST.tag("{{ nope }}")]))
633
634 with pytest.raises(AnsibleUndefinedVariable) as ex:
635 templar.template(template)
636
637 assert ex.value.message == "'nope' is undefined"
638
639
640 def as_template(value: str) -> str:
641 return f"{{{{ {value} }}}}"
642
643
644 TEMPLATED_LOOKUP_NAME_TEST_VALUES = [
645 ("""lookup('{{ "pipe" }}', 'echo hi')""", "hi"),
646 ("""query('{{ "pipe" }}', 'echo hi')""", ["hi"]),
647 ]
648
649
650 @pytest.mark.parametrize("value", [v[0] for v in TEMPLATED_LOOKUP_NAME_TEST_VALUES])
651 def test_lookup_query_name_is_not_templated_non_conditional(value: str) -> None:
652 with pytest.raises(AnsibleTemplatePluginNotFoundError):
653 TemplateEngine().template(TRUST.tag(as_template(value)))
654
655
656 @pytest.mark.parametrize("value", [v[0] for v in TEMPLATED_LOOKUP_NAME_TEST_VALUES])
657 def test_lookup_query_name_is_not_templated_conditional_nested_template(value: str, mocker: pytest_mock.MockerFixture) -> None:
658 mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since a number of cases need it
659
660 with pytest.raises(AnsibleTemplatePluginNotFoundError):
661 TemplateEngine().evaluate_conditional(TRUST.tag(as_template(value)))
662
663
664 @pytest.mark.parametrize("value, expected_result", TEMPLATED_LOOKUP_NAME_TEST_VALUES)
665 def test_lookup_query_name_is_not_templated_conditional_expression(value: str, expected_result: t.Any, mocker: pytest_mock.MockerFixture) -> None:
666 mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since a number of cases need it
667
668 with emits_warnings(warning_pattern="should not contain embedded templates"):
669 assert TemplateEngine().evaluate_conditional(TRUST.tag(f'{value} == {expected_result!r}'))
670
671
672 @pytest.mark.parametrize("value", [
673 "foo(",
674 "'a' == {{ 'b' }}",
675 ])
676 def test_conditional_syntax_error(value: str) -> None:
677 with pytest.raises(AnsibleTemplateSyntaxError):
678 TemplateEngine().evaluate_conditional(TRUST.tag(value))
679
680
681 BROKEN_CONDITIONAL_VALUES = [
682 (None, True), # stupid backward-compat
683 ("", True), # stupid backward-compat
684 ("''", False),
685 ("0", False),
686 ("0.0", False),
687 ("1", True),
688 ("1.1", True),
689 ("'abc'", True),
690 ("{{ '' }}", True),
691 ("{{ None }}", True),
692 ("{{ 0 }}", False),
693 ("{{ 0.0 }}", False),
694 ("{{ [] }}", False),
695 ("{{ {} }}", False),
696 ([], False),
697 ([TRUST.tag("{{ omit }}")], False),
698 ({}, False),
699 (dict(a=TRUST.tag("{{ omit }}")), False),
700 (["abc", TRUST.tag("{{ omit }}")], True),
701 (dict(a="b", omitted=TRUST.tag("{{ omit }}")), True),
702 (0, False),
703 (0.0, False),
704 (1, True),
705 (1.1, True),
706 ]
707
708
709 @pytest.mark.parametrize("value", [v[0] for v in BROKEN_CONDITIONAL_VALUES], ids=repr)
710 def test_broken_conditionals_disabled(value: t.Any, mocker: pytest_mock.MockerFixture) -> None:
711 mocker.patch.object(_TemplateConfig, 'allow_broken_conditionals', False)
712
713 with pytest.raises(AnsibleBrokenConditionalError):
714 TemplateEngine().evaluate_conditional(TRUST.tag(value))
715
716
717 @pytest.mark.parametrize("value, expected_result", BROKEN_CONDITIONAL_VALUES, ids=repr)
718 def test_broken_conditionals_enabled(value: t.Any, expected_result: bool, mocker: pytest_mock.MockerFixture) -> None:
719 mocker.patch.object(_TemplateConfig, 'allow_broken_conditionals', True)
720 mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since a number of cases need it
721
722 deprecation_matches = []
723
724 if isinstance(value, str) and is_possibly_all_template(value):
725 deprecation_matches.append("should not be surrounded")
726
727 if value in (None, '', "{{ '' }}", "{{ None }}"):
728 deprecation_matches.append("Empty conditional")
729 else:
730 deprecation_matches.append("must have a boolean result")
731
732 with emits_warnings(deprecation_pattern=deprecation_matches):
733 assert TemplateEngine().evaluate_conditional(TRUST.tag(value)) == expected_result
734
735
736 @pytest.mark.parametrize("template, expected", (
737 ("1 == '{{ 1 }}'", False),
738 ("lookup('items', '{{ [1, 2, 3] }}') == [1, 2, 3]", False),
739 ("query('items', '{{ [1, 2, 3] }}') == [1, 2, 3]", False),
740 ))
741 def test_embedded_templates_disabled(template: str, expected: t.Any, mocker: pytest_mock.MockerFixture) -> None:
742 mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', False)
743
744 with emits_warnings(warning_pattern=[]):
745 assert TemplateEngine().evaluate_conditional(TRUST.tag(template)) == expected
746
747
748 @pytest.mark.parametrize("template, expected", (
749 ("1 == '{{ 1 }}'", True),
750 ("lookup('items', '{{ [1, 2, 3] }}') == [1, 2, 3]", True),
751 ("query('items', '{{ [1, 2, 3] }}') == [1, 2, 3]", True),
752 ))
753 def test_embedded_templates_enabled(template: str, expected: t.Any, mocker: pytest_mock.MockerFixture) -> None:
754 mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True)
755
756 templar = TemplateEngine()
757
758 with emits_warnings(warning_pattern="should not contain embedded templates"):
759 assert templar.evaluate_conditional(TRUST.tag(template)) == expected
760
761 # only lookup/query args support embedded templates in an actual template (not a naked expression)
762 if 'lookup' in template or 'query' in template:
763 with emits_warnings(warning_pattern="should not contain embedded templates"):
764 assert templar.evaluate_conditional(TRUST.tag(as_template(template))) == expected
765
766
767 def test_available_vars_smuggling():
768 """
769 Jinja Template.render() and TemplateExpression.__call__() flatten their args/kwargs via splatting to dict(), which is an unnecessary copy as well as
770 causing top-level templated variables to be rendered prematurely. We have some arg smuggling code to prevent this, which this test validates.
771 """
772
773 class ExplodingDict(dict):
774 """A dict subclass that explodes when copied or iterated via `dict()`."""
775
776 def __iter__(self):
777 raise NotImplementedError()
778
779 def keys(self):
780 raise NotImplementedError()
781
782 template_vars = ExplodingDict()
783
784 # ensure our tripwire dict subclass fails when used as the source for a dict copy
785 with pytest.raises(NotImplementedError):
786 dict(template_vars)
787
788 # if Jinja copies our input dict, it should blow up; assert that it doesn't and that the template renders as expected
789 assert TemplateEngine(variables=template_vars).template(TRUST.tag("{{ 1 }}")) == 1
790
791
792 def test_template_var_isolation():
793 """
794 Ensure that plugin mutations to lazy-wrapped container variables do not persist outside templating.
795 Direct mutation via Templar.available_variables is not currently protected (and is generally a bad idea).
796 """
797
798 orig_dict_value = dict(one="one")
799 orig_list_value = [1, 2, 3]
800
801 available_vars = dict(dict_value=orig_dict_value, list_value=orig_list_value)
802
803 def mutate_my_vars(dict_value: dict, list_value: list) -> dict[str, t.Any]:
804 dict_value["added"] = "added"
805 list_value.append("added")
806
807 return dict(dict_value=dict_value, list_value=list_value)
808
809 res = TemplateEngine(variables=available_vars).evaluate_expression(
810 TRUST.tag("mutate_my_vars(dict_value, list_value)"),
811 local_variables=dict(mutate_my_vars=mutate_my_vars)
812 )
813
814 # ensure the plugin returned the mutated copies as expected
815 assert res == dict(dict_value=dict(one="one", added="added"), list_value=[1, 2, 3, "added"])
816
817 # ensure the original input variables are the same unmodified instances
818 assert available_vars == dict(dict_value=dict(one="one"), list_value=[1, 2, 3])
819 assert available_vars['dict_value'] is orig_dict_value
820 assert available_vars['list_value'] is orig_list_value
821
822
823 @pytest.mark.parametrize('fixture, plugin_type, plugin_name, expected', (
824 ('no_collections', 'filter', 'invalid/name.does_not_matter.also_does_not_matter', AnsibleTemplateSyntaxError), # plugin is None
825 ('no_collections', 'lookup', 'invalid/name.does_not_matter.also_does_not_matter', AnsibleTemplatePluginNotFoundError),
826 ('no_collections', 'filter', 'missing_namespace_name.does_not_matter.also_does_not_matter', AnsibleTemplateSyntaxError), # KeyError
827 ('no_collections', 'lookup', 'missing_namespace_name.does_not_matter.also_does_not_matter', AnsibleTemplatePluginNotFoundError),
828
829 ('valid_collection', 'filter', 'valid.invalid/name.does_not_matter', AnsibleTemplateSyntaxError), # KeyError
830 ('valid_collection', 'lookup', 'valid.invalid/name.does_not_matter', AnsibleTemplatePluginNotFoundError),
831 ('valid_collection', 'filter', 'valid.missing_collection.does_not_matter', AnsibleTemplateSyntaxError), # KeyError
832 ('valid_collection', 'lookup', 'valid.missing_collection.does_not_matter', AnsibleTemplatePluginNotFoundError),
833 ('valid_collection', 'filter', 'valid.also_valid.invalid/name', AnsibleTemplateSyntaxError), # plugin is None
834 ('valid_collection', 'lookup', 'valid.also_valid.invalid/name', AnsibleTemplatePluginNotFoundError),
835 ('valid_collection', 'filter', 'valid.also_valid.missing_plugin', AnsibleTemplateSyntaxError), # plugin is None
836 ('valid_collection', 'lookup', 'valid.also_valid.missing_plugin', AnsibleTemplatePluginNotFoundError),
837 ('valid_collection', 'filter', 'valid.also_valid.also_also_valid', []),
838 ('valid_collection', 'lookup', 'valid.also_valid.also_also_valid', []),
839 ('valid_collection', 'filter', 'valid.also_valid.runtime_error', AnsibleTemplatePluginRuntimeError),
840 ('valid_collection', 'lookup', 'valid.also_valid.runtime_error', AnsibleTemplatePluginRuntimeError),
841 ('valid_collection', 'filter', 'valid.also_valid.load_error', AnsibleTemplatePluginLoadError), # AnsibleError
842 ('valid_collection', 'lookup', 'valid.also_valid.load_error', AnsibleTemplatePluginLoadError),
843 ('valid_collection', 'template', '{% if false %}{{ 123 | valid.also_valid.load_error }}{% else %}Success{% endif %}', AnsibleTemplatePluginLoadError),
844
845 ('no_collections', 'filter', 'ansible.invalid/name.does_not_matter', AnsibleTemplateSyntaxError), # KeyError
846 ('no_collections', 'lookup', 'ansible.invalid/name.does_not_matter', AnsibleTemplatePluginNotFoundError),
847 ('no_collections', 'filter', 'ansible.missing_collection.does_not_matter', AnsibleTemplateSyntaxError), # KeyError
848 ('no_collections', 'lookup', 'ansible.missing_collection.does_not_matter', AnsibleTemplatePluginNotFoundError),
849 ('no_collections', 'filter', 'ansible.builtin.invalid/name', AnsibleTemplateSyntaxError), # plugin is None
850 ('no_collections', 'lookup', 'ansible.builtin.invalid/name', AnsibleTemplatePluginNotFoundError),
851 ('no_collections', 'filter', 'ansible.builtin.missing_plugin', AnsibleTemplateSyntaxError), # plugin is None
852 ('no_collections', 'lookup', 'ansible.builtin.missing_plugin', AnsibleTemplatePluginNotFoundError),
853 ('no_collections', 'filter', 'ansible.builtin.quote', 'foo'),
854 ('no_collections', 'lookup', 'ansible.builtin.env', []),
855 ('no_collections', 'template', '{% if false %}{{ 123 | ansible.builtin.missing_plugin }}{% else %}Success{% endif %}', 'Success'),
856
857 ('no_collections', 'filter', 'invalid/name', AnsibleTemplateSyntaxError), # plugin is None
858 ('no_collections', 'lookup', 'invalid/name', AnsibleTemplatePluginNotFoundError),
859 ('no_collections', 'filter', 'missing_plugin', AnsibleTemplateSyntaxError), # plugin is None
860 ('no_collections', 'lookup', 'missing_plugin', AnsibleTemplatePluginNotFoundError),
861 ('no_collections', 'filter', 'quote', 'foo'),
862 ('no_collections', 'lookup', 'env', []),
863 ), ids=str)
864 def test_jinja2_loader_plugin(fixture: str, plugin_type: str, plugin_name: str, expected: t.Any) -> None:
865 if plugin_type == 'filter':
866 expression = f'{{{{ "foo" | {plugin_name} }}}}'
867 elif plugin_type == 'template':
868 expression = plugin_name # abusing plugin_type and plugin_name to allow for testing arbitrary expressions
869 else:
870 expression = f'{{{{ lookup("{plugin_name}") }}}}'
871
872 # HACK: this test should really be using a shared collection loader fixture, but this fixes an "inherited" dummy collection loader
873 from ansible.utils.collection_loader._collection_finder import _AnsibleCollectionFinder
874
875 try:
876 _AnsibleCollectionFinder._remove()
877 nuke_module_prefix('ansible_collections')
878 except Exception:
879 pass
880
881 _AnsibleCollectionFinder(paths=[str(pathlib.Path(__file__).parent / 'fixtures' / fixture)])._install()
882
883 try:
884 if isinstance(expected, type) and issubclass(expected, Exception):
885 with pytest.raises(expected):
886 TemplateEngine().template(TRUST.tag(expression))
887 else:
888 assert TemplateEngine().template(TRUST.tag(expression)) == expected
889 finally:
890 _AnsibleCollectionFinder._remove()
891
892 nuke_module_prefix('ansible_collections')
893
894
895 def test_variable_name_as_template_success() -> None:
896 name = origin.tag("blar")
897
898 res = TemplateEngine().variable_name_as_template(name)
899 assert res.replace(' ', '') == "{{blar}}"
900
901 required_tags: frozenset[AnsibleDatatagBase] = frozenset({origin, TrustedAsTemplate()})
902
903 assert required_tags - AnsibleTagHelper.tags(res) == set() # there might be others, that's fine
904
905
906 def test_variable_name_as_template_invalid() -> None:
907 invalid_name = origin.tag(" invalid[var*name")
908
909 with pytest.raises(AnsibleError) as err:
910 TemplateEngine().variable_name_as_template(invalid_name)
911
912 assert err.value.obj is invalid_name
913
914
915 @pytest.mark.parametrize("expression, expected", (
916 ("dictthing.subdict1.subdict2", "hi mom"),
917 ("dictthing.sublist1[0]", 1),
918 ("dictthing[keys.sublist1][0]", 1),
919 ("123", 123),
920 ))
921 def test_resolve_variable_expression_success(expression: str, expected: t.Any) -> None:
922 templar = TemplateEngine()
923
924 local_variables = dict(
925 dictthing=dict(sublist1=[1, 2, 3], subdict1=dict(subdict2="hi mom")),
926 keys=dict(sublist1="sublist1")
927 )
928
929 assert templar.resolve_variable_expression(expression, local_variables=local_variables) == expected
930
931
932 @pytest.mark.parametrize("expression", (
933 "'text'",
934 "dictthing['subdict1']",
935 "q('env')",
936 ))
937 def test_resolve_variable_expression_invalid(expression: str) -> None:
938 templar = TemplateEngine()
939
940 with pytest.raises(AnsibleError) as err:
941 templar.resolve_variable_expression(expression, local_variables=dict(dictthing=dict(subdict1=1)))
942
943 assert err.value.obj is expression
944
945
946 def test_resolve_variable_expression_missing() -> None:
947 templar = TemplateEngine()
948
949 expr = origin.tag("missing_variable")
950
951 with pytest.raises(AnsibleUndefinedVariable) as err:
952 templar.resolve_variable_expression(expr)
953
954 assert err.value.obj == expr # may not be the same instance, since it was tagged TrustedAsTemplate internally
955
956 required_tags: frozenset[AnsibleDatatagBase] = frozenset({origin, TrustedAsTemplate()})
957
958 assert required_tags - AnsibleTagHelper.tags(err.value.obj) == set() # there might be others, that's fine
959
960
961 def test_error_invalid_non_string_template():
962 """Ensure errors on non-string template inputs include type information."""
963 with pytest.raises(AnsibleTemplateError) as err:
964 TemplateEngine().template(...)
965
966 assert f"Type {type(...).__name__!r} is unsupported for variable storage." in err.value.message
967
968
969 def nuke_module_prefix(prefix):
970 for module_to_nuke in [m for m in sys.modules if m.startswith(prefix)]:
971 sys.modules.pop(module_to_nuke)
972
973
974 def test_template_transform_limit_exceeded(mocker: pytest_mock.MockerFixture) -> None:
975 """
976 Verify that template transforms cannot trigger an infinite loop.
977 This currently requires injecting bogus transforms to trigger the condition, but the logic is present to catch future coding errors.
978 """
979 class One:
980 def __init__(self, *args, **kwargs):
981 pass
982
983 class Two:
984 def __init__(self, *args, **kwargs):
985 pass
986
987 mocker.patch.dict(_transform._type_transform_mapping, {One: Two, Two: One})
988
989 with pytest.raises(AnsibleTemplateTransformLimitError):
990 TemplateEngine(variables=dict(limit=One())).template(TRUST.tag("{{ limit }}"))
991
992
993 def test_transform_transform_limit_exceeded(mocker: pytest_mock.MockerFixture) -> None:
994 """
995 Verify that standalone recursive transforms cannot trigger an infinite loop.
996 This currently requires injecting bogus transforms to trigger the condition, but the logic is present to catch future coding errors.
997 """
998 class One:
999 def __init__(self, *args, **kwargs):
1000 pass
1001
1002 class Two:
1003 def __init__(self, *args, **kwargs):
1004 pass
1005
1006 mocker.patch.dict(_transform._type_transform_mapping, {One: Two, Two: One})
1007
1008 with pytest.raises(AnsibleTemplateTransformLimitError):
1009 TemplateEngine().transform(One())
1010
1011
1012 def test_deprecated_dedupe_and_source():
1013 """Validate dedupe and source context behavior for deprecated item access and associated warning behavior."""
1014 # unique tag instances that share the same contents (can be tracked independently by the audit context)
1015 deprecated_string = Deprecated(msg="deprecated").tag("deprecated string")
1016 deprecated_list = Deprecated(msg="deprecated").tag([42])
1017 deprecated_dict = Deprecated(msg="deprecated").tag(dict(key="value"))
1018
1019 # a shared tag instance (cannot be tracked independently by the audit context)
1020 shared_tag_instance = Deprecated(msg="shared tag")
1021 d1 = shared_tag_instance.tag("d1")
1022 d2 = shared_tag_instance.tag("d2")
1023
1024 variables = dict(
1025 indirect1=TRUST.tag('{{ indirect2 }}'),
1026 indirect2=TRUST.tag('{{ deprecated_string }}'),
1027 deprecated_string=deprecated_string,
1028 deprecated_list=deprecated_list,
1029 deprecated_dict=deprecated_dict,
1030 d1=d1,
1031 d2=d2,
1032 ansible_deprecation_warnings=True,
1033 )
1034
1035 templar = TemplateEngine(variables=variables)
1036
1037 with _display_utils.DeferredWarningContext(variables=variables) as dwc:
1038 # The indirect access summary occurs first.
1039 # The two following direct access summaries get deduped to a single one by the warning context (but unique template value keeps distinct from indirect).
1040 # The accesses with the shared tag instance values are internally deduped by the audit context.
1041 templar.evaluate_expression(TRUST.tag("indirect1 and deprecated_list and deprecated_dict and d1 and d2"))
1042
1043 dep_warnings = dwc.get_deprecation_warnings()
1044
1045 assert len(dep_warnings) == 3
1046 assert 'deprecated_string' in _event_utils.format_event_brief_message(dep_warnings[0].event)
1047 assert 'indirect1 and deprecated_list and deprecated_dict' in _event_utils.format_event_brief_message(dep_warnings[1].event)
1048 assert 'd1 and d2' in _event_utils.format_event_brief_message(dep_warnings[2].event)
1049
1050
1051 def test_jinja_const_template_leak(template_context: TemplateContext) -> None:
1052 """Verify that _JinjaConstTemplate is present during internal templating."""
1053 with _display_utils.DeferredWarningContext(variables={}): # suppress warning from usage of embedded template
1054 with unittest.mock.patch.object(_TemplateConfig, 'allow_embedded_templates', True):
1055 assert _JinjaConstTemplate.is_tagged_on(TemplateEngine().template(TRUST.tag("{{ '{{ 1 }}' }}")))
1056
1057
1058 def test_jinja_const_template_finalized() -> None:
1059 """Verify that _JinjaConstTemplate is not present in finalized template results."""
1060 with _display_utils.DeferredWarningContext(variables={}): # suppress warning from usage of embedded template
1061 with unittest.mock.patch.object(_TemplateConfig, 'allow_embedded_templates', True):
1062 assert not _JinjaConstTemplate.is_tagged_on(TemplateEngine().template(TRUST.tag("{{ '{{ 1 }}' }}")))
1063
1064
1065 @pytest.mark.parametrize("template,expected", (
1066 ("{{ (-1).__abs__() }}", 1),
1067 ))
1068 def test_unsafe_attr_access(template: str, expected: object) -> None:
1069 """Verify that unsafe attribute access fails by default and works when explicitly configured."""
1070 assert _TemplateConfig.sandbox_mode == _SandboxMode.DEFAULT
1071
1072 with pytest.raises(AnsibleUndefinedVariable):
1073 TemplateEngine().template(TRUST.tag(template))
1074
1075 with unittest.mock.patch.object(_TemplateConfig, 'sandbox_mode', _SandboxMode.ALLOW_UNSAFE_ATTRIBUTES):
1076 assert TemplateEngine().template(TRUST.tag(template)) == expected
1077
1078
1079 def test_marker_from_test_plugin() -> None:
1080 """Verify test plugins can raise MarkerError to return a Marker, and that no warnings or deprecations are emitted."""
1081 with emits_warnings(deprecation_pattern=[], warning_pattern=[]):
1082 assert TemplateEngine(variables=dict(something=TRUST.tag("{{ nope }}"))).template(TRUST.tag("{{ (something is eq {}) is undefined }}"))
1083
1084
1085 @pytest.mark.parametrize("template,expected", (
1086 ("{{ none }}", None), # concat sees one node, NoneType result is preserved
1087 ("{% if False %}{% endif %}", None), # concat sees one node, NoneType result is preserved
1088 ("{{''}}{% if False %}{% endif %}", ""), # multiple blocks with an embedded None result, concat is in play, the result is an empty string
1089 ("hey {{ none }}", "hey "), # composite template, the result is an empty string
1090 ("{% import 'importme' as imported %}{{ imported }}", "imported template result"),
1091 ))
1092 def test_none_concat(template: str, expected: object) -> None:
1093 """Validate that None values are omitted from composite template concat."""
1094 te = TemplateEngine()
1095
1096 # set up an importable template to exercise TemplateModule code paths
1097 te.environment.loader = DictLoader(dict(importme=TRUST.tag("{{ none }}{{ 'imported template result' }}{{ none }}")))
1098
1099 assert te.template(TRUST.tag(template)) == expected
1100
1101
1102 def test_filter_generator() -> None:
1103 """Verify that filters which return a generator are converted to a list while under the filter's JinjaCallContext."""
1104 variables = dict(
1105 foo=[
1106 dict(x=1, optional_var=0),
1107 dict(x=2),
1108 ],
1109 bar=TRUST.tag("{{ foo | selectattr('optional_var', 'defined') }}"),
1110 )
1111
1112 te = TemplateEngine(variables=variables)
1113 te.template(TRUST.tag("{{ bar }}"))
1114 te.template(TRUST.tag("{{ lookup('vars', 'bar') }}"))
1115
1116
1117 def test_call_context_reset() -> None:
1118 """Ensure that new template invocations do not inherit trip behavior from running Jinja plugins."""
1119 templar = TemplateEngine(variables=dict(
1120 somevar=TRUST.tag("{{ somedict.somekey | default('ok') }}"),
1121 somedict=dict(
1122 somekey=TRUST.tag("{{ not_here }}"),
1123 )
1124 ))
1125
1126 assert templar.template(TRUST.tag("{{ lookup('vars', 'somevar') }}")) == 'ok'