Debian Codegraph @

test/units/conftest.py

raw
1 # Try to globally patch Templar trust check failures to be fatal for all unit tests
2
3 from __future__ import annotations
4
5 import pytest
6 import sys
7 import typing as t
8
9 import pytest_mock
10
11 try:
12 from ansible import _internal # sets is_controller=True in controller context
13 from ansible.module_utils._internal import is_controller # allow checking is_controller
14 from ansible._internal._templating._jinja_common import _TemplateConfig
15 from ansible._internal._errors._handler import ErrorHandler, ErrorAction
16 except ImportError:
17 # likely doing only module_utils testing; ignore here and rely on test_templar::test_trust_fail_raises_in_tests to ensure the right behavior
18 pass
19 else:
20 assert _internal
21 assert is_controller
22
23 # Ensure unit tests fail when encountering untrusted templates to reduce mistakes in tests.
24 # Tests that need to ignore or warn on untrusted templates will need to override this setting.
25 _TemplateConfig.untrusted_template_handler = ErrorHandler(ErrorAction.ERROR)
26
27 from .controller_only_conftest import * # pylint: disable=wildcard-import,unused-wildcard-import
28
29 from ansible.module_utils import _internal as _module_utils_internal
30 from ansible.module_utils._internal import _traceback as _module_utils_internal_traceback
31
32
33 def pytest_configure(config: pytest.Config):
34 config.addinivalue_line("markers", "autoparam(value): metadata-driven parametrization")
35 config.addinivalue_line("markers", "allow_delazify: test will delazify the result")
36
37
38 @pytest.fixture
39 def collection_loader() -> t.Iterator[None]:
40 """
41 Provide a collection loader with no collections.
42 Useful for tests that fail without a collection loader, but that don't actually depend on collections.
43 """
44 from ansible.utils.collection_loader._collection_finder import _AnsibleCollectionFinder
45
46 _AnsibleCollectionFinder()._install()
47
48 try:
49 yield
50 finally:
51 _AnsibleCollectionFinder._remove()
52
53 for module_to_nuke in [m for m in sys.modules if m.startswith('ansible_collections')]:
54 sys.modules.pop(module_to_nuke)
55
56
57 # @pytest.fixture(autouse=True)
58 # def prevent_collection_loader_leak(request: pytest.FixtureRequest):
59 # # DTFIX-FUTURE: enable this fixture to ensure the collection loader has not "leaked"
60 # for finder in sys.meta_path:
61 # if "_AnsibleCollectionFinder" in type(finder).__name__:
62 # finder._remove()
63 # assert False, f"a finder was active before test {request.node.name}"
64 #
65 # yield
66 #
67 # for finder in sys.meta_path:
68 # if "_AnsibleCollectionFinder" in type(finder).__name__:
69 # finder._remove()
70 # assert False, f"a finder was active after test {request.node.name}"
71
72
73 def pytest_collection_finish(session: pytest.Session):
74 """
75 This hook ensures that a collection loader is not installed after test import/collection.
76 The presence of a collection loader pollutes test state in various undesirable ways.
77 """
78 for finder in sys.meta_path:
79 if "_AnsibleCollectionFinder" in type(finder).__name__:
80 assert False, "a collection loader was active after collection"
81
82
83 @pytest.fixture
84 def as_target(mocker: pytest_mock.MockerFixture) -> None:
85 """Force execution in the context of a target host instead of the controller."""
86 mocker.patch.object(_module_utils_internal, 'is_controller', False)
87 mocker.patch.object(_module_utils_internal_traceback, '_is_traceback_enabled', _module_utils_internal_traceback._is_module_traceback_enabled)