Debian Codegraph @

ansible_collections/netapp/cloudmanager/tests/unit/plugins/module_utils/test_netapp.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright (c) 2021, Laurent Nicolas <[email protected]>
8 # All rights reserved.
9 #
10 # Redistribution and use in source and binary forms, with or without modification,
11 # are permitted provided that the following conditions are met:
12 #
13 # * Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # * Redistributions in binary form must reproduce the above copyright notice,
16 # this list of conditions and the following disclaimer in the documentation
17 # and/or other materials provided with the distribution.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 """ unit tests for module_utils netapp.py
30
31 Provides wrappers for cloudmanager REST APIs
32 """
33
34 from __future__ import (absolute_import, division, print_function)
35 __metaclass__ = type
36
37 # import copy # for deepcopy
38 import json
39 import pytest
40 import sys
41 try:
42 import requests.exceptions
43 HAS_REQUESTS_EXC = True
44 except ImportError:
45 HAS_REQUESTS_EXC = False
46
47 from ansible.module_utils import basic
48 from ansible.module_utils._text import to_bytes
49 from ansible_collections.netapp.cloudmanager.tests.unit.compat.mock import patch
50 import ansible_collections.netapp.cloudmanager.plugins.module_utils.netapp as netapp_utils
51
52 if (not netapp_utils.HAS_REQUESTS or not HAS_REQUESTS_EXC) and sys.version_info < (3, 5):
53 pytestmark = pytest.mark.skip('skipping as missing required imports on 2.6 and 2.7')
54
55
56 def set_module_args(args):
57 """prepare arguments so that they will be picked up during module creation"""
58 args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
59 basic._ANSIBLE_ARGS = to_bytes(args) # pylint: disable=protected-access
60
61
62 class AnsibleFailJson(Exception):
63 """Exception class to be raised by module.fail_json and caught by the test case"""
64
65
66 def fail_json(*args, **kwargs): # pylint: disable=unused-argument
67 """function to patch over fail_json; package return data into an exception"""
68 kwargs['failed'] = True
69 raise AnsibleFailJson(kwargs)
70
71
72 class MockModule():
73 ''' rough mock for an Ansible module class '''
74 def __init__(self):
75 self.params = {}
76
77 def fail_json(self, *args, **kwargs): # pylint: disable=unused-argument
78 """function to simulate fail_json: package return data into an exception"""
79 kwargs['failed'] = True
80 raise AnsibleFailJson(kwargs)
81
82
83 class mockResponse:
84 def __init__(self, json_data, status_code, headers=None, raise_action=None):
85 self.json_data = json_data
86 self.status_code = status_code
87 self.content = json_data
88 self.headers = headers or {}
89 self.raise_action = raise_action
90
91 def raise_for_status(self):
92 pass
93
94 def json(self):
95 if self.raise_action == 'bad_json':
96 raise ValueError(self.raise_action)
97 return self.json_data
98
99
100 def create_module(args):
101 argument_spec = netapp_utils.cloudmanager_host_argument_spec()
102 set_module_args(args)
103 module = basic.AnsibleModule(argument_spec)
104 module.fail_json = fail_json
105 return module
106
107
108 def create_restapi_object(args):
109 module = create_module(args)
110 return netapp_utils.CloudManagerRestAPI(module)
111
112
113 def mock_args(feature_flags=None, client_id=None):
114 args = {
115 'refresh_token': 'ABCDEFGS'
116 }
117 if feature_flags is not None:
118 args['feature_flags'] = feature_flags
119 if client_id is not None:
120 args['client_id'] = client_id
121 return args
122
123
124 TOKEN_DICT = {
125 'access_token': 'access_token',
126 'token_type': 'token_type'
127 }
128
129
130 def test_missing_params():
131 module = MockModule()
132 with pytest.raises(KeyError) as exc:
133 netapp_utils.CloudManagerRestAPI(module)
134 assert exc.match('refresh_token')
135
136
137 @patch('requests.request')
138 def test_get_token_refresh(mock_request):
139 ''' successfully get token using refresh token '''
140 mock_request.side_effect = [
141 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
142 ]
143 # get_token is called when the object is created
144 rest_api = create_restapi_object(mock_args())
145 print(rest_api.token_type, rest_api.token)
146 assert rest_api.token_type == TOKEN_DICT['token_type']
147 assert rest_api.token == TOKEN_DICT['access_token']
148
149
150 @patch('requests.request')
151 def test_negative_get_token_none(mock_request):
152 ''' missing refresh token and Service Account '''
153 mock_request.side_effect = [
154 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
155 ]
156 # get_token is called when the object is created
157 args = dict(mock_args())
158 args.pop('refresh_token')
159 # get_token is called when the object is created
160 with pytest.raises(AnsibleFailJson) as exc:
161 rest_api = create_restapi_object(args)
162 msg = 'Missing refresh_token or sa_client_id and sa_secret_key'
163 assert msg in exc.value.args[0]['msg']
164
165
166 @patch('requests.request')
167 def test_get_token_sa(mock_request):
168 ''' successfully get token using Service Account '''
169 mock_request.side_effect = [
170 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
171 ]
172 # get_token is called when the object is created
173 args = dict(mock_args())
174 args.pop('refresh_token')
175 args['sa_client_id'] = '123'
176 args['sa_secret_key'] = 'a1b2c3'
177 rest_api = create_restapi_object(args)
178 print(rest_api.token_type, rest_api.token)
179 assert rest_api.token_type == TOKEN_DICT['token_type']
180 assert rest_api.token == TOKEN_DICT['access_token']
181
182
183 @patch('requests.request')
184 def test_negative_get_token(mock_request):
185 ''' error on OAUTH request '''
186 mock_request.side_effect = [
187 mockResponse(json_data={'message': 'error message'}, status_code=206)
188 ]
189 # get_token is called when the object is created
190 with pytest.raises(AnsibleFailJson) as exc:
191 rest_api = create_restapi_object(mock_args())
192 msg = 'Error acquiring token: error message'
193 assert msg in exc.value.args[0]['msg']
194
195
196 @patch('requests.request')
197 def test_get_json(mock_request):
198 ''' get with no data '''
199 mock_request.side_effect = [
200 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
201 mockResponse(json_data={'key': 'value'}, status_code=200, headers={'OnCloud-Request-Id': 'OCR_id'})
202 ]
203 rest_api = create_restapi_object(mock_args())
204 message, error, ocr = rest_api.get('api', None)
205 print(message, error, ocr)
206 assert message == {'key': 'value'}
207 assert error is None
208 assert ocr == 'OCR_id'
209
210
211 @patch('time.sleep')
212 @patch('requests.request')
213 def test_get_retries(mock_request, dont_sleep):
214 ''' get with no data '''
215 mock_request.side_effect = [
216 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
217 requests.exceptions.ConnectionError('Max retries exceeded with url:'),
218 requests.exceptions.ConnectionError('Max retries exceeded with url:'),
219 mockResponse(json_data={'key': 'value'}, status_code=200, headers={'OnCloud-Request-Id': 'OCR_id'})
220 ]
221 rest_api = create_restapi_object(mock_args())
222 message, error, ocr = rest_api.get('api', None)
223 print(message, error, ocr)
224 assert message == {'key': 'value'}
225 assert error is None
226 assert ocr == 'OCR_id'
227
228
229 @patch('time.sleep')
230 @patch('requests.request')
231 def test_get_retries_exceeded(mock_request, dont_sleep):
232 ''' get with no data '''
233 mock_request.side_effect = [
234 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
235 requests.exceptions.ConnectionError('Max retries exceeded with url:'),
236 requests.exceptions.ConnectionError('Max retries exceeded with url:'),
237 requests.exceptions.ConnectionError('Max retries exceeded with url:'),
238 mockResponse(json_data={'key': 'value'}, status_code=200, headers={'OnCloud-Request-Id': 'OCR_id'})
239 ]
240 rest_api = create_restapi_object(mock_args())
241 message, error, ocr = rest_api.get('api', None)
242 print(message, error, ocr)
243 assert 'Max retries exceeded with url:' in error
244
245
246 @patch('requests.request')
247 def test_empty_get_sent_bad_json(mock_request):
248 ''' get with invalid json '''
249 mock_request.side_effect = [
250 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
251 mockResponse(json_data='anything', status_code=200, raise_action='bad_json')
252 ]
253 rest_api = create_restapi_object(mock_args())
254 message, error, ocr = rest_api.get('api', None)
255 print(message, error, ocr)
256 assert message is None
257 assert error is None
258 assert ocr is None
259
260
261 @patch('requests.request')
262 def test_empty_get_sent_203(mock_request):
263 ''' get with no data and 203 status code '''
264 mock_request.side_effect = [
265 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
266 mockResponse(json_data={}, status_code=203)
267 ]
268 rest_api = create_restapi_object(mock_args())
269 message, error, ocr = rest_api.get('api', None)
270 print(message, error, ocr)
271 assert message == {}
272 assert error is None
273 assert ocr is None
274
275
276 @patch('requests.request')
277 def test_negative_get_sent_203(mock_request):
278 ''' get with 203 status code - not sure we should error out here '''
279 mock_request.side_effect = [
280 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
281 mockResponse(json_data={'message': 'error message'}, status_code=203)
282 ]
283 rest_api = create_restapi_object(mock_args())
284 message, error, ocr = rest_api.get('api', None)
285 print(message, error, ocr)
286 assert message == {'message': 'error message'}
287 assert error == 'error message'
288 assert ocr is None
289
290
291 @patch('requests.request')
292 def test_negative_get_sent_300(mock_request):
293 ''' get with 300 status code - 300 indicates an error '''
294 mock_request.side_effect = [
295 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
296 mockResponse(json_data={}, status_code=300)
297 ]
298 rest_api = create_restapi_object(mock_args())
299 message, error, ocr = rest_api.get('api', None)
300 print(message, error, ocr)
301 assert message == {}
302 assert error == '300'
303 assert ocr is None
304
305
306 @patch('requests.request')
307 def test_negative_get_raise_http_exc(mock_request):
308 ''' get with HTTPError exception '''
309 mock_request.side_effect = [
310 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
311 requests.exceptions.HTTPError('some exception')
312 ]
313 rest_api = create_restapi_object(mock_args())
314 message, error, ocr = rest_api.get('api', None)
315 print(message, error, ocr)
316 assert message is None
317 assert error == 'some exception'
318 assert ocr is None
319
320
321 @patch('requests.request')
322 def test_negative_get_raise_conn_exc(mock_request):
323 ''' get with ConnectionError exception '''
324 mock_request.side_effect = [
325 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
326 requests.exceptions.ConnectionError('some exception')
327 ]
328 rest_api = create_restapi_object(mock_args())
329 message, error, ocr = rest_api.get('api', None)
330 print(message, error, ocr)
331 assert message is None
332 assert error == 'some exception'
333 assert ocr is None
334
335
336 @patch('requests.request')
337 def test_negative_get_raise_oserror_exc(mock_request):
338 ''' get with a general exception '''
339 mock_request.side_effect = [
340 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
341 OSError('some exception')
342 ]
343 rest_api = create_restapi_object(mock_args())
344 message, error, ocr = rest_api.get('api', None)
345 print(message, error, ocr)
346 assert message is None
347 assert error == 'some exception'
348 assert ocr is None
349
350
351 def test_has_feature_success_default():
352 ''' existing feature_flag with default '''
353 flag = 'show_modified'
354 module = create_module(mock_args())
355 value = netapp_utils.has_feature(module, flag)
356 assert value
357
358
359 def test_has_feature_success_user_true():
360 ''' existing feature_flag with value set to True '''
361 flag = 'user_deprecation_warning'
362 args = dict(mock_args({flag: True}))
363 module = create_module(args)
364 value = netapp_utils.has_feature(module, flag)
365 assert value
366
367
368 def test_has_feature_success_user_false():
369 ''' existing feature_flag with value set to False '''
370 flag = 'user_deprecation_warning'
371 args = dict(mock_args({flag: False}))
372 print(args)
373 module = create_module(args)
374 value = netapp_utils.has_feature(module, flag)
375 assert not value
376
377
378 def test_has_feature_invalid_key():
379 ''' existing feature_flag with unknown key '''
380 flag = 'deprecation_warning_bad_key'
381 module = create_module(mock_args())
382 with pytest.raises(AnsibleFailJson) as exc:
383 netapp_utils.has_feature(module, flag)
384 msg = 'Internal error: unexpected feature flag: %s' % flag
385 assert exc.value.args[0]['msg'] == msg
386
387
388 def test_has_feature_invalid_bool():
389 ''' existing feature_flag with non boolean value '''
390 flag = 'deprecation_warning_key'
391 module = create_module(mock_args({flag: 'str'}))
392 with pytest.raises(AnsibleFailJson) as exc:
393 netapp_utils.has_feature(module, flag)
394 msg = "Error: expected bool type for feature flag"
395 assert msg in exc.value.args[0]['msg']
396
397
398 STATUS_DICT = {
399 'status': 1,
400 'error': None
401 }
402
403
404 @patch('time.sleep')
405 @patch('requests.request')
406 def test_check_task_status(mock_request, mock_sleep):
407 ''' successful get with 2 retries '''
408 mock_request.side_effect = [
409 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
410 OSError('some exception'),
411 requests.exceptions.ConnectionError('some exception'),
412 mockResponse(json_data=STATUS_DICT, status_code=200)
413 ]
414 rest_api = create_restapi_object(mock_args())
415 rest_api.module.params['client_id'] = '123'
416 status, error_msg, error = rest_api.check_task_status('api')
417 assert status == STATUS_DICT['status']
418 assert error_msg == STATUS_DICT['error']
419 assert error is None
420
421
422 @patch('time.sleep')
423 @patch('requests.request')
424 def test_negative_check_task_status(mock_request, mock_sleep):
425 ''' get with 4 failed retries '''
426 mock_request.side_effect = [
427 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
428 OSError('some exception'),
429 requests.exceptions.ConnectionError('some exception'),
430 requests.exceptions.ConnectionError('some exception'),
431 requests.exceptions.HTTPError('some exception'),
432 ]
433 rest_api = create_restapi_object(mock_args())
434 rest_api.module.params['client_id'] = '123'
435 status, error_msg, error = rest_api.check_task_status('api')
436 assert status == 0
437 assert error_msg == ''
438 assert error == 'some exception'
439
440
441 @patch('time.sleep')
442 @patch('requests.request')
443 def test_wait_on_completion(mock_request, mock_sleep):
444 ''' successful get with 2 retries '''
445 mock_request.side_effect = [
446 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
447 OSError('some exception'),
448 requests.exceptions.ConnectionError('some exception'),
449 mockResponse(json_data=STATUS_DICT, status_code=200)
450 ]
451 rest_api = create_restapi_object(mock_args())
452 rest_api.module.params['client_id'] = '123'
453 error = rest_api.wait_on_completion('api', 'action', 'task', 2, 1)
454 assert error is None
455
456
457 @patch('time.sleep')
458 @patch('requests.request')
459 def test_negative_wait_on_completion_failure(mock_request, mock_sleep):
460 ''' successful get with 2 retries, but status is -1 '''
461 mock_request.side_effect = [
462 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
463 OSError('some exception'),
464 requests.exceptions.ConnectionError('some exception'),
465 mockResponse(json_data={'status': -1, 'error': 'task_error'}, status_code=200)
466 ]
467 rest_api = create_restapi_object(mock_args())
468 rest_api.module.params['client_id'] = '123'
469 error = rest_api.wait_on_completion('api', 'action', 'task', 2, 1)
470 assert error == 'Failed to task action, error: task_error'
471
472
473 @patch('time.sleep')
474 @patch('requests.request')
475 def test_negative_wait_on_completion_error(mock_request, mock_sleep):
476 ''' get with 4 failed retries '''
477 mock_request.side_effect = [
478 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
479 OSError('some exception'),
480 requests.exceptions.ConnectionError('some exception'),
481 requests.exceptions.ConnectionError('some exception'),
482 requests.exceptions.HTTPError('some http exception'),
483 ]
484 rest_api = create_restapi_object(mock_args())
485 rest_api.module.params['client_id'] = '123'
486 error = rest_api.wait_on_completion('api', 'action', 'task', 2, 1)
487 assert error == 'some http exception'
488
489
490 @patch('time.sleep')
491 @patch('requests.request')
492 def test_negative_wait_on_completion_timeout(mock_request, mock_sleep):
493 ''' successful get with 2 retries, but status is 0 '''
494 mock_request.side_effect = [
495 mockResponse(json_data=TOKEN_DICT, status_code=200), # OAUTH
496 OSError('some exception'),
497 requests.exceptions.ConnectionError('some exception'),
498 mockResponse(json_data={'status': 0, 'error': 'task_error'}, status_code=200),
499 mockResponse(json_data={'status': 0, 'error': 'task_error'}, status_code=200),
500 mockResponse(json_data={'status': 0, 'error': 'task_error'}, status_code=200)
501 ]
502 rest_api = create_restapi_object(mock_args())
503 rest_api.module.params['client_id'] = '123'
504 error = rest_api.wait_on_completion('api', 'action', 'task', 2, 1)
505 assert error == 'Taking too long for action to task or not properly setup'