Debian Codegraph @

ansible_collections/community/sap_libs/tests/unit/plugins/modules/utils.py

raw
1 #!/usr/bin/env python
2
3 # Copyright (c) 2022-2026 The Project Contributors.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # For a detailed list of copyright holders and contribution history,
18 # please refer to the CONTRIBUTORS.md file in the project root.
19
20 from __future__ import (absolute_import, division, print_function)
21 __metaclass__ = type
22
23 import json
24 import contextlib
25
26 from unittest import TestCase
27 from unittest.mock import patch
28 from ansible.module_utils import basic
29 from ansible.module_utils.common.text.converters import to_bytes
30
31
32 @contextlib.contextmanager
33 def set_module_args(args):
34 """
35 Context manager that sets module arguments for AnsibleModule
36 """
37 if '_ansible_remote_tmp' not in args:
38 args['_ansible_remote_tmp'] = '/tmp'
39 if '_ansible_keep_remote_files' not in args:
40 args['_ansible_keep_remote_files'] = False
41
42 try:
43 from ansible.module_utils.testing import patch_module_args
44 except ImportError:
45 # Before ansible-core 2.19, this was the way to go:
46 serialized_args = to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': args}))
47 with patch.object(basic, '_ANSIBLE_ARGS', serialized_args):
48 yield
49 else:
50 with patch_module_args(args):
51 yield
52
53
54 class AnsibleExitJson(Exception):
55 pass
56
57
58 class AnsibleFailJson(Exception):
59 pass
60
61
62 def exit_json(*args, **kwargs):
63 if 'changed' not in kwargs:
64 kwargs['changed'] = False
65 raise AnsibleExitJson(kwargs)
66
67
68 def fail_json(*args, **kwargs):
69 kwargs['failed'] = True
70 raise AnsibleFailJson(kwargs)
71
72
73 class ModuleTestCase(TestCase):
74
75 def setUp(self):
76 self.mock_module = patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json)
77 self.mock_module.start()
78 self.mock_sleep = patch('time.sleep')
79 self.mock_sleep.start()
80 self.addCleanup(self.mock_module.stop)
81 self.addCleanup(self.mock_sleep.stop)