Debian Codegraph @

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