Debian Codegraph @

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

raw
1 # Copyright (c) 2024, 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 json import dumps
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_userprofile
20
21
22 @contextmanager
23 def patch_keycloak_api(
24 get_components=None, get_component=None, create_component=None, update_component=None, delete_component=None
25 ):
26 """Mock context manager for patching the methods in KeycloakAPI"""
27
28 obj = keycloak_userprofile.KeycloakAPI
29 with patch.object(obj, "get_components", side_effect=get_components) as mock_get_components:
30 with patch.object(obj, "get_component", side_effect=get_component) as mock_get_component:
31 with patch.object(obj, "create_component", side_effect=create_component) as mock_create_component:
32 with patch.object(obj, "update_component", side_effect=update_component) as mock_update_component:
33 with patch.object(obj, "delete_component", side_effect=delete_component) as mock_delete_component:
34 yield (
35 mock_get_components,
36 mock_get_component,
37 mock_create_component,
38 mock_update_component,
39 mock_delete_component,
40 )
41
42
43 def get_response(object_with_future_response, method, get_id_call_count):
44 if callable(object_with_future_response):
45 return object_with_future_response()
46 if isinstance(object_with_future_response, dict):
47 return get_response(object_with_future_response[method], method, get_id_call_count)
48 if isinstance(object_with_future_response, list):
49 call_number = next(get_id_call_count)
50 return get_response(object_with_future_response[call_number], method, get_id_call_count)
51 return object_with_future_response
52
53
54 def build_mocked_request(get_id_user_count, response_dict):
55 def _mocked_requests(*args, **kwargs):
56 url = args[0]
57 method = kwargs["method"]
58 future_response = response_dict.get(url, None)
59 return get_response(future_response, method, get_id_user_count)
60
61 return _mocked_requests
62
63
64 def create_wrapper(text_as_string):
65 """Allow to mock many times a call to one address.
66 Without this function, the StringIO is empty for the second call.
67 """
68
69 def _create_wrapper():
70 return StringIO(text_as_string)
71
72 return _create_wrapper
73
74
75 def mock_good_connection():
76 token_response = {
77 "http://keycloak.url/auth/realms/master/protocol/openid-connect/token": create_wrapper(
78 '{"access_token": "alongtoken"}'
79 ),
80 }
81 return patch(
82 "ansible_collections.community.general.plugins.module_utils._keycloak.open_url",
83 side_effect=build_mocked_request(count(), token_response),
84 autospec=True,
85 )
86
87
88 class TestKeycloakUserprofile(ModuleTestCase):
89 def setUp(self):
90 super().setUp()
91 self.module = keycloak_userprofile
92
93 def test_create_when_absent(self):
94 """Add a new userprofile"""
95
96 module_args = {
97 "auth_keycloak_url": "http://keycloak.url/auth",
98 "auth_realm": "master",
99 "auth_username": "admin",
100 "auth_password": "admin",
101 "parent_id": "realm-name",
102 "state": "present",
103 "provider_id": "declarative-user-profile",
104 "config": {
105 "kc_user_profile_config": [
106 {
107 "attributes": [
108 {
109 "annotations": {},
110 "displayName": "${username}",
111 "multivalued": False,
112 "name": "username",
113 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
114 "required": None,
115 "validations": {
116 "length": {"max": 255, "min": 3},
117 "up_username_not_idn_homograph": {},
118 "username_prohibited_characters": {},
119 },
120 },
121 {
122 "annotations": {},
123 "displayName": "${email}",
124 "multivalued": False,
125 "name": "email",
126 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
127 "required": {"roles": ["user"]},
128 "validations": {"email": {}, "length": {"max": 255}},
129 },
130 {
131 "annotations": {},
132 "displayName": "${firstName}",
133 "multivalued": False,
134 "name": "firstName",
135 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
136 "required": {"roles": ["user"]},
137 "validations": {"length": {"max": 255}, "person_name_prohibited_characters": {}},
138 },
139 {
140 "annotations": {},
141 "displayName": "${lastName}",
142 "multivalued": False,
143 "name": "lastName",
144 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
145 "required": {"roles": ["user"]},
146 "validations": {"length": {"max": 255}, "person_name_prohibited_characters": {}},
147 },
148 {
149 "annotations": {},
150 "displayName": "${testAttr}",
151 "multivalued": False,
152 "name": "testAttr",
153 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
154 "required": {"roles": ["user"]},
155 "validations": {
156 "integer": {"min": 0, "max": 255},
157 "double": {},
158 "iso_date": {},
159 "local_date": {},
160 },
161 },
162 {
163 "annotations": {},
164 "displayName": "${testAttr2}",
165 "multivalued": True,
166 "name": "testAttr2",
167 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
168 "required": {"roles": ["user"]},
169 "validations": {
170 "multivalued": {"min": 0, "max": 5},
171 },
172 },
173 ],
174 "groups": [
175 {
176 "displayDescription": "Attributes, which refer to user metadata",
177 "displayHeader": "User metadata",
178 "name": "user-metadata",
179 }
180 ],
181 }
182 ]
183 },
184 }
185 return_value_component_create = [
186 {
187 "id": "4ba43451-6bb4-4b50-969f-e890539f15e3",
188 "parentId": "realm-name",
189 "providerId": "declarative-user-profile",
190 "providerType": "org.keycloak.userprofile.UserProfileProvider",
191 "config": {
192 "kc.user.profile.config": [
193 {
194 "attributes": [
195 {
196 "name": "username",
197 "displayName": "${username}",
198 "validations": {
199 "length": {"min": 3, "max": 255},
200 "username-prohibited-characters": {},
201 "up-username-not-idn-homograph": {},
202 },
203 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
204 "multivalued": False,
205 "annotations": {},
206 "required": None,
207 },
208 {
209 "name": "email",
210 "displayName": "${email}",
211 "validations": {"email": {}, "length": {"max": 255}},
212 "required": {"roles": ["user"]},
213 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
214 "multivalued": False,
215 "annotations": {},
216 },
217 {
218 "name": "firstName",
219 "displayName": "${firstName}",
220 "validations": {"length": {"max": 255}, "person-name-prohibited-characters": {}},
221 "required": {"roles": ["user"]},
222 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
223 "multivalued": False,
224 "annotations": {},
225 },
226 {
227 "name": "lastName",
228 "displayName": "${lastName}",
229 "validations": {"length": {"max": 255}, "person-name-prohibited-characters": {}},
230 "required": {"roles": ["user"]},
231 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
232 "multivalued": False,
233 "annotations": {},
234 },
235 {
236 "annotations": {},
237 "displayName": "${testAttr}",
238 "multivalued": False,
239 "name": "testAttr",
240 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
241 "required": {"roles": ["user"]},
242 "validations": {
243 "integer": {"min": 0, "max": 255},
244 "double": {},
245 "iso_date": {},
246 "local_date": {},
247 },
248 },
249 {
250 "annotations": {},
251 "displayName": "${testAttr2}",
252 "multivalued": True,
253 "name": "testAttr2",
254 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
255 "required": {"roles": ["user"]},
256 "validations": {
257 "multivalued": {"min": 0, "max": 5},
258 },
259 },
260 ],
261 "groups": [
262 {
263 "name": "user-metadata",
264 "displayHeader": "User metadata",
265 "displayDescription": "Attributes, which refer to user metadata",
266 }
267 ],
268 }
269 ]
270 },
271 }
272 ]
273 return_value_get_components_get = [[], []]
274 changed = True
275
276 # Run the module
277
278 with set_module_args(module_args):
279 with mock_good_connection():
280 with patch_keycloak_api(
281 get_components=return_value_get_components_get, create_component=return_value_component_create
282 ) as (
283 mock_get_components,
284 mock_get_component,
285 mock_create_component,
286 mock_update_component,
287 mock_delete_component,
288 ):
289 with self.assertRaises(AnsibleExitJson) as exec_info:
290 self.module.main()
291
292 self.assertEqual(len(mock_get_components.mock_calls), 1)
293 self.assertEqual(len(mock_get_component.mock_calls), 0)
294 self.assertEqual(len(mock_create_component.mock_calls), 1)
295 self.assertEqual(len(mock_update_component.mock_calls), 0)
296 self.assertEqual(len(mock_delete_component.mock_calls), 0)
297
298 # Verify that the module's changed status matches what is expected
299 self.assertIs(exec_info.exception.args[0]["changed"], changed)
300
301 def test_create_when_present(self):
302 """Update existing userprofile"""
303
304 module_args = {
305 "auth_keycloak_url": "http://keycloak.url/auth",
306 "auth_realm": "master",
307 "auth_username": "admin",
308 "auth_password": "admin",
309 "parent_id": "realm-name",
310 "state": "present",
311 "provider_id": "declarative-user-profile",
312 "config": {
313 "kc_user_profile_config": [
314 {
315 "attributes": [
316 {
317 "annotations": {},
318 "displayName": "${username}",
319 "multivalued": False,
320 "name": "username",
321 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
322 "required": None,
323 "validations": {
324 "length": {"max": 255, "min": 3},
325 "up_username_not_idn_homograph": {},
326 "username_prohibited_characters": {},
327 },
328 },
329 {
330 "annotations": {},
331 "displayName": "${email}",
332 "multivalued": False,
333 "name": "email",
334 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
335 "required": {"roles": ["user"]},
336 "validations": {"email": {}, "length": {"max": 255}},
337 },
338 {
339 "annotations": {},
340 "displayName": "${firstName}",
341 "multivalued": False,
342 "name": "firstName",
343 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
344 "required": {"roles": ["user"]},
345 "validations": {"length": {"max": 255}, "person_name_prohibited_characters": {}},
346 },
347 {
348 "annotations": {},
349 "displayName": "${lastName}",
350 "multivalued": False,
351 "name": "lastName",
352 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
353 "required": {"roles": ["user"]},
354 "validations": {"length": {"max": 255}, "person_name_prohibited_characters": {}},
355 },
356 {
357 "annotations": {},
358 "displayName": "${testAttr}",
359 "multivalued": False,
360 "name": "testAttr",
361 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
362 "required": {"roles": ["user"]},
363 "validations": {
364 "integer": {"min": 0, "max": 255},
365 "double": {},
366 "iso_date": {},
367 "local_date": {},
368 },
369 },
370 {
371 "annotations": {},
372 "displayName": "${testAttr2}",
373 "multivalued": True,
374 "name": "testAttr2",
375 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
376 "required": {"roles": ["user"]},
377 "validations": {
378 "multivalued": {"min": 0, "max": 5},
379 },
380 },
381 ],
382 "groups": [
383 {
384 "displayDescription": "Attributes, which refer to user metadata",
385 "displayHeader": "User metadata",
386 "name": "user-metadata",
387 }
388 ],
389 }
390 ]
391 },
392 }
393 return_value_get_components_get = [
394 [
395 {
396 "id": "4ba43451-6bb4-4b50-969f-e890539f15e3",
397 "parentId": "realm-1",
398 "providerId": "declarative-user-profile",
399 "providerType": "org.keycloak.userprofile.UserProfileProvider",
400 "config": {
401 "kc.user.profile.config": [
402 dumps(
403 {
404 "attributes": [
405 {
406 "name": "username",
407 "displayName": "${username}",
408 "validations": {
409 "length": {"min": 3, "max": 255},
410 "username-prohibited-characters": {},
411 "up-username-not-idn-homograph": {},
412 },
413 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
414 "multivalued": False,
415 "annotations": {},
416 "required": None,
417 },
418 {
419 "name": "email",
420 "displayName": "${email}",
421 "validations": {"email": {}, "length": {"max": 255}},
422 "required": {"roles": ["user"]},
423 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
424 "multivalued": False,
425 "annotations": {},
426 },
427 {
428 "name": "firstName",
429 "displayName": "${firstName}",
430 "validations": {
431 "length": {"max": 255},
432 "person-name-prohibited-characters": {},
433 },
434 "required": {"roles": ["user"]},
435 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
436 "multivalued": False,
437 "annotations": {},
438 },
439 {
440 "name": "lastName",
441 "displayName": "${lastName}",
442 "validations": {
443 "length": {"max": 255},
444 "person-name-prohibited-characters": {},
445 },
446 "required": {"roles": ["user"]},
447 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
448 "multivalued": False,
449 "annotations": {},
450 },
451 {
452 "annotations": {},
453 "displayName": "${testAttr}",
454 "multivalued": False,
455 "name": "testAttr",
456 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
457 "required": {"roles": ["user"]},
458 "validations": {
459 "integer": {"min": 0, "max": 255},
460 "double": {},
461 "iso_date": {},
462 "local_date": {},
463 },
464 },
465 {
466 "annotations": {},
467 "displayName": "${testAttr2}",
468 "multivalued": True,
469 "name": "testAttr2",
470 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
471 "required": {"roles": ["user"]},
472 "validations": {
473 "multivalued": {"min": 0, "max": 5},
474 },
475 },
476 ],
477 "groups": [
478 {
479 "name": "user-metadata",
480 "displayHeader": "User metadata",
481 "displayDescription": "Attributes, which refer to user metadata",
482 }
483 ],
484 }
485 )
486 ]
487 },
488 }
489 ],
490 [],
491 ]
492 return_value_component_update = [None]
493 changed = True
494
495 # Run the module
496
497 with set_module_args(module_args):
498 with mock_good_connection():
499 with patch_keycloak_api(
500 get_components=return_value_get_components_get, update_component=return_value_component_update
501 ) as (
502 mock_get_components,
503 mock_get_component,
504 mock_create_component,
505 mock_update_component,
506 mock_delete_component,
507 ):
508 with self.assertRaises(AnsibleExitJson) as exec_info:
509 self.module.main()
510
511 self.assertEqual(len(mock_get_components.mock_calls), 1)
512 self.assertEqual(len(mock_get_component.mock_calls), 0)
513 self.assertEqual(len(mock_create_component.mock_calls), 0)
514 self.assertEqual(len(mock_update_component.mock_calls), 1)
515 self.assertEqual(len(mock_delete_component.mock_calls), 0)
516
517 # Verify that the module's changed status matches what is expected
518 self.assertIs(exec_info.exception.args[0]["changed"], changed)
519
520 def test_delete_when_absent(self):
521 """Remove an absent userprofile"""
522
523 module_args = {
524 "auth_keycloak_url": "http://keycloak.url/auth",
525 "auth_realm": "master",
526 "auth_username": "admin",
527 "auth_password": "admin",
528 "parent_id": "realm-name",
529 "provider_id": "declarative-user-profile",
530 "state": "absent",
531 }
532 return_value_get_components_get = [[]]
533 changed = False
534
535 # Run the module
536
537 with set_module_args(module_args):
538 with mock_good_connection():
539 with patch_keycloak_api(get_components=return_value_get_components_get) as (
540 mock_get_components,
541 mock_get_component,
542 mock_create_component,
543 mock_update_component,
544 mock_delete_component,
545 ):
546 with self.assertRaises(AnsibleExitJson) as exec_info:
547 self.module.main()
548
549 self.assertEqual(len(mock_get_components.mock_calls), 1)
550 self.assertEqual(len(mock_get_component.mock_calls), 0)
551 self.assertEqual(len(mock_create_component.mock_calls), 0)
552 self.assertEqual(len(mock_update_component.mock_calls), 0)
553 self.assertEqual(len(mock_delete_component.mock_calls), 0)
554
555 # Verify that the module's changed status matches what is expected
556 self.assertIs(exec_info.exception.args[0]["changed"], changed)
557
558 def test_delete_when_present(self):
559 """Remove an existing userprofile"""
560
561 module_args = {
562 "auth_keycloak_url": "http://keycloak.url/auth",
563 "auth_realm": "master",
564 "auth_username": "admin",
565 "auth_password": "admin",
566 "parent_id": "realm-name",
567 "provider_id": "declarative-user-profile",
568 "state": "absent",
569 }
570 return_value_get_components_get = [
571 [
572 {
573 "id": "4ba43451-6bb4-4b50-969f-e890539f15e3",
574 "parentId": "realm-1",
575 "providerId": "declarative-user-profile",
576 "providerType": "org.keycloak.userprofile.UserProfileProvider",
577 "config": {
578 "kc.user.profile.config": [
579 dumps(
580 {
581 "attributes": [
582 {
583 "name": "username",
584 "displayName": "${username}",
585 "validations": {
586 "length": {"min": 3, "max": 255},
587 "username-prohibited-characters": {},
588 "up-username-not-idn-homograph": {},
589 },
590 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
591 "multivalued": False,
592 "annotations": {},
593 "required": None,
594 },
595 {
596 "name": "email",
597 "displayName": "${email}",
598 "validations": {"email": {}, "length": {"max": 255}},
599 "required": {"roles": ["user"]},
600 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
601 "multivalued": False,
602 "annotations": {},
603 },
604 {
605 "name": "firstName",
606 "displayName": "${firstName}",
607 "validations": {
608 "length": {"max": 255},
609 "person-name-prohibited-characters": {},
610 },
611 "required": {"roles": ["user"]},
612 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
613 "multivalued": False,
614 "annotations": {},
615 },
616 {
617 "name": "lastName",
618 "displayName": "${lastName}",
619 "validations": {
620 "length": {"max": 255},
621 "person-name-prohibited-characters": {},
622 },
623 "required": {"roles": ["user"]},
624 "permissions": {"view": ["admin", "user"], "edit": ["admin", "user"]},
625 "multivalued": False,
626 "annotations": {},
627 },
628 {
629 "annotations": {},
630 "displayName": "${testAttr}",
631 "multivalued": False,
632 "name": "testAttr",
633 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
634 "required": {"roles": ["user"]},
635 "validations": {
636 "integer": {"min": 0, "max": 255},
637 "double": {},
638 "iso_date": {},
639 "local_date": {},
640 },
641 },
642 {
643 "annotations": {},
644 "displayName": "${testAttr2}",
645 "multivalued": True,
646 "name": "testAttr2",
647 "permissions": {"edit": ["admin", "user"], "view": ["admin", "user"]},
648 "required": {"roles": ["user"]},
649 "validations": {
650 "multivalued": {"min": 0, "max": 5},
651 },
652 },
653 ],
654 "groups": [
655 {
656 "name": "user-metadata",
657 "displayHeader": "User metadata",
658 "displayDescription": "Attributes, which refer to user metadata",
659 }
660 ],
661 }
662 )
663 ]
664 },
665 }
666 ],
667 [],
668 ]
669 return_value_component_delete = [None]
670 changed = True
671
672 # Run the module
673
674 with set_module_args(module_args):
675 with mock_good_connection():
676 with patch_keycloak_api(
677 get_components=return_value_get_components_get, delete_component=return_value_component_delete
678 ) as (
679 mock_get_components,
680 mock_get_component,
681 mock_create_component,
682 mock_update_component,
683 mock_delete_component,
684 ):
685 with self.assertRaises(AnsibleExitJson) as exec_info:
686 self.module.main()
687
688 self.assertEqual(len(mock_get_components.mock_calls), 1)
689 self.assertEqual(len(mock_get_component.mock_calls), 0)
690 self.assertEqual(len(mock_create_component.mock_calls), 0)
691 self.assertEqual(len(mock_update_component.mock_calls), 0)
692 self.assertEqual(len(mock_delete_component.mock_calls), 1)
693
694 # Verify that the module's changed status matches what is expected
695 self.assertIs(exec_info.exception.args[0]["changed"], changed)