Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/modules/test_ipa_otptoken.py

raw
1 # Copyright (c) 2020, Ansible Project
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 from contextlib import contextmanager
8 from unittest.mock import call, patch
9
10 from ansible_collections.community.internal_test_tools.tests.unit.plugins.modules.utils import (
11 AnsibleExitJson,
12 AnsibleFailJson,
13 ModuleTestCase,
14 set_module_args,
15 )
16
17 from ansible_collections.community.general.plugins.modules import ipa_otptoken
18
19
20 @contextmanager
21 def patch_ipa(**kwargs):
22 """Mock context manager for patching the methods in OTPTokenIPAClient that contact the IPA server
23
24 Patches the `login` and `_post_json` methods
25
26 Keyword arguments are passed to the mock object that patches `_post_json`
27
28 No arguments are passed to the mock object that patches `login` because no tests require it
29
30 Example::
31
32 with patch_ipa(return_value={}) as (mock_login, mock_post):
33 ...
34 """
35 obj = ipa_otptoken.OTPTokenIPAClient
36 with patch.object(obj, "login") as mock_login:
37 with patch.object(obj, "_post_json", **kwargs) as mock_post:
38 yield mock_login, mock_post
39
40
41 class TestIPAOTPToken(ModuleTestCase):
42 def setUp(self):
43 super().setUp()
44 self.module = ipa_otptoken
45
46 def _test_base(self, module_args, return_value, mock_calls, changed):
47 """Base function that's called by all the other test functions
48
49 module_args (dict):
50 Arguments passed to the module
51
52 return_value (dict):
53 Mocked return value of OTPTokenIPAClient.otptoken_show, as returned by the IPA API.
54 This should be set to the current state. It will be changed to the desired state using the above arguments.
55 (Technically, this is the return value of _post_json, but it's only checked by otptoken_show).
56
57 mock_calls (list/tuple of dicts):
58 List of calls made to OTPTokenIPAClient._post_json, in order.
59 _post_json is called by all of the otptoken_* methods of the class.
60 Pass an empty list if no calls are expected.
61
62 changed (bool):
63 Whether or not the module is supposed to be marked as changed
64 """
65 with set_module_args(module_args):
66 # Run the module
67 with patch_ipa(return_value=return_value) as (mock_login, mock_post):
68 with self.assertRaises(AnsibleExitJson) as exec_info:
69 self.module.main()
70
71 # Verify that the calls to _post_json match what is expected
72 expected_call_count = len(mock_calls)
73 if expected_call_count > 1:
74 # Convert the call dicts to unittest.mock.call instances because `assert_has_calls` only accepts them
75 converted_calls = []
76 for call_dict in mock_calls:
77 converted_calls.append(call(**call_dict))
78
79 mock_post.assert_has_calls(converted_calls)
80 self.assertEqual(len(mock_post.mock_calls), expected_call_count)
81 elif expected_call_count == 1:
82 mock_post.assert_called_once_with(**mock_calls[0])
83 else: # expected_call_count is 0
84 mock_post.assert_not_called()
85
86 # Verify that the module's changed status matches what is expected
87 self.assertIs(exec_info.exception.args[0]["changed"], changed)
88
89 def test_add_new_all_default(self):
90 """Add a new OTP with all default values"""
91 module_args = {"uniqueid": "NewToken1"}
92 return_value = {}
93 mock_calls = (
94 {
95 "method": "otptoken_find",
96 "name": None,
97 "item": {"all": True, "ipatokenuniqueid": "NewToken1", "timelimit": "0", "sizelimit": "0"},
98 },
99 {"method": "otptoken_add", "name": "NewToken1", "item": {"ipatokendisabled": False, "all": True}},
100 )
101 changed = True
102
103 self._test_base(module_args, return_value, mock_calls, changed)
104
105 def test_add_new_all_default_with_aliases(self):
106 """Add a new OTP with all default values using alias values"""
107 module_args = {"name": "NewToken1"}
108 return_value = {}
109 mock_calls = (
110 {
111 "method": "otptoken_find",
112 "name": None,
113 "item": {"all": True, "ipatokenuniqueid": "NewToken1", "timelimit": "0", "sizelimit": "0"},
114 },
115 {"method": "otptoken_add", "name": "NewToken1", "item": {"ipatokendisabled": False, "all": True}},
116 )
117 changed = True
118
119 self._test_base(module_args, return_value, mock_calls, changed)
120
121 def test_add_new_all_specified(self):
122 """Add a new OTP with all default values"""
123 module_args = {
124 "uniqueid": "NewToken1",
125 "otptype": "hotp",
126 "secretkey": "VGVzdFNlY3JldDE=",
127 "description": "Test description",
128 "owner": "pinky",
129 "enabled": True,
130 "notbefore": "20200101010101",
131 "notafter": "20900101010101",
132 "vendor": "Acme",
133 "model": "ModelT",
134 "serial": "Number1",
135 "state": "present",
136 "algorithm": "sha256",
137 "digits": 6,
138 "offset": 10,
139 "interval": 30,
140 "counter": 30,
141 }
142 return_value = {}
143 mock_calls = (
144 {
145 "method": "otptoken_find",
146 "name": None,
147 "item": {"all": True, "ipatokenuniqueid": "NewToken1", "timelimit": "0", "sizelimit": "0"},
148 },
149 {
150 "method": "otptoken_add",
151 "name": "NewToken1",
152 "item": {
153 "type": "HOTP",
154 "ipatokenotpkey": "KRSXG5CTMVRXEZLUGE======",
155 "description": "Test description",
156 "ipatokenowner": "pinky",
157 "ipatokendisabled": False,
158 "ipatokennotbefore": "20200101010101Z",
159 "ipatokennotafter": "20900101010101Z",
160 "ipatokenvendor": "Acme",
161 "ipatokenmodel": "ModelT",
162 "ipatokenserial": "Number1",
163 "ipatokenotpalgorithm": "sha256",
164 "ipatokenotpdigits": "6",
165 "ipatokentotpclockoffset": "10",
166 "ipatokentotptimestep": "30",
167 "ipatokenhotpcounter": "30",
168 "all": True,
169 },
170 },
171 )
172 changed = True
173
174 self._test_base(module_args, return_value, mock_calls, changed)
175
176 def test_already_existing_no_change_all_specified(self):
177 """Add a new OTP with all values specified but needing no change"""
178 module_args = {
179 "uniqueid": "NewToken1",
180 "otptype": "hotp",
181 "secretkey": "VGVzdFNlY3JldDE=",
182 "description": "Test description",
183 "owner": "pinky",
184 "enabled": True,
185 "notbefore": "20200101010101",
186 "notafter": "20900101010101",
187 "vendor": "Acme",
188 "model": "ModelT",
189 "serial": "Number1",
190 "state": "present",
191 "algorithm": "sha256",
192 "digits": 6,
193 "offset": 10,
194 "interval": 30,
195 "counter": 30,
196 }
197 return_value = {
198 "ipatokenuniqueid": "NewToken1",
199 "type": "HOTP",
200 "ipatokenotpkey": [{"__base64__": "VGVzdFNlY3JldDE="}],
201 "description": ["Test description"],
202 "ipatokenowner": ["pinky"],
203 "ipatokendisabled": [False],
204 "ipatokennotbefore": ["20200101010101Z"],
205 "ipatokennotafter": ["20900101010101Z"],
206 "ipatokenvendor": ["Acme"],
207 "ipatokenmodel": ["ModelT"],
208 "ipatokenserial": ["Number1"],
209 "ipatokenotpalgorithm": ["sha256"],
210 "ipatokenotpdigits": ["6"],
211 "ipatokentotpclockoffset": ["10"],
212 "ipatokentotptimestep": ["30"],
213 "ipatokenhotpcounter": ["30"],
214 }
215 mock_calls = [
216 {
217 "method": "otptoken_find",
218 "name": None,
219 "item": {"all": True, "ipatokenuniqueid": "NewToken1", "timelimit": "0", "sizelimit": "0"},
220 }
221 ]
222 changed = False
223
224 self._test_base(module_args, return_value, mock_calls, changed)
225
226 def test_already_existing_one_change_all_specified(self):
227 """Modify an existing OTP with one value specified needing change"""
228 module_args = {
229 "uniqueid": "NewToken1",
230 "otptype": "hotp",
231 "secretkey": "VGVzdFNlY3JldDE=",
232 "description": "Test description",
233 "owner": "brain",
234 "enabled": True,
235 "notbefore": "20200101010101",
236 "notafter": "20900101010101",
237 "vendor": "Acme",
238 "model": "ModelT",
239 "serial": "Number1",
240 "state": "present",
241 "algorithm": "sha256",
242 "digits": 6,
243 "offset": 10,
244 "interval": 30,
245 "counter": 30,
246 }
247 return_value = {
248 "ipatokenuniqueid": "NewToken1",
249 "type": "HOTP",
250 "ipatokenotpkey": [{"__base64__": "VGVzdFNlY3JldDE="}],
251 "description": ["Test description"],
252 "ipatokenowner": ["pinky"],
253 "ipatokendisabled": [False],
254 "ipatokennotbefore": ["20200101010101Z"],
255 "ipatokennotafter": ["20900101010101Z"],
256 "ipatokenvendor": ["Acme"],
257 "ipatokenmodel": ["ModelT"],
258 "ipatokenserial": ["Number1"],
259 "ipatokenotpalgorithm": ["sha256"],
260 "ipatokenotpdigits": ["6"],
261 "ipatokentotpclockoffset": ["10"],
262 "ipatokentotptimestep": ["30"],
263 "ipatokenhotpcounter": ["30"],
264 }
265 mock_calls = (
266 {
267 "method": "otptoken_find",
268 "name": None,
269 "item": {"all": True, "ipatokenuniqueid": "NewToken1", "timelimit": "0", "sizelimit": "0"},
270 },
271 {
272 "method": "otptoken_mod",
273 "name": "NewToken1",
274 "item": {
275 "description": "Test description",
276 "ipatokenowner": "brain",
277 "ipatokendisabled": False,
278 "ipatokennotbefore": "20200101010101Z",
279 "ipatokennotafter": "20900101010101Z",
280 "ipatokenvendor": "Acme",
281 "ipatokenmodel": "ModelT",
282 "ipatokenserial": "Number1",
283 "all": True,
284 },
285 },
286 )
287 changed = True
288
289 self._test_base(module_args, return_value, mock_calls, changed)
290
291 def test_already_existing_all_valid_change_all_specified(self):
292 """Modify an existing OTP with all valid values specified needing change"""
293 module_args = {
294 "uniqueid": "NewToken1",
295 "otptype": "hotp",
296 "secretkey": "VGVzdFNlY3JldDE=",
297 "description": "New Test description",
298 "owner": "pinky",
299 "enabled": False,
300 "notbefore": "20200101010102",
301 "notafter": "20900101010102",
302 "vendor": "NewAcme",
303 "model": "NewModelT",
304 "serial": "Number2",
305 "state": "present",
306 "algorithm": "sha256",
307 "digits": 6,
308 "offset": 10,
309 "interval": 30,
310 "counter": 30,
311 }
312 return_value = {
313 "ipatokenuniqueid": "NewToken1",
314 "type": "HOTP",
315 "ipatokenotpkey": [{"__base64__": "VGVzdFNlY3JldDE="}],
316 "description": ["Test description"],
317 "ipatokenowner": ["pinky"],
318 "ipatokendisabled": [False],
319 "ipatokennotbefore": ["20200101010101Z"],
320 "ipatokennotafter": ["20900101010101Z"],
321 "ipatokenvendor": ["Acme"],
322 "ipatokenmodel": ["ModelT"],
323 "ipatokenserial": ["Number1"],
324 "ipatokenotpalgorithm": ["sha256"],
325 "ipatokenotpdigits": ["6"],
326 "ipatokentotpclockoffset": ["10"],
327 "ipatokentotptimestep": ["30"],
328 "ipatokenhotpcounter": ["30"],
329 }
330 mock_calls = (
331 {
332 "method": "otptoken_find",
333 "name": None,
334 "item": {"all": True, "ipatokenuniqueid": "NewToken1", "timelimit": "0", "sizelimit": "0"},
335 },
336 {
337 "method": "otptoken_mod",
338 "name": "NewToken1",
339 "item": {
340 "description": "New Test description",
341 "ipatokenowner": "pinky",
342 "ipatokendisabled": True,
343 "ipatokennotbefore": "20200101010102Z",
344 "ipatokennotafter": "20900101010102Z",
345 "ipatokenvendor": "NewAcme",
346 "ipatokenmodel": "NewModelT",
347 "ipatokenserial": "Number2",
348 "all": True,
349 },
350 },
351 )
352 changed = True
353
354 self._test_base(module_args, return_value, mock_calls, changed)
355
356 def test_delete_existing_token(self):
357 """Delete an existing OTP"""
358 module_args = {"uniqueid": "NewToken1", "state": "absent"}
359 return_value = {
360 "ipatokenuniqueid": "NewToken1",
361 "type": "HOTP",
362 "ipatokenotpkey": [{"__base64__": "KRSXG5CTMVRXEZLUGE======"}],
363 "description": ["Test description"],
364 "ipatokenowner": ["pinky"],
365 "ipatokendisabled": [False],
366 "ipatokennotbefore": ["20200101010101Z"],
367 "ipatokennotafter": ["20900101010101Z"],
368 "ipatokenvendor": ["Acme"],
369 "ipatokenmodel": ["ModelT"],
370 "ipatokenserial": ["Number1"],
371 "ipatokenotpalgorithm": ["sha256"],
372 "ipatokenotpdigits": ["6"],
373 "ipatokentotpclockoffset": ["10"],
374 "ipatokentotptimestep": ["30"],
375 "ipatokenhotpcounter": ["30"],
376 }
377 mock_calls = (
378 {
379 "method": "otptoken_find",
380 "name": None,
381 "item": {"all": True, "ipatokenuniqueid": "NewToken1", "timelimit": "0", "sizelimit": "0"},
382 },
383 {"method": "otptoken_del", "name": "NewToken1"},
384 )
385 changed = True
386
387 self._test_base(module_args, return_value, mock_calls, changed)
388
389 def test_disable_existing_token(self):
390 """Disable an existing OTP"""
391 module_args = {"uniqueid": "NewToken1", "otptype": "hotp", "enabled": False}
392 return_value = {
393 "ipatokenuniqueid": "NewToken1",
394 "type": "HOTP",
395 "ipatokenotpkey": [{"__base64__": "KRSXG5CTMVRXEZLUGE======"}],
396 "description": ["Test description"],
397 "ipatokenowner": ["pinky"],
398 "ipatokendisabled": [False],
399 "ipatokennotbefore": ["20200101010101Z"],
400 "ipatokennotafter": ["20900101010101Z"],
401 "ipatokenvendor": ["Acme"],
402 "ipatokenmodel": ["ModelT"],
403 "ipatokenserial": ["Number1"],
404 "ipatokenotpalgorithm": ["sha256"],
405 "ipatokenotpdigits": ["6"],
406 "ipatokentotpclockoffset": ["10"],
407 "ipatokentotptimestep": ["30"],
408 "ipatokenhotpcounter": ["30"],
409 }
410 mock_calls = (
411 {
412 "method": "otptoken_find",
413 "name": None,
414 "item": {"all": True, "ipatokenuniqueid": "NewToken1", "timelimit": "0", "sizelimit": "0"},
415 },
416 {"method": "otptoken_mod", "name": "NewToken1", "item": {"ipatokendisabled": True, "all": True}},
417 )
418 changed = True
419
420 self._test_base(module_args, return_value, mock_calls, changed)
421
422 def test_delete_not_existing_token(self):
423 """Delete a OTP that does not exist"""
424 module_args = {"uniqueid": "NewToken1", "state": "absent"}
425 return_value = {}
426
427 mock_calls = [
428 {
429 "method": "otptoken_find",
430 "name": None,
431 "item": {"all": True, "ipatokenuniqueid": "NewToken1", "timelimit": "0", "sizelimit": "0"},
432 }
433 ]
434
435 changed = False
436
437 self._test_base(module_args, return_value, mock_calls, changed)
438
439 def test_fail_post(self):
440 """Fail due to an exception raised from _post_json"""
441 with set_module_args({"uniqueid": "NewToken1"}):
442 with patch_ipa(side_effect=Exception("ERROR MESSAGE")) as (mock_login, mock_post):
443 with self.assertRaises(AnsibleFailJson) as exec_info:
444 self.module.main()
445
446 self.assertEqual(exec_info.exception.args[0]["msg"], "ERROR MESSAGE")