Debian Codegraph @

test/units/_internal/templating/conftest.py

raw
1 from __future__ import annotations
2
3 import typing as t
4
5 import pytest
6
7 from ansible.errors import AnsibleError
8 from ansible.module_utils.common._utils import get_all_subclasses
9 from ansible.module_utils._internal import _messages
10 from ansible._internal._templating._jinja_common import Marker, TruncationMarker, CapturedExceptionMarker, VaultExceptionMarker
11 from ansible._internal._templating._engine import TemplateEngine, TemplateOptions
12 from ansible._internal._templating._utils import TemplateContext
13
14
15 @pytest.fixture
16 def template_context() -> t.Iterator[TemplateContext]:
17 """A fixture that provides a TemplateContext for the duration of a test."""
18 with TemplateContext(template_value=None, templar=TemplateEngine(), options=TemplateOptions.DEFAULT, stop_on_template=False) as ctx:
19 yield ctx
20
21
22 def get_concrete_marker_types() -> list[type[Marker]]:
23 """Return a sorted list of Marker and its derived types."""
24 return sorted(get_all_subclasses(Marker, include_abstract=False, consider_self=True), key=lambda au: au.__name__)
25
26
27 @pytest.fixture(params=get_concrete_marker_types())
28 def marker(request, template_context: TemplateContext) -> t.Iterator[Marker]:
29 """
30 A multiplying parameterized fixture that will yield an instance of each Marker-derived type.
31 Depends on the template_context fixture, since these types can only be created under templating.
32 """
33 request_type = request.param
34
35 if issubclass(request_type, TruncationMarker):
36 yield request_type()
37 elif issubclass(request_type, VaultExceptionMarker):
38 yield VaultExceptionMarker(ciphertext='a ciphertext', event=_messages.Event(msg='a msg'))
39 elif issubclass(request_type, CapturedExceptionMarker):
40 try:
41 try:
42 raise Exception('bang')
43 except Exception as ex:
44 defer = ex
45
46 raise AnsibleError('big bang') from defer # pylint: disable=used-before-assignment # false positive
47 except Exception as ex2:
48 yield request_type(ex2)
49 else:
50 yield request_type(hint="a hint", obj="obj", name="name")