Debian Codegraph @

ansible_collections/dellemc/openmanage/tests/unit/plugins/modules/common.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 #
4 # Dell OpenManage Ansible Modules
5 # Version 7.0.0
6 # Copyright (C) 2019-2022 Dell Inc.
7
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9 # All rights reserved. Dell, EMC, and other trademarks are trademarks of Dell Inc. or its subsidiaries.
10 # Other trademarks may be trademarks of their respective owners.
11 #
12
13 from __future__ import (absolute_import, division, print_function)
14
15 __metaclass__ = type
16
17 import pytest
18 from ansible_collections.dellemc.openmanage.tests.unit.plugins.modules.utils import set_module_args, AnsibleFailJson, \
19 AnsibleExitJson
20 from unittest.mock import MagicMock
21 import ast
22
23
24 class Constants:
25 device_id1 = 1234
26 device_id2 = 4321
27 service_tag1 = "MXL1234"
28 service_tag2 = "MXL5467"
29 hostname1 = "XX.XX.XX.XX"
30 hostname2 = "YY.YY.YY.YY"
31
32
33 class AnsibleFailJSonException(Exception):
34 def __init__(self, msg, **kwargs):
35 super(AnsibleFailJSonException, self).__init__(msg)
36 self.fail_msg = msg
37 self.fail_kwargs = kwargs
38
39
40 class FakeAnsibleModule:
41
42 def _run_module(self, module_args, check_mode=False):
43 module_args.update({'_ansible_check_mode': check_mode})
44 set_module_args(module_args)
45 with pytest.raises(AnsibleExitJson) as ex:
46 self.module.main()
47 return ex.value.args[0]
48
49 def _run_module_with_fail_json(self, module_args):
50 set_module_args(module_args)
51 with pytest.raises(AnsibleFailJson) as exc:
52 self.module.main()
53 result = exc.value.args[0]
54 return result
55
56 def execute_module(self, module_args, check_mode=False):
57 """[workaround]: generic exception handling in module will
58 be caught here and extracted the result for exit_json case"""
59 module_args.update({'_ansible_check_mode': check_mode})
60 set_module_args(module_args)
61 result = {}
62 try:
63 with pytest.raises(AnsibleExitJson) as ex:
64 self.module.main()
65 except Exception as err:
66 result = ast.literal_eval(err.args[0]['msg'])
67 return result
68
69 def get_module_mock(self, params=None, check_mode=False):
70 if params is None:
71 params = {}
72
73 def fail_func(msg, **kwargs):
74 raise AnsibleFailJSonException(msg, **kwargs)
75
76 module = MagicMock()
77 module.fail_json.side_effect = fail_func
78 module.exit_json.side_effect = fail_func
79 module.params = params
80 module.check_mode = check_mode
81 return module