Debian Codegraph @

ansible_collections/netapp/ontap/tests/unit/plugins/module_utils/ansible_mocks.py

raw
1 # (c) 2022, NetApp, Inc
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import (absolute_import, division, print_function)
5 __metaclass__ = type
6 import copy
7 import json
8 import pytest
9 import sys
10 from ansible.module_utils import basic
11 from ansible.module_utils._text import to_bytes
12
13 from ansible_collections.netapp.ontap.tests.unit.compat.mock import patch
14 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import ZAPI_DEPRECATION_MESSAGE
15
16 VERBOSE = True
17
18 if sys.version_info < (3, 11):
19 pytestmark = pytest.mark.skip("Skipping Unit Tests on 3.11")
20
21
22 def set_module_args(args):
23 """prepare arguments so that they will be picked up during module creation"""
24 args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
25 basic._ANSIBLE_ARGS = to_bytes(args) # pylint: disable=protected-access
26
27
28 class AnsibleExitJson(Exception):
29 """Exception class to be raised by module.exit_json and caught by the test case"""
30
31
32 class AnsibleFailJson(Exception):
33 """Exception class to be raised by module.fail_json and caught by the test case"""
34
35
36 def exit_json(*args, **kwargs): # pylint: disable=unused-argument
37 """function to patch over exit_json; package return data into an exception"""
38 if 'changed' not in kwargs:
39 kwargs['changed'] = False
40 raise AnsibleExitJson(kwargs)
41
42
43 def fail_json(*args, **kwargs): # pylint: disable=unused-argument
44 """function to patch over fail_json; package return data into an exception"""
45 kwargs['failed'] = True
46 raise AnsibleFailJson(kwargs)
47
48
49 WARNINGS = []
50
51
52 def warn(dummy, msg):
53 print('WARNING:', msg)
54 WARNINGS.append(msg)
55
56
57 def expect_and_capture_ansible_exception(function, exception, *args, **kwargs):
58 ''' wraps a call to a funtion in a pytest.raises context and return the exception data as a dict
59
60 function: the function to call -- without ()
61 exception: 'exit' or 'fail' to trap Ansible exceptions raised by exit_json or fail_json
62 can also take an exception to test some corner cases (eg KeyError)
63 *args, **kwargs to capture any function arguments
64 '''
65 if exception in ('fail', 'exit'):
66 exception = AnsibleFailJson if exception == 'fail' else AnsibleExitJson
67 if not (isinstance(exception, type) and issubclass(exception, Exception)):
68 raise KeyError('Error: got: %s, expecting fail, exit, or some exception' % exception)
69 with pytest.raises(exception) as exc:
70 function(*args, **kwargs)
71 if VERBOSE:
72 print('EXC:', exception, exc.value)
73 if exception in (AnsibleExitJson, AnsibleFailJson, Exception, AttributeError, KeyError, TypeError, ValueError):
74 return exc.value.args[0]
75 return exc
76
77
78 def call_main(my_main, default_args=None, module_args=None, fail=False):
79 ''' utility function to call a module main() entry point
80 my_main: main function for a module
81 default_args: a dict for the Ansible options - in general, what is accepted by all tests
82 module_args: additional options - in general what is specific to a test
83
84 call main and should raise AnsibleExitJson or AnsibleFailJson
85 '''
86 args = copy.deepcopy(default_args) if default_args else {}
87 if module_args:
88 args.update(module_args)
89 set_module_args(args)
90 return expect_and_capture_ansible_exception(my_main, 'fail' if fail else 'exit')
91
92
93 def create_module(my_module, default_args=None, module_args=None, check_mode=None, fail=False):
94 ''' utility function to create a module object
95 my_module: a class that represent an ONTAP Ansible module
96 default_args: a dict for the Ansible options - in general, what is accepted by all tests
97 module_args: additional options - in general what is specific to a test
98 check_mode: True/False - if not None, check_mode is set accordingly
99
100 returns an instance of the module
101 '''
102 args = copy.deepcopy(default_args) if default_args else {}
103 if module_args:
104 args.update(module_args)
105 set_module_args(args)
106 if fail:
107 return expect_and_capture_ansible_exception(my_module, 'fail')
108 my_module_object = my_module()
109 if check_mode is not None:
110 my_module_object.module.check_mode = check_mode
111 return my_module_object
112
113
114 def create_and_apply(my_module, default_args=None, module_args=None, fail=False, check_mode=None):
115 ''' utility function to create a module and call apply
116
117 calls create_module, then calls the apply function and checks for:
118 AnsibleExitJson exception if fail is False or not present.
119 AnsibleFailJson exception if fail is True.
120
121 see create_module for a description of the other arguments.
122 '''
123 try:
124 my_obj = create_module(my_module, default_args, module_args, check_mode)
125 except Exception as exc:
126 print('Unexpected exception returned in create_module: %s' % exc)
127 print('If expected, use create_module with fail=True.')
128 raise
129 return expect_and_capture_ansible_exception(my_obj.apply, 'fail' if fail else 'exit')
130
131
132 # using pytest natively, without unittest.TestCase
133 @pytest.fixture(autouse=True)
134 def patch_ansible():
135 with patch.multiple(basic.AnsibleModule,
136 exit_json=exit_json,
137 fail_json=fail_json,
138 warn=warn) as mocks:
139 clear_warnings()
140 # so that we get a SystemExit: 1 error (no able to read from stdin in ansible-test !)
141 # if set_module_args() was not called
142 basic._ANSIBLE_ARGS = None
143 yield mocks
144
145
146 def get_warnings():
147 return WARNINGS
148
149
150 def print_warnings(framed=True):
151 if framed:
152 sep = '-' * 7
153 title = ' WARNINGS '
154 print(sep, title, sep)
155 for warning in WARNINGS:
156 print(warning)
157 if framed:
158 sep = '-' * (7 * 2 + len(title))
159 print(sep)
160
161
162 def assert_no_warnings():
163 assert not WARNINGS
164
165
166 def assert_no_warnings_except_zapi():
167 # Deprecation message can appear more than once. Remove will only remove the first instance.
168 local_warning = list(set(WARNINGS))
169 tmp_warnings = local_warning[:]
170 for warning in tmp_warnings:
171 if warning in ZAPI_DEPRECATION_MESSAGE:
172 local_warning.remove(ZAPI_DEPRECATION_MESSAGE)
173 assert not local_warning
174
175
176 def assert_warning_was_raised(warning, partial_match=False):
177 if partial_match:
178 assert any(warning in msg for msg in WARNINGS)
179 else:
180 assert warning in WARNINGS
181
182
183 def clear_warnings():
184 global WARNINGS
185 WARNINGS = []