Debian Codegraph @

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

raw
1 # Copyright Jakub Danek <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or
3 # https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 from contextlib import contextmanager
9 from io import StringIO
10 from itertools import count
11 from unittest.mock import patch
12
13 from ansible_collections.community.internal_test_tools.tests.unit.plugins.modules.utils import (
14 AnsibleExitJson,
15 ModuleTestCase,
16 set_module_args,
17 )
18
19 from ansible_collections.community.general.plugins.modules import keycloak_realm_localization
20
21
22 @contextmanager
23 def patch_keycloak_api(get_localization_values=None, set_localization_value=None, delete_localization_value=None):
24 """
25 Patch KeycloakAPI methods used by the module under test.
26 """
27 obj = keycloak_realm_localization.KeycloakAPI
28 with patch.object(obj, "get_localization_values", side_effect=get_localization_values) as mock_get_values:
29 with patch.object(obj, "set_localization_value", side_effect=set_localization_value) as mock_set_value:
30 with patch.object(
31 obj, "delete_localization_value", side_effect=delete_localization_value
32 ) as mock_del_value:
33 yield mock_get_values, mock_set_value, mock_del_value
34
35
36 def get_response(object_with_future_response, method, get_id_call_count):
37 if callable(object_with_future_response):
38 return object_with_future_response()
39 if isinstance(object_with_future_response, dict):
40 return get_response(object_with_future_response[method], method, get_id_call_count)
41 if isinstance(object_with_future_response, list):
42 call_number = next(get_id_call_count)
43 return get_response(object_with_future_response[call_number], method, get_id_call_count)
44 return object_with_future_response
45
46
47 def build_mocked_request(get_id_user_count, response_dict):
48 def _mocked_requests(*args, **kwargs):
49 url = args[0]
50 method = kwargs["method"]
51 future_response = response_dict.get(url, None)
52 return get_response(future_response, method, get_id_user_count)
53
54 return _mocked_requests
55
56
57 def create_wrapper(text_as_string):
58 """Allow to mock many times a call to one address.
59 Without this function, the StringIO is empty for the second call.
60 """
61
62 def _create_wrapper():
63 return StringIO(text_as_string)
64
65 return _create_wrapper
66
67
68 def mock_good_connection():
69 token_response = {
70 "http://keycloak.url/auth/realms/master/protocol/openid-connect/token": create_wrapper(
71 '{"access_token": "alongtoken"}'
72 ),
73 }
74 return patch(
75 "ansible_collections.community.general.plugins.module_utils._keycloak.open_url",
76 side_effect=build_mocked_request(count(), token_response),
77 autospec=True,
78 )
79
80
81 class TestKeycloakRealmLocalization(ModuleTestCase):
82 def setUp(self):
83 super().setUp()
84 self.module = keycloak_realm_localization
85
86 def test_present_no_change_in_sync(self):
87 """Desired overrides already match, no change."""
88 module_args = {
89 "auth_keycloak_url": "http://keycloak.url/auth",
90 "token": "{{ access_token }}",
91 "parent_id": "my-realm",
92 "locale": "en",
93 "state": "present",
94 "overrides": [
95 {"key": "greeting", "value": "Hello"},
96 {"key": "farewell", "value": "Bye"},
97 ],
98 }
99 # get_localization_values is called twice: before and after
100 return_value_get_localization_values = [
101 {"greeting": "Hello", "farewell": "Bye"},
102 {"greeting": "Hello", "farewell": "Bye"},
103 ]
104
105 with set_module_args(module_args):
106 with mock_good_connection():
107 with patch_keycloak_api(get_localization_values=return_value_get_localization_values) as (
108 mock_get_values,
109 mock_set_value,
110 mock_del_value,
111 ):
112 with self.assertRaises(AnsibleExitJson) as exec_info:
113 self.module.main()
114
115 self.assertEqual(mock_get_values.call_count, 2)
116 self.assertEqual(mock_set_value.call_count, 0)
117 self.assertEqual(mock_del_value.call_count, 0)
118 self.assertIs(exec_info.exception.args[0]["changed"], False)
119
120 def test_present_check_mode_only_reports(self):
121 """Check mode: report changes, do not call API mutators."""
122 module_args = {
123 "auth_keycloak_url": "http://keycloak.url/auth",
124 "token": "{{ access_token }}",
125 "parent_id": "my-realm",
126 "locale": "en",
127 "state": "present",
128 "overrides": [
129 {"key": "x", "value": "1"}, # change
130 {"key": "y", "value": "2"}, # create
131 ],
132 "_ansible_check_mode": True, # signal for readers; set_module_args is what matters
133 }
134 return_value_get_localization_values = [
135 {"x": "0"},
136 ]
137
138 with set_module_args(module_args):
139 with mock_good_connection():
140 with patch_keycloak_api(get_localization_values=return_value_get_localization_values) as (
141 mock_get_values,
142 mock_set_value,
143 mock_del_value,
144 ):
145 with self.assertRaises(AnsibleExitJson) as exec_info:
146 self.module.main()
147
148 # Only read current values
149 self.assertEqual(mock_get_values.call_count, 1)
150 self.assertEqual(mock_set_value.call_count, 0)
151 self.assertEqual(mock_del_value.call_count, 0)
152 self.assertIs(exec_info.exception.args[0]["changed"], True)
153 self.assertIn("would be updated", exec_info.exception.args[0]["msg"])
154
155 def test_absent_idempotent_when_nothing_to_delete(self):
156 """No change when locale has no overrides."""
157 module_args = {
158 "auth_keycloak_url": "http://keycloak.url/auth",
159 "token": "{{ access_token }}",
160 "parent_id": "my-realm",
161 "locale": "en",
162 "state": "absent",
163 }
164 return_value_get_localization_values = [
165 {},
166 ]
167
168 with set_module_args(module_args):
169 with mock_good_connection():
170 with patch_keycloak_api(get_localization_values=return_value_get_localization_values) as (
171 mock_get_values,
172 mock_set_value,
173 mock_del_value,
174 ):
175 with self.assertRaises(AnsibleExitJson) as exec_info:
176 self.module.main()
177
178 self.assertEqual(mock_get_values.call_count, 1)
179 self.assertEqual(mock_del_value.call_count, 0)
180 self.assertEqual(mock_set_value.call_count, 0)
181 self.assertIs(exec_info.exception.args[0]["changed"], False)
182
183 def test_present_value_defaults_to_empty_string(self):
184 """When value is omitted, it defaults to empty string."""
185 module_args = {
186 "auth_keycloak_url": "http://keycloak.url/auth",
187 "token": "{{ access_token }}",
188 "parent_id": "my-realm",
189 "locale": "en",
190 "state": "present",
191 "overrides": [
192 {"key": "greeting"}, # value omitted, should default to ""
193 ],
194 }
195 # Before: greeting="Hello"; After: greeting="" (empty string)
196 return_value_get_localization_values = [
197 {"greeting": "Hello"},
198 {"greeting": ""},
199 ]
200 return_value_set = [None]
201
202 with set_module_args(module_args):
203 with mock_good_connection():
204 with patch_keycloak_api(
205 get_localization_values=return_value_get_localization_values,
206 set_localization_value=return_value_set,
207 ) as (mock_get_values, mock_set_value, mock_del_value):
208 with self.assertRaises(AnsibleExitJson) as exec_info:
209 self.module.main()
210
211 self.assertEqual(mock_get_values.call_count, 2)
212 self.assertEqual(mock_del_value.call_count, 0)
213 # One set call to update 'greeting' to empty string
214 self.assertEqual(mock_set_value.call_count, 1)
215 self.assertIs(exec_info.exception.args[0]["changed"], True)
216
217 def test_present_append_true_preserves_unspecified_keys(self):
218 """With append=True, only modify specified keys, preserve others."""
219 module_args = {
220 "auth_keycloak_url": "http://keycloak.url/auth",
221 "token": "{{ access_token }}",
222 "parent_id": "my-realm",
223 "locale": "en",
224 "state": "present",
225 "force": False,
226 "overrides": [
227 {"key": "a", "value": "1-updated"}, # update existing
228 {"key": "c", "value": "3"}, # create new
229 ],
230 }
231 # Before: a=1, b=2; After: a=1-updated, b=2, c=3 (b is preserved)
232 return_value_get_localization_values = [
233 {"a": "1", "b": "2"},
234 {"a": "1-updated", "b": "2", "c": "3"},
235 ]
236 return_value_set = [None, None]
237
238 with set_module_args(module_args):
239 with mock_good_connection():
240 with patch_keycloak_api(
241 get_localization_values=return_value_get_localization_values,
242 set_localization_value=return_value_set,
243 ) as (mock_get_values, mock_set_value, mock_del_value):
244 with self.assertRaises(AnsibleExitJson) as exec_info:
245 self.module.main()
246
247 self.assertEqual(mock_get_values.call_count, 2)
248 # No deletes - key 'b' should be preserved
249 self.assertEqual(mock_del_value.call_count, 0)
250 # Two set calls: update 'a', create 'c'
251 self.assertEqual(mock_set_value.call_count, 2)
252 self.assertIs(exec_info.exception.args[0]["changed"], True)
253
254 def test_present_append_false_removes_unspecified_keys(self):
255 """With append=False, create new, update existing, and delete unspecified keys."""
256 module_args = {
257 "auth_keycloak_url": "http://keycloak.url/auth",
258 "token": "{{ access_token }}",
259 "parent_id": "my-realm",
260 "locale": "en",
261 "state": "present",
262 "force": True,
263 "overrides": [
264 {"key": "a", "value": "1-updated"}, # update
265 {"key": "c", "value": "3"}, # create
266 ],
267 }
268 # Before: a=1, b=2; After: a=1-updated, c=3 (b is removed)
269 return_value_get_localization_values = [
270 {"a": "1", "b": "2"},
271 {"a": "1-updated", "c": "3"},
272 ]
273 return_value_set = [None, None]
274 return_value_delete = [None]
275
276 with set_module_args(module_args):
277 with mock_good_connection():
278 with patch_keycloak_api(
279 get_localization_values=return_value_get_localization_values,
280 set_localization_value=return_value_set,
281 delete_localization_value=return_value_delete,
282 ) as (mock_get_values, mock_set_value, mock_del_value):
283 with self.assertRaises(AnsibleExitJson) as exec_info:
284 self.module.main()
285
286 self.assertEqual(mock_get_values.call_count, 2)
287 # One delete for 'b'
288 self.assertEqual(mock_del_value.call_count, 1)
289 # Two set calls: update 'a', create 'c'
290 self.assertEqual(mock_set_value.call_count, 2)
291 self.assertIs(exec_info.exception.args[0]["changed"], True)
292
293 def test_absent_append_true_removes_only_specified_keys(self):
294 """With state=absent and append=True, remove only specified keys."""
295 module_args = {
296 "auth_keycloak_url": "http://keycloak.url/auth",
297 "token": "{{ access_token }}",
298 "parent_id": "my-realm",
299 "locale": "en",
300 "state": "absent",
301 "force": False,
302 "overrides": [
303 {"key": "a"},
304 ],
305 }
306 # Before: a=1, b=2; Remove only 'a', keep 'b'
307 return_value_get_localization_values = [
308 {"a": "1", "b": "2"},
309 ]
310 return_value_delete = [None]
311
312 with set_module_args(module_args):
313 with mock_good_connection():
314 with patch_keycloak_api(
315 get_localization_values=return_value_get_localization_values,
316 delete_localization_value=return_value_delete,
317 ) as (mock_get_values, mock_set_value, mock_del_value):
318 with self.assertRaises(AnsibleExitJson) as exec_info:
319 self.module.main()
320
321 self.assertEqual(mock_get_values.call_count, 1)
322 # One delete for 'a' only
323 self.assertEqual(mock_del_value.call_count, 1)
324 self.assertEqual(mock_set_value.call_count, 0)
325 self.assertIs(exec_info.exception.args[0]["changed"], True)
326
327 def test_absent_append_false_removes_all_keys(self):
328 """With state=absent and append=False, remove all keys."""
329 module_args = {
330 "auth_keycloak_url": "http://keycloak.url/auth",
331 "token": "{{ access_token }}",
332 "parent_id": "my-realm",
333 "locale": "en",
334 "state": "absent",
335 "force": True,
336 }
337 # Before: a=1, b=2; Remove all
338 return_value_get_localization_values = [
339 {"a": "1", "b": "2"},
340 ]
341 return_value_delete = [None, None]
342
343 with set_module_args(module_args):
344 with mock_good_connection():
345 with patch_keycloak_api(
346 get_localization_values=return_value_get_localization_values,
347 delete_localization_value=return_value_delete,
348 ) as (mock_get_values, mock_set_value, mock_del_value):
349 with self.assertRaises(AnsibleExitJson) as exec_info:
350 self.module.main()
351
352 self.assertEqual(mock_get_values.call_count, 1)
353 # Two deletes for 'a' and 'b'
354 self.assertEqual(mock_del_value.call_count, 2)
355 self.assertEqual(mock_set_value.call_count, 0)
356 self.assertIs(exec_info.exception.args[0]["changed"], True)