Debian Codegraph @

ansible_collections/netapp/ontap/tests/unit/plugins/modules/test_na_ontap_restit.py

raw
1 # (c) 2021-2026, NetApp, Inc
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 ''' unit tests ONTAP Ansible module: na_ontap_cluster '''
5
6 from __future__ import (absolute_import, division, print_function)
7 __metaclass__ = type
8 import pytest
9 import sys
10
11 from ansible_collections.netapp.ontap.tests.unit.compat.mock import patch, call
12 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
13 # pylint: disable=unused-import
14 from ansible_collections.netapp.ontap.tests.unit.plugins.module_utils.ansible_mocks import set_module_args, \
15 AnsibleFailJson, AnsibleExitJson, patch_ansible
16
17 from ansible_collections.netapp.ontap.plugins.modules.na_ontap_restit \
18 import NetAppONTAPRestAPI as my_module, main as my_main # module under test
19
20 if sys.version_info < (2, 7):
21 pytestmark = pytest.mark.skip('Skipping Unit Tests on 2.6 as requests is not available')
22
23
24 SRR = {
25 # common responses
26 'is_rest': (200, dict(version=dict(generation=9, major=7, minor=0, full='dummy_9_7_0')), None),
27 'is_rest_95': (200, dict(version=dict(generation=9, major=5, minor=0, full='dummy_9_5_0')), None),
28 'is_rest_96': (200, dict(version=dict(generation=9, major=6, minor=0, full='dummy_9_6_0')), None),
29 'is_rest_97': (200, dict(version=dict(generation=9, major=7, minor=0, full='dummy_9_7_0')), None),
30 'is_zapi': (400, {}, "Unreachable"),
31 'empty_good': ({}, None, None),
32 'zero_record': (200, {'records': []}, None),
33 'job_id_record': (
34 200, {
35 'job': {
36 'uuid': '94b6e6a7-d426-11eb-ac81-00505690980f',
37 '_links': {'self': {'href': '/api/cluster/jobs/94b6e6a7-d426-11eb-ac81-00505690980f'}}},
38 'cli_output': ' Use the "job show -id 2379" command to view the status of this operation.'}, None),
39 'job_response_record': (
40 200, {
41 "uuid": "f03ccbb6-d8bb-11eb-ac81-00505690980f",
42 "description": "File Directory Security Apply Job",
43 "state": "success",
44 "message": "Complete: Operation completed successfully. File ACLs modified using policy \"policy1\" on Vserver \"GBSMNAS80LD\". File count: 0. [0]",
45 "code": 0,
46 "start_time": "2021-06-29T05:25:26-04:00",
47 "end_time": "2021-06-29T05:25:26-04:00"
48 }, None),
49 'job_response_record_running': (
50 200, {
51 "uuid": "f03ccbb6-d8bb-11eb-ac81-00505690980f",
52 "description": "File Directory Security Apply Job",
53 "state": "running",
54 "message": "Complete: Operation completed successfully. File ACLs modified using policy \"policy1\" on Vserver \"GBSMNAS80LD\". File count: 0. [0]",
55 "code": 0,
56 "start_time": "2021-06-29T05:25:26-04:00",
57 "end_time": "2021-06-29T05:25:26-04:00"
58 }, None),
59 'job_response_record_failure': (
60 200, {
61 "uuid": "f03ccbb6-d8bb-11eb-ac81-00505690980f",
62 "description": "File Directory Security Apply Job",
63 "state": "failure",
64 "message": "Forcing some error for UT.",
65 "code": 0,
66 "start_time": "2021-06-29T05:25:26-04:00",
67 "end_time": "2021-06-29T05:25:26-04:00"
68 }, None),
69 'generic_error': (500, None, "Expected error"),
70 'rest_error': (400, None, {'message': '-error_message-', 'code': '-error_code-'}),
71 'end_of_sequence': (None, None, "Unexpected call to send_request"),
72 }
73
74
75 def set_default_args(use_rest='auto'):
76 hostname = '10.10.10.10'
77 username = 'admin'
78 password = 'password'
79 api = 'abc'
80 return dict({
81 'hostname': hostname,
82 'username': username,
83 'password': password,
84 'api': api,
85 'use_rest': use_rest
86 })
87
88
89 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
90 def test_rest_run_default_get(mock_request, patch_ansible):
91 ''' if no method is given, GET is the default '''
92 args = dict(set_default_args())
93 set_module_args(args)
94 mock_request.side_effect = [
95 SRR['empty_good'],
96 SRR['end_of_sequence']
97 ]
98 my_obj = my_module()
99 with pytest.raises(AnsibleExitJson) as exc:
100 my_obj.apply()
101 assert exc.value.args[0]['changed'] is False
102 print(mock_request.mock_calls)
103 assert len(mock_request.mock_calls) == 1
104
105
106 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
107 def test_rest_run_any(mock_request, patch_ansible):
108 ''' We don't validate the method name, so ANYthing goes '''
109 args = dict(set_default_args())
110 args['method'] = 'ANY'
111 args['body'] = {'bkey1': 'bitem1', 'bkey2': 'bitem2'}
112 args['query'] = {'qkey1': 'qitem1', 'qkey2': 'qitem2'}
113 args['files'] = {'fkey1': 'fitem1', 'fkey2': 'fitem2'}
114 set_module_args(args)
115 mock_request.side_effect = [
116 SRR['empty_good'],
117 SRR['end_of_sequence']
118 ]
119 my_obj = my_module()
120 with pytest.raises(AnsibleExitJson) as exc:
121 my_obj.apply()
122 assert exc.value.args[0]['changed'] is True
123 print(mock_request.mock_calls)
124 assert len(mock_request.mock_calls) == 1
125 headers = my_obj.rest_api.build_headers(accept='application/json')
126 expected_call = call('ANY', 'abc', args['query'], args['body'], headers, args['files'])
127 assert expected_call in mock_request.mock_calls
128
129
130 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
131 def test_rest_negative_run_any_rest_error(mock_request, patch_ansible):
132 ''' We don't validate the method name, so ANYthing goes '''
133 args = dict(set_default_args())
134 args['method'] = 'ANY'
135 args['body'] = {'bkey1': 'bitem1', 'bkey2': 'bitem2'}
136 args['query'] = {'qkey1': 'qitem1', 'qkey2': 'qitem2'}
137 set_module_args(args)
138 mock_request.side_effect = [
139 SRR['rest_error'],
140 SRR['end_of_sequence']
141 ]
142 my_obj = my_module()
143 with pytest.raises(AnsibleFailJson) as exc:
144 my_obj.apply()
145 msg = "Error when calling 'abc': check error_message and error_code for details."
146 assert msg == exc.value.args[0]['msg']
147 assert '-error_message-' == exc.value.args[0]['error_message']
148 assert '-error_code-' == exc.value.args[0]['error_code']
149
150
151 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
152 def test_rest_negative_run_any_other_error(mock_request, patch_ansible):
153 ''' We don't validate the method name, so ANYthing goes '''
154 args = dict(set_default_args())
155 args['method'] = 'ANY'
156 args['body'] = {'bkey1': 'bitem1', 'bkey2': 'bitem2'}
157 args['query'] = {'qkey1': 'qitem1', 'qkey2': 'qitem2'}
158 set_module_args(args)
159 mock_request.side_effect = [
160 SRR['generic_error'],
161 SRR['end_of_sequence']
162 ]
163 my_obj = my_module()
164 with pytest.raises(AnsibleFailJson) as exc:
165 my_obj.apply()
166 msg = "Error when calling 'abc': Expected error"
167 assert msg == exc.value.args[0]['msg']
168 assert 'Expected error' == exc.value.args[0]['error_message']
169 assert exc.value.args[0]['error_code'] is None
170
171
172 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
173 def test_rest_run_post_async_no_job(mock_request, patch_ansible):
174 ''' POST async, but returns immediately '''
175 args = dict(set_default_args())
176 args['method'] = 'POST'
177 args['body'] = {'bkey1': 'bitem1', 'bkey2': 'bitem2'}
178 args['query'] = {'qkey1': 'qitem1', 'qkey2': 'qitem2'}
179 args['wait_for_completion'] = True
180 set_module_args(args)
181 mock_request.side_effect = [
182 SRR['empty_good'],
183 SRR['end_of_sequence']
184 ]
185 my_obj = my_module()
186 with pytest.raises(AnsibleExitJson) as exc:
187 my_obj.apply()
188 assert exc.value.args[0]['changed'] is True
189 print(mock_request.mock_calls)
190 assert len(mock_request.mock_calls) == 1
191 headers = my_obj.rest_api.build_headers(accept='application/json')
192 args['query'].update({'return_timeout': 30})
193 expected_call = call('POST', 'abc', args['query'], json=args['body'], headers=headers, files=None)
194 assert expected_call in mock_request.mock_calls
195
196
197 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
198 def test_rest_run_post_async_with_job(mock_request, patch_ansible):
199 ''' POST async, but returns immediately '''
200 args = dict(set_default_args())
201 args['method'] = 'POST'
202 args['body'] = {'bkey1': 'bitem1', 'bkey2': 'bitem2'}
203 args['query'] = {'qkey1': 'qitem1', 'qkey2': 'qitem2'}
204 args['wait_for_completion'] = True
205 set_module_args(args)
206 mock_request.side_effect = [
207 SRR['job_id_record'],
208 SRR['job_response_record'],
209 SRR['end_of_sequence']
210 ]
211 my_obj = my_module()
212 with pytest.raises(AnsibleExitJson) as exc:
213 my_obj.apply()
214 assert exc.value.args[0]['changed'] is True
215 print(mock_request.mock_calls)
216 assert len(mock_request.mock_calls) == 2
217 headers = my_obj.rest_api.build_headers(accept='application/json')
218 args['query'].update({'return_timeout': 30})
219 expected_call = call('POST', 'abc', args['query'], json=args['body'], headers=headers, files=None)
220 assert expected_call in mock_request.mock_calls
221
222
223 # patch time to not wait between job retries
224 @patch('time.sleep')
225 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
226 def test_rest_run_patch_async_with_job_loop(mock_request, mock_sleep, patch_ansible):
227 ''' POST async, but returns immediately '''
228 args = dict(set_default_args())
229 args['method'] = 'PATCH'
230 args['body'] = {'bkey1': 'bitem1', 'bkey2': 'bitem2'}
231 args['query'] = {'qkey1': 'qitem1', 'qkey2': 'qitem2'}
232 args['wait_for_completion'] = True
233 set_module_args(args)
234 mock_request.side_effect = [
235 SRR['job_id_record'],
236 SRR['job_response_record_running'],
237 SRR['job_response_record'],
238 SRR['end_of_sequence']
239 ]
240 my_obj = my_module()
241 with pytest.raises(AnsibleExitJson) as exc:
242 my_obj.apply()
243 assert exc.value.args[0]['changed'] is True
244 print(mock_request.mock_calls)
245 assert len(mock_request.mock_calls) == 3
246 headers = my_obj.rest_api.build_headers(accept='application/json')
247 args['query'].update({'return_timeout': 30})
248 expected_call = call('PATCH', 'abc', args['query'], json=args['body'], headers=headers, files=None)
249 assert expected_call in mock_request.mock_calls
250
251
252 @patch('time.sleep')
253 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
254 def test_rest_run_negative_delete(mock_request, mock_sleep, patch_ansible):
255 ''' POST async, but returns immediately '''
256 args = dict(set_default_args())
257 args['method'] = 'DELETE'
258 args['body'] = {'bkey1': 'bitem1', 'bkey2': 'bitem2'}
259 args['query'] = {'qkey1': 'qitem1', 'qkey2': 'qitem2'}
260 args['wait_for_completion'] = True
261 set_module_args(args)
262 mock_request.side_effect = [
263 SRR['job_id_record'],
264 SRR['job_response_record_running'],
265 SRR['job_response_record_failure'],
266 SRR['end_of_sequence']
267 ]
268 my_obj = my_module()
269 with pytest.raises(AnsibleFailJson) as exc:
270 my_obj.apply()
271 msg = "Error when calling 'abc': Forcing some error for UT."
272 assert msg == exc.value.args[0]['msg']
273 assert 'Forcing some error for UT.' == exc.value.args[0]['error_message']
274 assert exc.value.args[0]['error_code'] is None
275 print(mock_request.mock_calls)
276 assert len(mock_request.mock_calls) == 3
277 headers = my_obj.rest_api.build_headers(accept='application/json')
278 args['query'].update({'return_timeout': 30})
279 expected_call = call('DELETE', 'abc', args['query'], json=None, headers=headers)
280 assert expected_call in mock_request.mock_calls
281
282
283 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
284 def test_rest_run_any_async(mock_request, patch_ansible):
285 ''' We don't validate the method name, so ANYthing goes '''
286 args = dict(set_default_args())
287 args['method'] = 'ANY'
288 args['body'] = {'bkey1': 'bitem1', 'bkey2': 'bitem2'}
289 args['query'] = {'qkey1': 'qitem1', 'qkey2': 'qitem2'}
290 args['files'] = {'fkey1': 'fitem1', 'fkey2': 'fitem2'}
291 args['wait_for_completion'] = True
292 set_module_args(args)
293 mock_request.side_effect = [
294 SRR['empty_good'],
295 SRR['end_of_sequence']
296 ]
297 my_obj = my_module()
298 with pytest.raises(AnsibleExitJson) as exc:
299 my_obj.apply()
300 assert exc.value.args[0]['changed'] is True
301 print(mock_request.mock_calls)
302 assert len(mock_request.mock_calls) == 1
303 headers = my_obj.rest_api.build_headers(accept='application/json')
304 expected_call = call('ANY', 'abc', args['query'], args['body'], headers, args['files'])
305 assert expected_call in mock_request.mock_calls
306
307
308 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
309 def test_rest_run_main(mock_request, patch_ansible):
310 ''' We don't validate the method name, so ANYthing goes '''
311 args = dict(set_default_args())
312 args['method'] = 'ANY'
313 args['body'] = {'bkey1': 'bitem1', 'bkey2': 'bitem2'}
314 args['query'] = {'qkey1': 'qitem1', 'qkey2': 'qitem2'}
315 args['wait_for_completion'] = True
316 set_module_args(args)
317 mock_request.side_effect = [
318 SRR['empty_good'],
319 SRR['end_of_sequence']
320 ]
321 with pytest.raises(AnsibleExitJson) as exc:
322 my_main()
323 assert exc.value.args[0]['changed'] is True
324 print(mock_request.mock_calls)
325 assert len(mock_request.mock_calls) == 1
326
327
328 @patch('ansible_collections.netapp.ontap.plugins.module_utils.netapp.OntapRestAPI.send_request')
329 def test_rest_build_headers(mock_request, patch_ansible):
330 ''' create cluster '''
331 args = dict(set_default_args())
332 set_module_args(args)
333 my_obj = my_module()
334 headers = my_obj.build_headers()
335 # TODO: in UT (and only in UT) module._name is not set properly. It shows as basic.py instead of 'na_ontap_restit'
336 assert headers == {'X-Dot-Client-App': 'basic.py/%s' % netapp_utils.COLLECTION_VERSION, 'accept': 'application/json'}
337 args['hal_linking'] = True
338 set_module_args(args)
339 my_obj = my_module()
340 headers = my_obj.build_headers()
341 assert headers == {'X-Dot-Client-App': 'basic.py/%s' % netapp_utils.COLLECTION_VERSION, 'accept': 'application/hal+json'}
342 # Accept header
343 args['accept_header'] = "multipart/form-data"
344 set_module_args(args)
345 my_obj = my_module()
346 headers = my_obj.build_headers()
347 assert headers == {'X-Dot-Client-App': 'basic.py/%s' % netapp_utils.COLLECTION_VERSION, 'accept': 'multipart/form-data'}