| 1 |
""" |
| 2 |
Utilities to support unit testing of Ansible Python modules. |
| 3 |
Not supported for use cases other than testing. |
| 4 |
""" |
| 5 |
|
| 6 |
from __future__ import annotations as _annotations |
| 7 |
|
| 8 |
import contextlib as _contextlib |
| 9 |
import json as _json |
| 10 |
import typing as _t |
| 11 |
|
| 12 |
from unittest import mock as _mock |
| 13 |
|
| 14 |
from ansible.module_utils.common import json as _common_json |
| 15 |
from . import basic as _basic |
| 16 |
|
| 17 |
|
| 18 |
@_contextlib.contextmanager |
| 19 |
def patch_module_args(args: dict[str, _t.Any] | None = None) -> _t.Iterator[None]: |
| 20 |
"""Expose the given module args to `AnsibleModule` instances created within this context.""" |
| 21 |
if not isinstance(args, (dict, type(None))): |
| 22 |
raise TypeError("The `args` arg must be a dict or None.") |
| 23 |
|
| 24 |
args = dict(ANSIBLE_MODULE_ARGS=args or {}) |
| 25 |
profile = 'legacy' # this should be configurable in the future, once the profile feature is more fully baked |
| 26 |
|
| 27 |
encoder = _common_json.get_module_encoder(profile, _common_json.Direction.CONTROLLER_TO_MODULE) |
| 28 |
args = _json.dumps(args, cls=encoder).encode() |
| 29 |
|
| 30 |
with _mock.patch.object(_basic, '_ANSIBLE_ARGS', args), _mock.patch.object(_basic, '_ANSIBLE_PROFILE', profile): |
| 31 |
yield |