Debian Codegraph @

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

raw
1 # Copyright (c) 2021, 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 io import StringIO
9 from itertools import count
10 from unittest.mock import patch
11
12 from ansible_collections.community.internal_test_tools.tests.unit.plugins.modules.utils import (
13 AnsibleExitJson,
14 ModuleTestCase,
15 set_module_args,
16 )
17
18 from ansible_collections.community.general.plugins.modules import keycloak_realm_key
19
20
21 @contextmanager
22 def patch_keycloak_api(
23 get_components=None, get_component=None, create_component=None, update_component=None, delete_component=None
24 ):
25 """Mock context manager for patching the methods in KeycloakAPI"""
26
27 obj = keycloak_realm_key.KeycloakAPI
28 with patch.object(obj, "get_components", side_effect=get_components) as mock_get_components:
29 with patch.object(obj, "get_component", side_effect=get_component) as mock_get_component:
30 with patch.object(obj, "create_component", side_effect=create_component) as mock_create_component:
31 with patch.object(obj, "update_component", side_effect=update_component) as mock_update_component:
32 with patch.object(obj, "delete_component", side_effect=delete_component) as mock_delete_component:
33 yield (
34 mock_get_components,
35 mock_get_component,
36 mock_create_component,
37 mock_update_component,
38 mock_delete_component,
39 )
40
41
42 def get_response(object_with_future_response, method, get_id_call_count):
43 if callable(object_with_future_response):
44 return object_with_future_response()
45 if isinstance(object_with_future_response, dict):
46 return get_response(object_with_future_response[method], method, get_id_call_count)
47 if isinstance(object_with_future_response, list):
48 call_number = next(get_id_call_count)
49 return get_response(object_with_future_response[call_number], method, get_id_call_count)
50 return object_with_future_response
51
52
53 def build_mocked_request(get_id_user_count, response_dict):
54 def _mocked_requests(*args, **kwargs):
55 url = args[0]
56 method = kwargs["method"]
57 future_response = response_dict.get(url, None)
58 return get_response(future_response, method, get_id_user_count)
59
60 return _mocked_requests
61
62
63 def create_wrapper(text_as_string):
64 """Allow to mock many times a call to one address.
65 Without this function, the StringIO is empty for the second call.
66 """
67
68 def _create_wrapper():
69 return StringIO(text_as_string)
70
71 return _create_wrapper
72
73
74 def mock_good_connection():
75 token_response = {
76 "http://keycloak.url/auth/realms/master/protocol/openid-connect/token": create_wrapper(
77 '{"access_token": "alongtoken"}'
78 ),
79 }
80 return patch(
81 "ansible_collections.community.general.plugins.module_utils._keycloak.open_url",
82 side_effect=build_mocked_request(count(), token_response),
83 autospec=True,
84 )
85
86
87 class TestKeycloakRealmKeys(ModuleTestCase):
88 def setUp(self):
89 super().setUp()
90 self.module = keycloak_realm_key
91
92 def test_create_when_absent(self):
93 """Add a new realm key"""
94
95 module_args = {
96 "auth_keycloak_url": "http://keycloak.url/auth",
97 "auth_realm": "master",
98 "auth_username": "admin",
99 "auth_password": "admin",
100 "parent_id": "realm-name",
101 "name": "testkey",
102 "state": "present",
103 "provider_id": "rsa",
104 "config": {
105 "priority": 0,
106 "enabled": True,
107 "private_key": "privatekey",
108 "algorithm": "RS256",
109 "certificate": "foo",
110 },
111 }
112 return_value_component_create = [
113 {
114 "id": "ebb7d999-60cc-4dfe-ab79-48f7bbd9d4d9",
115 "name": "testkey",
116 "providerId": "rsa",
117 "parentId": "90c8fef9-15f8-4d5b-8b22-44e2e1cdcd09",
118 "config": {
119 "privateKey": ["**********"],
120 "certificate": ["foo"],
121 "active": ["true"],
122 "priority": ["122"],
123 "enabled": ["true"],
124 "algorithm": ["RS256"],
125 },
126 }
127 ]
128 # get before_comp, get default_mapper, get after_mapper
129 return_value_components_get = [[], [], []]
130 changed = True
131
132 # Run the module
133
134 with set_module_args(module_args):
135 with mock_good_connection():
136 with patch_keycloak_api(
137 get_components=return_value_components_get, create_component=return_value_component_create
138 ) as (
139 mock_get_components,
140 mock_get_component,
141 mock_create_component,
142 mock_update_component,
143 mock_delete_component,
144 ):
145 with self.assertRaises(AnsibleExitJson) as exec_info:
146 self.module.main()
147
148 self.assertEqual(len(mock_get_components.mock_calls), 1)
149 self.assertEqual(len(mock_get_component.mock_calls), 0)
150 self.assertEqual(len(mock_create_component.mock_calls), 1)
151 self.assertEqual(len(mock_update_component.mock_calls), 0)
152 self.assertEqual(len(mock_delete_component.mock_calls), 0)
153
154 # must not contain parent_id
155 mock_create_component.assert_called_once_with(
156 {
157 "name": "testkey",
158 "providerId": "rsa",
159 "providerType": "org.keycloak.keys.KeyProvider",
160 "config": {
161 "priority": ["0"],
162 "enabled": ["true"],
163 "privateKey": ["privatekey"],
164 "algorithm": ["RS256"],
165 "certificate": ["foo"],
166 "active": ["true"],
167 },
168 },
169 "realm-name",
170 )
171
172 # Verify that the module's changed status matches what is expected
173 self.assertIs(exec_info.exception.args[0]["changed"], changed)
174
175 def test_create_when_present(self):
176 """Update existing realm key"""
177
178 module_args = {
179 "auth_keycloak_url": "http://keycloak.url/auth",
180 "auth_realm": "master",
181 "auth_username": "admin",
182 "auth_password": "admin",
183 "parent_id": "realm-name",
184 "name": "testkey",
185 "state": "present",
186 "provider_id": "rsa",
187 "config": {
188 "priority": 0,
189 "enabled": True,
190 "private_key": "privatekey",
191 "algorithm": "RS256",
192 "certificate": "foo",
193 },
194 }
195 return_value_components_get = [
196 [
197 {
198 "id": "c1a957aa-3df0-4f70-9418-44202bf4ae1f",
199 "name": "testkey",
200 "providerId": "rsa",
201 "providerType": "org.keycloak.keys.KeyProvider",
202 "parentId": "90c8fef9-15f8-4d5b-8b22-44e2e1cdcd09",
203 "config": {
204 "privateKey": ["**********"],
205 "certificate": ["foo"],
206 "active": ["true"],
207 "priority": ["122"],
208 "enabled": ["true"],
209 "algorithm": ["RS256"],
210 },
211 },
212 ],
213 [],
214 [],
215 ]
216 return_value_component_update = [None]
217 changed = True
218
219 # Run the module
220
221 with set_module_args(module_args):
222 with mock_good_connection():
223 with patch_keycloak_api(
224 get_components=return_value_components_get, update_component=return_value_component_update
225 ) as (
226 mock_get_components,
227 mock_get_component,
228 mock_create_component,
229 mock_update_component,
230 mock_delete_component,
231 ):
232 with self.assertRaises(AnsibleExitJson) as exec_info:
233 self.module.main()
234
235 self.assertEqual(len(mock_get_components.mock_calls), 1)
236 self.assertEqual(len(mock_get_component.mock_calls), 0)
237 self.assertEqual(len(mock_create_component.mock_calls), 0)
238 self.assertEqual(len(mock_update_component.mock_calls), 1)
239 self.assertEqual(len(mock_delete_component.mock_calls), 0)
240
241 # Verify that the module's changed status matches what is expected
242 self.assertIs(exec_info.exception.args[0]["changed"], changed)
243
244 def test_delete_when_absent(self):
245 """Remove an absent realm key"""
246
247 module_args = {
248 "auth_keycloak_url": "http://keycloak.url/auth",
249 "auth_realm": "master",
250 "auth_username": "admin",
251 "auth_password": "admin",
252 "parent_id": "realm-name",
253 "name": "testkey",
254 "state": "absent",
255 "provider_id": "rsa",
256 "config": {
257 "priority": 0,
258 "enabled": True,
259 "private_key": "privatekey",
260 "algorithm": "RS256",
261 "certificate": "foo",
262 },
263 }
264 return_value_components_get = [[]]
265 changed = False
266
267 # Run the module
268
269 with set_module_args(module_args):
270 with mock_good_connection():
271 with patch_keycloak_api(get_components=return_value_components_get) as (
272 mock_get_components,
273 mock_get_component,
274 mock_create_component,
275 mock_update_component,
276 mock_delete_component,
277 ):
278 with self.assertRaises(AnsibleExitJson) as exec_info:
279 self.module.main()
280
281 self.assertEqual(len(mock_get_components.mock_calls), 1)
282 self.assertEqual(len(mock_get_component.mock_calls), 0)
283 self.assertEqual(len(mock_create_component.mock_calls), 0)
284 self.assertEqual(len(mock_update_component.mock_calls), 0)
285 self.assertEqual(len(mock_delete_component.mock_calls), 0)
286
287 # Verify that the module's changed status matches what is expected
288 self.assertIs(exec_info.exception.args[0]["changed"], changed)
289
290 def test_delete_when_present(self):
291 """Remove an existing realm key"""
292
293 module_args = {
294 "auth_keycloak_url": "http://keycloak.url/auth",
295 "auth_realm": "master",
296 "auth_username": "admin",
297 "auth_password": "admin",
298 "parent_id": "realm-name",
299 "name": "testkey",
300 "state": "absent",
301 "provider_id": "rsa",
302 "config": {
303 "priority": 0,
304 "enabled": True,
305 "private_key": "privatekey",
306 "algorithm": "RS256",
307 "certificate": "foo",
308 },
309 }
310
311 return_value_components_get = [
312 [
313 {
314 "id": "c1a957aa-3df0-4f70-9418-44202bf4ae1f",
315 "name": "testkey",
316 "providerId": "rsa",
317 "providerType": "org.keycloak.keys.KeyProvider",
318 "parentId": "90c8fef9-15f8-4d5b-8b22-44e2e1cdcd09",
319 "config": {
320 "privateKey": ["**********"],
321 "certificate": ["foo"],
322 "active": ["true"],
323 "priority": ["122"],
324 "enabled": ["true"],
325 "algorithm": ["RS256"],
326 },
327 },
328 ],
329 [],
330 [],
331 ]
332 return_value_component_delete = [None]
333 changed = True
334
335 # Run the module
336
337 with set_module_args(module_args):
338 with mock_good_connection():
339 with patch_keycloak_api(
340 get_components=return_value_components_get, delete_component=return_value_component_delete
341 ) as (
342 mock_get_components,
343 mock_get_component,
344 mock_create_component,
345 mock_update_component,
346 mock_delete_component,
347 ):
348 with self.assertRaises(AnsibleExitJson) as exec_info:
349 self.module.main()
350
351 self.assertEqual(len(mock_get_components.mock_calls), 1)
352 self.assertEqual(len(mock_get_component.mock_calls), 0)
353 self.assertEqual(len(mock_create_component.mock_calls), 0)
354 self.assertEqual(len(mock_update_component.mock_calls), 0)
355 self.assertEqual(len(mock_delete_component.mock_calls), 1)
356
357 # Verify that the module's changed status matches what is expected
358 self.assertIs(exec_info.exception.args[0]["changed"], changed)