Debian Codegraph @

ansible_collections/community/hrobot/tests/unit/plugins/module_utils/test_robot.py

raw
1 # Copyright (c) 2017 Ansible Project
2 # Copyright (c), Felix Fontein <[email protected]>, 2019-2020
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import (absolute_import, division, print_function)
7 __metaclass__ = type
8
9 import json
10 import pytest
11
12 from mock import MagicMock
13 from ansible_collections.community.hrobot.plugins.module_utils import robot
14
15
16 class ModuleFailException(Exception):
17 def __init__(self, msg, **kwargs):
18 super(ModuleFailException, self).__init__(msg)
19 self.fail_msg = msg
20 self.fail_kwargs = kwargs
21
22
23 def get_module_mock():
24 def f(msg, **kwargs):
25 raise ModuleFailException(msg, **kwargs)
26
27 module = MagicMock()
28 module.fail_json = f
29 module.from_json = json.loads
30 return module
31
32
33 # ########################################################################################
34
35 FETCH_URL_JSON_SUCCESS = [
36 (
37 (None, dict(
38 body=json.dumps(dict(
39 a='b'
40 )).encode('utf-8'),
41 )),
42 None,
43 (dict(
44 a='b'
45 ), None)
46 ),
47 (
48 (None, dict(
49 body=json.dumps(dict(
50 error=dict(
51 code="foo",
52 status=400,
53 message="bar",
54 ),
55 a='b'
56 )).encode('utf-8'),
57 )),
58 ['foo'],
59 (dict(
60 error=dict(
61 code="foo",
62 status=400,
63 message="bar",
64 ),
65 a='b'
66 ), 'foo')
67 ),
68 ]
69
70
71 FETCH_URL_JSON_FAIL = [
72 (
73 (None, dict(
74 body=json.dumps(dict(
75 error=dict(
76 code="foo",
77 status=400,
78 message="bar",
79 ),
80 )).encode('utf-8'),
81 )),
82 None,
83 'Request failed: 400 foo (bar)',
84 {
85 'error': {
86 'code': "foo",
87 'status': 400,
88 'message': "bar",
89 },
90 },
91 ),
92 (
93 (None, dict(
94 body=json.dumps(dict(
95 error=dict(
96 code="foo",
97 status=400,
98 message="bar",
99 missing=None,
100 invalid=None,
101 max_request=None,
102 interval=None,
103 ),
104 )).encode('utf-8'),
105 )),
106 ['bar'],
107 'Request failed: 400 foo (bar)',
108 {
109 'error': {
110 'code': "foo",
111 'status': 400,
112 'message': "bar",
113 'missing': None,
114 'invalid': None,
115 'max_request': None,
116 'interval': None,
117 },
118 },
119 ),
120 (
121 (None, dict(
122 body=json.dumps(dict(
123 error=dict(
124 code="foo",
125 status=400,
126 message="bar",
127 missing=["foo"],
128 invalid=["bar"],
129 max_request=0,
130 interval=0,
131 ),
132 )).encode('utf-8'),
133 )),
134 None,
135 "Request failed: 400 foo (bar). Missing input parameters: ['foo']. Invalid input"
136 " parameters: ['bar']. Maximum allowed requests: 0. Time interval in seconds: 0",
137 {
138 'error': {
139 'code': "foo",
140 'status': 400,
141 'message': "bar",
142 'missing': ["foo"],
143 'invalid': ["bar"],
144 'max_request': 0,
145 'interval': 0,
146 },
147 },
148 ),
149 (
150 (None, dict(body='{this is not json}'.encode('utf-8'))),
151 [],
152 'Cannot decode content retrieved from https://foo/bar',
153 {},
154 ),
155 (
156 (None, dict(status=400, msg="Error!")),
157 [],
158 'Cannot retrieve content from GET https://foo/bar, HTTP status code 400 (Error!)',
159 {},
160 ),
161 ]
162
163
164 @pytest.mark.parametrize("return_value, accept_errors, result", FETCH_URL_JSON_SUCCESS)
165 def test_fetch_url_json(monkeypatch, return_value, accept_errors, result):
166 module = get_module_mock()
167 robot.fetch_url = MagicMock(return_value=return_value)
168
169 assert robot.fetch_url_json(module, 'https://foo/bar', accept_errors=accept_errors) == result
170
171
172 @pytest.mark.parametrize("return_value, accept_errors, fail_msg, fail_kwargs", FETCH_URL_JSON_FAIL)
173 def test_fetch_url_json_fail(monkeypatch, return_value, accept_errors, fail_msg, fail_kwargs):
174 module = get_module_mock()
175 robot.fetch_url = MagicMock(return_value=return_value)
176
177 with pytest.raises(ModuleFailException) as exc:
178 robot.fetch_url_json(module, 'https://foo/bar', accept_errors=accept_errors)
179
180 print(exc.value.fail_msg)
181 print(exc.value.fail_kwargs)
182 assert exc.value.fail_msg == fail_msg
183 assert exc.value.fail_kwargs == fail_kwargs
184
185
186 def test_fetch_url_json_empty(monkeypatch):
187 module = get_module_mock()
188 robot.fetch_url = MagicMock(return_value=(None, dict(status=204, body='')))
189
190 assert robot.fetch_url_json(module, 'https://foo/bar', allow_empty_result=True) == (None, None)
191
192 robot.fetch_url = MagicMock(return_value=(None, dict(status=400, body='', msg='Error!')))
193
194 with pytest.raises(ModuleFailException) as exc:
195 robot.fetch_url_json(module, 'https://foo/bar', allow_empty_result=True)
196
197 print(exc.value.fail_msg)
198 print(exc.value.fail_kwargs)
199 assert exc.value.fail_msg == 'Cannot retrieve content from GET https://foo/bar, HTTP status code 400 (Error!)'
200 assert exc.value.fail_kwargs == dict()
201
202
203 @pytest.mark.parametrize("return_value, accept_errors, result", FETCH_URL_JSON_SUCCESS)
204 def test_plugin_open_url_json(monkeypatch, return_value, accept_errors, result):
205 response = MagicMock()
206 response.read = MagicMock(return_value=return_value[1]['body'])
207 robot.open_url = MagicMock(return_value=response)
208 plugin = MagicMock()
209
210 assert robot.plugin_open_url_json(plugin, 'https://foo/bar', accept_errors=accept_errors) == result
211
212
213 @pytest.mark.parametrize("return_value, accept_errors, fail_msg, fail_kwargs", FETCH_URL_JSON_FAIL)
214 def test_plugin_open_url_json_fail(monkeypatch, return_value, accept_errors, fail_msg, fail_kwargs):
215 response = MagicMock()
216 response.read = MagicMock(return_value=return_value[1].get('body', ''))
217 robot.open_url = MagicMock(side_effect=robot.HTTPError('https://foo/bar', 400, 'Error!', {}, response))
218 plugin = MagicMock()
219
220 with pytest.raises(robot.PluginException) as exc:
221 robot.plugin_open_url_json(plugin, 'https://foo/bar', accept_errors=accept_errors)
222
223 print(exc.value.error_message)
224 assert exc.value.error_message == fail_msg
225
226
227 def test_plugin_open_url_json_fail_other(monkeypatch):
228 robot.open_url = MagicMock(side_effect=Exception('buh!'))
229 plugin = MagicMock()
230
231 with pytest.raises(robot.PluginException) as exc:
232 robot.plugin_open_url_json(plugin, 'https://foo/bar')
233
234 assert exc.value.error_message == 'Failed request to Hetzner Robot server endpoint https://foo/bar: buh!'
235
236
237 def test_plugin_open_url_json_fail_other_2(monkeypatch):
238 response = MagicMock()
239 response.read = MagicMock(side_effect=AttributeError('read'))
240 robot.open_url = MagicMock(side_effect=robot.HTTPError('https://foo/bar', 400, 'Error!', {}, response))
241 plugin = MagicMock()
242
243 with pytest.raises(robot.PluginException) as exc:
244 robot.plugin_open_url_json(plugin, 'https://foo/bar')
245
246 assert exc.value.error_message == 'Cannot retrieve content from GET https://foo/bar, HTTP status code 400 (Error!)'
247
248
249 def test_plugin_open_url_json_empty_result(monkeypatch):
250 response = MagicMock()
251 response.read = MagicMock(return_value='')
252 response.code = 200
253 robot.open_url = MagicMock(return_value=response)
254 plugin = MagicMock()
255
256 assert robot.plugin_open_url_json(plugin, 'https://foo/bar', allow_empty_result=True) == (None, None)
257
258 response = MagicMock()
259 response.read = MagicMock(side_effect=AttributeError('read'))
260 robot.open_url = MagicMock(side_effect=robot.HTTPError('https://foo/bar', 400, 'Error!', {}, response))
261
262 with pytest.raises(robot.PluginException) as exc:
263 robot.plugin_open_url_json(plugin, 'https://foo/bar')
264
265 assert exc.value.error_message == 'Cannot retrieve content from GET https://foo/bar, HTTP status code 400 (Error!)'