Debian Codegraph @

test/units/mock/module.py

raw
1 """Support fixtures for testing Ansible modules."""
2
3 from __future__ import annotations
4
5 from ansible.module_utils._internal import _traceback
6 from ansible.module_utils.common import warnings
7
8 import pytest
9
10
11 class ModuleEnvMocker:
12 """
13 A Swiss Army Knife mock fixture for target-side environments (e.g., modules, module_utils).
14
15 Using this fixture automatically applies a number of default patches, and offers tests a one-stop
16 fixture to configure a number of others.
17
18 Default behaviors:
19 * Warnings and deprecations are cleared.
20 * Traceback collection is disabled.
21 """
22
23 def __init__(self, mp: pytest.MonkeyPatch):
24 self._mp = mp
25 self.reset_warnings()
26 self.reset_deprecations()
27 self.set_traceback_config()
28
29 def set_traceback_config(self, value: list[_traceback.TracebackEvent] | None = None) -> None:
30 """Accepts a list of TracebackEvent values to enable."""
31 self._mp.setattr(_traceback, '_module_tracebacks_enabled_events', value or [])
32
33 def reset_warnings(self) -> None:
34 """Clears accumulated target-side warnings."""
35 self._mp.setattr(warnings, '_global_warnings', {})
36
37 def reset_deprecations(self) -> None:
38 """Clears accumulated target-side deprecation warnings."""
39 self._mp.setattr(warnings, '_global_deprecations', {})
40
41
42 @pytest.fixture
43 def module_env_mocker(monkeypatch: pytest.MonkeyPatch) -> ModuleEnvMocker:
44 """Provides a ModuleEnvMocker instance that allows configurable simulation of an Ansible Python module runtime environment."""
45 return ModuleEnvMocker(monkeypatch)