Debian Codegraph @

ansible_collections/community/hashi_vault/tests/unit/plugins/modules/conftest.py

raw
1 # Copyright (c) 2022 Brian Scholer (@briantist)
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import (absolute_import, division, print_function)
7 __metaclass__ = type
8
9 import json
10
11 import pytest
12
13 from ansible.module_utils.common.text.converters import to_bytes
14 from ansible.module_utils.common._collections_compat import MutableMapping, Sequence
15
16 from ...compat import mock
17
18
19 def pytest_configure(config):
20 config.addinivalue_line(
21 "markers", "no_ansible_module_patch: causes the patch_ansible_module fixture to have no effect"
22 )
23
24
25 @pytest.fixture
26 def module_warn():
27 return mock.MagicMock()
28
29
30 @pytest.fixture
31 def patch_ansible_module(request, module_warn):
32 def _process(param):
33 if isinstance(param, str):
34 args = param
35 _yield = args
36 return (args, _yield)
37 elif isinstance(param, MutableMapping):
38 if '_yield' in param:
39 y = param.pop('_yield')
40 _yield = dict((k, v) for k, v in param.items() if k in y)
41 else:
42 _yield = param
43
44 if 'ANSIBLE_MODULE_ARGS' not in param:
45 param = {'ANSIBLE_MODULE_ARGS': param}
46 if '_ansible_remote_tmp' not in param['ANSIBLE_MODULE_ARGS']:
47 param['ANSIBLE_MODULE_ARGS']['_ansible_remote_tmp'] = '/tmp'
48 if '_ansible_keep_remote_files' not in param['ANSIBLE_MODULE_ARGS']:
49 param['ANSIBLE_MODULE_ARGS']['_ansible_keep_remote_files'] = False
50 return (param, _yield)
51 elif isinstance(param, Sequence):
52 # First item should be a dict that serves as the base of options,
53 # use it for things that aren't being parametrized.
54 # Each of the remaining items is the name of a fixture whose name
55 # begins with opt_ (but without the opt_ prefix), and we will look those up.
56 if not isinstance(param[0], MutableMapping):
57 raise Exception('First value in patch_ansible_module array param must be a dict')
58
59 margs = param[0]
60 for fixt in param[1:]:
61 margs[fixt] = request.getfixturevalue('opt_' + fixt)
62
63 return _process(margs)
64 else:
65 raise Exception('Malformed data to the patch_ansible_module pytest fixture')
66
67 if 'no_ansible_module_patch' in request.keywords:
68 yield
69 else:
70 args, _yield = _process(request.param)
71 # TODO: in 2.10+ we can patch basic.warn instead of basic.AnsibleModule.warn
72 with mock.patch('ansible.module_utils.basic.AnsibleModule.warn', module_warn):
73 try:
74 from ansible.module_utils.testing import patch_module_args
75 except ImportError:
76 with mock.patch('ansible.module_utils.basic._ANSIBLE_ARGS', to_bytes(json.dumps(args))):
77 yield _yield
78 else:
79 with patch_module_args(args['ANSIBLE_MODULE_ARGS']):
80 yield _yield