Debian Codegraph @

test/units/template/test_template.py

raw
1 from __future__ import annotations
2
3 import io
4 import keyword
5 import pathlib
6
7 import typing as t
8
9 import pytest
10 import pytest_mock
11
12 from contextlib import nullcontext
13
14 from ansible import constants
15 from ansible import errors as _errors
16 from ansible import template as _template
17 from ansible._internal._templating import _engine, _jinja_bits
18 from ansible._internal._templating._jinja_common import UndefinedMarker
19 from ansible.errors import AnsibleUndefinedVariable
20 from ansible.module_utils._internal._datatag import NotTaggableError
21 from ansible.template import Templar, trust_as_template, is_trusted_as_template
22 from ansible._internal._datatag._tags import TrustedAsTemplate
23 from ansible._internal._templating import _lazy_containers
24
25 from ..test_utils.controller.display import emits_warnings
26
27 TRUST = TrustedAsTemplate()
28
29
30 def test_templar_do_template_trusted_template_str() -> None:
31 """Verify `Templar.do_template` processes a trusted template and emits a deprecation warning."""
32 data = TRUST.tag('{{ 1 }}')
33
34 with emits_warnings(deprecation_pattern='do_template.* is deprecated'):
35 result = Templar().do_template(data)
36
37 assert result == 1
38
39
40 def test_templar_do_template_non_str() -> None:
41 """Verify `Templar.do_template` returns non-string inputs as-is and emits a deprecation warning."""
42 trusted_template = TRUST.tag('{{ 1 }}')
43 data = dict(value=trusted_template)
44
45 with emits_warnings(deprecation_pattern='do_template.* is deprecated'):
46 result = Templar().do_template(data)
47
48 assert result is data
49 assert result == dict(value=trusted_template)
50 assert result['value'] is trusted_template
51
52
53 @pytest.mark.parametrize("value, result", (
54 (TRUST.tag('{{ 1 )}'), True),
55 ('{{ 1 }}', False),
56 (TRUST.tag('{{ invalid'), True),
57 (dict(value=TRUST.tag('{{ invalid')), True),
58 ))
59 def test_is_template(value: t.Any, result: bool) -> None:
60 """Verify `Templar.is_template` works as expected."""
61 assert Templar().is_template(value) is result
62
63
64 @pytest.mark.parametrize("value, overrides, result", (
65 ('foo {{ 123 }} bar', {}, True),
66 ('}}', {}, False),
67 ('<< blah >>', dict(variable_start_string='<<', variable_end_string='>>'), True),
68 ))
69 def test_is_possibly_template(value: t.Any, overrides: dict[str, t.Any], result: bool) -> None:
70 templar = Templar()
71 assert templar.is_possibly_template(value, overrides) is result
72
73
74 def test_is_possibly_template_override_merge() -> None:
75 """Verify override merge in `Templar.is_possibly_template` works as expected."""
76 templar = Templar()
77
78 with templar.set_temporary_context(variable_start_string='<<'):
79 assert templar.is_possibly_template('{{ nope }}') is False # temporary global override
80 assert templar.is_possibly_template('<< yep >>') is True # temporary global override
81 assert templar.is_possibly_template('<< nope >>', overrides=dict(variable_start_string='!!')) is False # local override masks global
82 assert templar.is_possibly_template('<< !!yep >>', overrides=dict(variable_start_string='!!')) is True # local override masks global
83
84
85 def test_templar_template_non_template_str() -> None:
86 """Verify `Templar.template` returns non-template strings as-is."""
87 data = TRUST.tag('hello')
88 result = Templar().template(data)
89
90 assert result is data
91
92
93 def test_templar_template_untrusted_template() -> None:
94 """
95 Verify `Templar.template` on an untrusted template triggers an exception.
96 The exception is due to unit tests setting the default trust behavior to error on untrusted templates, the default is to warn instead.
97 """
98 templar = Templar()
99 data = '{{ 1 }}'
100
101 with pytest.raises(_errors.TemplateTrustCheckFailedError):
102 templar.template(data)
103
104
105 def test_templar_template_fail_on_undefined_truthy_falsey() -> None:
106 """Verify `fail_on_undefined` compat behaviors behave as expected."""
107 template = TRUST.tag('{{ bogusvar }}')
108
109 with emits_warnings(deprecation_pattern='Falling back to `True` for `fail_on_undefined'), pytest.raises(_errors.AnsibleUndefinedVariable):
110 # fail_on_undefined None == True + dep warning
111 Templar().template(template, fail_on_undefined=None) # type: ignore
112
113 assert Templar().template(template, fail_on_undefined=False) is template
114
115 with pytest.raises(_errors.AnsibleUndefinedVariable):
116 Templar().template(template, fail_on_undefined=1) # type: ignore
117
118 assert Templar().template(template, fail_on_undefined=0) is template # type: ignore
119
120
121 @pytest.mark.parametrize("template, fail_on_undefined, result", (
122 ("somevar", True, "somevar value"), # success, starts with identifier that's a valid var
123 ("123 | int", True, 123), # success, has filter
124 ("bogusvar.somevar", True, "bogusvar.somevar"), # fail silently, starts with identifier that is not a var, so no-op
125 ("somevar.bogusvar", True, _errors.AnsibleUndefinedVariable), # fail with exception, starts with valid var, but the overall expression results in undefined
126 ("somevar.bogusvar", False, "somevar.bogusvar"), # fail silently, starts with valid var, but the overall expression results in undefined
127 ("1notavar", True, "1notavar"), # fail silently, does not start with a valid identifier
128 ("somevar | notafilter", True, _errors.AnsibleTemplateError), # fail with exception, has a filter-looking expression that is invalid
129 ))
130 def test_templar_template_convert_bare(template: str, fail_on_undefined: bool, result: t.Any) -> None:
131 """Verify the `convert_bare` selection heuristics behave properly."""
132 with emits_warnings(deprecation_pattern='convert_bare.* is deprecated'):
133 with pytest.raises(result) if isinstance(result, type) and issubclass(result, Exception) else nullcontext():
134 assert Templar(
135 variables=dict(somevar='somevar value'),
136 ).template(TRUST.tag(template), convert_bare=True, fail_on_undefined=fail_on_undefined) == result
137
138
139 def test_templar_template_convert_bare_truthy_falsey() -> None:
140 templar = Templar(variables=dict(somevar=1))
141 template = TRUST.tag('somevar')
142
143 assert templar.template(template, convert_bare=1) == 1 # type: ignore
144 assert templar.template(template, convert_bare=0) == 'somevar' # type: ignore
145
146
147 def test_templar_template_convert_data() -> None:
148 with emits_warnings(deprecation_pattern='convert_data.* is deprecated'):
149 assert Templar().template(TRUST.tag("{{123}}"), convert_data=True) == 123
150
151
152 def test_templar_template_disable_lookups() -> None:
153 with emits_warnings(deprecation_pattern='disable_lookups.* is deprecated'):
154 assert Templar().template(TRUST.tag("{{lookup('list', [1,2])}}"), disable_lookups=True) == [1, 2]
155
156
157 def test_resolve_variable_expression() -> None:
158 assert Templar().resolve_variable_expression('a_local', local_variables=dict(a_local=1)) == 1
159
160
161 def test_evaluate_expression() -> None:
162 assert Templar().evaluate_expression(TRUST.tag('a_local'), local_variables=dict(a_local=1)) == 1
163
164
165 def test_evaluate_conditional() -> None:
166 assert Templar().evaluate_conditional(True) is True
167
168
169 def test_from_template_engine() -> None:
170 engine = _engine.TemplateEngine()
171 templar = Templar._from_template_engine(engine)
172
173 assert templar._engine is not engine
174 assert isinstance(templar._engine, _engine.TemplateEngine)
175 assert templar._overrides is _engine.TemplateOverrides.DEFAULT
176
177
178 def test_basedir() -> None:
179 templar = Templar()
180
181 assert templar.basedir == templar._engine.basedir
182
183
184 def test_environment() -> None:
185 templar = Templar()
186
187 with emits_warnings(deprecation_pattern='environment.* is deprecated'):
188 assert templar.environment is templar._engine.environment
189
190
191 def test_available_variables() -> None:
192 variables: _template._VariableContainer = dict()
193 templar = Templar(variables=variables)
194
195 assert variables is templar.available_variables
196 assert templar.available_variables is templar._engine.available_variables
197
198 with emits_warnings(deprecation_pattern='_available_variables.* internal attribute is deprecated'):
199 assert variables is templar._available_variables
200
201 variables = dict(a=1)
202 templar.available_variables = variables
203
204 assert templar.available_variables is variables
205 assert templar._available_variables is variables
206 assert templar._engine.available_variables is variables
207
208
209 def test_loader() -> None:
210 templar = Templar()
211
212 with emits_warnings(deprecation_pattern='_loader.* is deprecated'):
213 assert templar._loader is templar._engine._loader
214
215
216 def test_copy_with_new_env_environment_class() -> None:
217 with emits_warnings(deprecation_pattern='environment_class.* is ignored'):
218 Templar().copy_with_new_env(environment_class=_jinja_bits.AnsibleEnvironment)
219
220
221 def test_copy_with_new_env_overrides() -> None:
222 with emits_warnings(deprecation_pattern='overrides.*copy_with_new_env.* is deprecated'):
223 assert Templar().copy_with_new_env(variable_start_string='!!').template(TRUST.tag('!! 1 }}')) == 1
224
225
226 def test_copy_with_new_env_invalid_overrides() -> None:
227 with emits_warnings(deprecation_pattern='overrides.* is deprecated'):
228 with pytest.raises(TypeError, match='variable_start_string must be'):
229 Templar().copy_with_new_env(variable_start_string=1)
230
231
232 def test_copy_with_new_env_available_variables() -> None:
233 templar = Templar()
234 new_variables: _template._VariableContainer = {}
235
236 assert templar.available_variables == {} # trigger lazy creation of available_variables
237 assert templar.copy_with_new_env().available_variables is templar.available_variables
238 assert templar.copy_with_new_env(available_variables={}).available_variables is not templar.available_variables
239 assert templar.copy_with_new_env(available_variables=new_variables).available_variables is new_variables
240
241
242 def test_copy_with_new_searchpath() -> None:
243 assert Templar().copy_with_new_env(searchpath='hello')._engine.environment.loader.searchpath == 'hello'
244
245
246 def test_set_temporary_context_overrides() -> None:
247 templar = Templar()
248
249 with emits_warnings(deprecation_pattern='set_temporary_context.* is deprecated'):
250 with templar.set_temporary_context(variable_start_string='!!'):
251 assert templar.template(TRUST.tag('!! 1 }}')) == 1
252
253
254 def test_set_temporary_context_searchpath() -> None:
255 templar = Templar()
256
257 with templar.set_temporary_context(searchpath='hello'):
258 assert templar._engine.environment.loader.searchpath == 'hello'
259
260
261 def test_set_temporary_context_available_variables() -> None:
262 templar = Templar()
263 available_variables = templar.available_variables
264 new_variables: _template._VariableContainer = {}
265
266 assert templar.available_variables == {}
267
268 with templar.set_temporary_context():
269 assert templar.available_variables is available_variables
270
271 with templar.set_temporary_context(available_variables={}):
272 assert templar.available_variables is not available_variables
273
274 with templar.set_temporary_context(available_variables=new_variables):
275 assert templar.available_variables is new_variables
276
277
278 class CustomStr(str): ...
279
280
281 @pytest.mark.parametrize("value", (
282 "yep",
283 lambda tmppath: pathlib.Path(tmppath / "afile").open("w"),
284 io.StringIO("blee"),
285 io.BytesIO(b"blee"),
286 ))
287 def test_trust_as_template(value: str | io.IOBase, tmp_path: pytest.TempPathFactory) -> None:
288 """Validate expected success behavior for `trust_value`."""
289 if callable(value):
290 value = value(tmp_path)
291
292 result = trust_as_template(value)
293
294 assert result is not value
295 assert TrustedAsTemplate.is_tagged_on(result)
296 assert isinstance(result, type(value))
297 assert is_trusted_as_template(result)
298
299
300 @pytest.mark.parametrize("value", (
301 None,
302 123,
303 dict(x=TrustedAsTemplate().tag("nope")),
304 [123],
305 ))
306 def test_not_is_trusted_as_template(value: object) -> None:
307 """Validate that types incorrectly tagged with trust are not reported as trusted."""
308 result = TrustedAsTemplate().tag(value) # force application of trust
309
310 assert not is_trusted_as_template(value)
311 assert not is_trusted_as_template(result)
312
313
314 @pytest.mark.parametrize("value, error_type, error_pattern", (
315 (123, TypeError, "cannot be applied to"),
316 (CustomStr("hey"), NotTaggableError, "is not taggable"),
317 ))
318 def test_trust_as_template_errors(value: object, error_type: t.Type[Exception], error_pattern: str | None) -> None:
319 """Validate expected error behavior for `trust_value`."""
320 with pytest.raises(error_type, match=error_pattern):
321 trust_as_template(value) # type: ignore
322
323
324 def test_templar_finalize_lazy() -> None:
325 """Ensure that containers returned via the `Templar.template` public API shim are always finalized, even under a TemplateContext."""
326 variables = dict(
327 indirect=TRUST.tag('{{ to_lazy_dict }}'),
328 to_lazy_dict=dict(t1=TRUST.tag('{{ "t1value" }}'), t2=TRUST.tag('{{ "t2value" }}'), scalar=42),
329 )
330
331 templar = _template.Templar(variables=variables)
332
333 with _engine.TemplateContext(template_value="bogus", templar=templar._engine, options=_engine.TemplateOptions.DEFAULT):
334 template = TRUST.tag('{{ indirect }}')
335
336 # self-test to ensure that this test would fail against the engine by default
337 assert type(templar._engine.template(template)) is _lazy_containers._AnsibleLazyTemplateDict # pylint: disable=unidiomatic-typecheck
338
339 result = templar.template(template)
340
341 assert type(result) is dict # pylint: disable=unidiomatic-typecheck
342 assert result['t1'] == 't1value'
343 assert result['t2'] == 't2value'
344 assert result['scalar'] == 42
345
346
347 def test_templar_finalize_undefined() -> None:
348 """Ensure that undefined values returned via the `Templar.template` public API are always finalized, even under a TemplateContext."""
349 templar = _template.Templar()
350
351 with _engine.TemplateContext(template_value="bogus", templar=templar._engine, options=_engine.TemplateOptions.DEFAULT):
352 undef_template = TRUST.tag('{{ with_undefined }}')
353
354 # self-test to ensure that this test would fail against the engine by default
355 assert isinstance(templar._engine.template(undef_template), UndefinedMarker)
356
357 with pytest.raises(AnsibleUndefinedVariable):
358 templar.template(undef_template)
359
360
361 def test_set_temporary_context_with_none() -> None:
362 """Verify that `set_temporary_context` ignores `None` overrides."""
363 templar = _template.Templar()
364
365 with templar.set_temporary_context(variable_start_string=None):
366 assert templar.template(trust_as_template('{{ True }}')) is True
367
368
369 def test_copy_with_new_env_with_none() -> None:
370 """Verify that `copy_with_new_env` ignores `None` overrides."""
371 templar = _template.Templar()
372
373 copied = templar.copy_with_new_env(variable_start_string=None)
374
375 assert copied.template(trust_as_template('{{ True }}')) is True
376
377
378 def test_generate_ansible_template_vars(mocker: pytest_mock.MockerFixture, tmp_path: pathlib.Path) -> None:
379 """Verify public API passes through ansible_managed."""
380 mocker.patch.object(constants.config, 'get_config_value', return_value='value from config')
381
382 tvars = _template.generate_ansible_template_vars(path="path", fullpath=str(tmp_path), dest_path=str(tmp_path))
383
384 assert tvars['ansible_managed'] == 'value from config'
385
386
387 _ALLOWED_PYTHON_KEYWORDS = sorted(set(keyword.kwlist) - _jinja_bits.JINJA_KEYWORDS)
388 """Python keywords which Jinja allows as variable names."""
389
390
391 @pytest.mark.parametrize("keyword_name", _ALLOWED_PYTHON_KEYWORDS)
392 def test_set_get_keyword(keyword_name: str) -> None:
393 """Verify Python keywords that are not Jinja keywords can be freely used to set and get variables in templates."""
394 template_set_get = TRUST.tag(f"{{% set {keyword_name} = 42 %}}{{{{ {keyword_name} }}}}")
395
396 assert Templar().template(template_set_get) == 42
397
398
399 @pytest.mark.parametrize("keyword_name", _ALLOWED_PYTHON_KEYWORDS)
400 def test_if_get_keyword(keyword_name: str) -> None:
401 """Verify Python keywords that are not Jinja keywords can be freely used as variables in templates and template conditionals."""
402 template_set_get = TRUST.tag(f"{{% if {keyword_name} == 42 %}}{{{{ {keyword_name} }}}}{{% endif %}}")
403
404 assert Templar(variables={keyword_name: 42}).template(template_set_get) == 42