Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/modules/test_keycloak_realm.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
19
20
21 @contextmanager
22 def patch_keycloak_api(get_realm_by_id, create_realm=None, update_realm=None, delete_realm=None):
23 """Mock context manager for patching the methods in PwPolicyIPAClient that contact the IPA server
24
25 Patches the `login` and `_post_json` methods
26
27 Keyword arguments are passed to the mock object that patches `_post_json`
28
29 No arguments are passed to the mock object that patches `login` because no tests require it
30
31 Example::
32
33 with patch_ipa(return_value={}) as (mock_login, mock_post):
34 ...
35 """
36
37 obj = keycloak_realm.KeycloakAPI
38 with patch.object(obj, "get_realm_by_id", side_effect=get_realm_by_id) as mock_get_realm_by_id:
39 with patch.object(obj, "create_realm", side_effect=create_realm) as mock_create_realm:
40 with patch.object(obj, "update_realm", side_effect=update_realm) as mock_update_realm:
41 with patch.object(obj, "delete_realm", side_effect=delete_realm) as mock_delete_realm:
42 yield mock_get_realm_by_id, mock_create_realm, mock_update_realm, mock_delete_realm
43
44
45 def get_response(object_with_future_response, method, get_id_call_count):
46 if callable(object_with_future_response):
47 return object_with_future_response()
48 if isinstance(object_with_future_response, dict):
49 return get_response(object_with_future_response[method], method, get_id_call_count)
50 if isinstance(object_with_future_response, list):
51 call_number = next(get_id_call_count)
52 return get_response(object_with_future_response[call_number], method, get_id_call_count)
53 return object_with_future_response
54
55
56 def build_mocked_request(get_id_user_count, response_dict):
57 def _mocked_requests(*args, **kwargs):
58 url = args[0]
59 method = kwargs["method"]
60 future_response = response_dict.get(url, None)
61 return get_response(future_response, method, get_id_user_count)
62
63 return _mocked_requests
64
65
66 def create_wrapper(text_as_string):
67 """Allow to mock many times a call to one address.
68 Without this function, the StringIO is empty for the second call.
69 """
70
71 def _create_wrapper():
72 return StringIO(text_as_string)
73
74 return _create_wrapper
75
76
77 def mock_good_connection():
78 token_response = {
79 "http://keycloak.url/auth/realms/master/protocol/openid-connect/token": create_wrapper(
80 '{"access_token": "alongtoken"}'
81 ),
82 }
83 return patch(
84 "ansible_collections.community.general.plugins.module_utils._keycloak.open_url",
85 side_effect=build_mocked_request(count(), token_response),
86 autospec=True,
87 )
88
89
90 class TestKeycloakRealm(ModuleTestCase):
91 def setUp(self):
92 super().setUp()
93 self.module = keycloak_realm
94
95 def test_create_when_absent(self):
96 """Add a new realm"""
97
98 module_args = {
99 "auth_keycloak_url": "http://keycloak.url/auth",
100 "auth_password": "admin",
101 "auth_realm": "master",
102 "auth_username": "admin",
103 "auth_client_id": "admin-cli",
104 "validate_certs": True,
105 "id": "realm-name",
106 "realm": "realm-name",
107 "enabled": True,
108 }
109 return_value_absent = [None, {"id": "realm-name", "realm": "realm-name", "enabled": True}]
110 return_value_created = [{"code": 201, "id": "realm-name", "realm": "realm-name", "enabled": True}]
111 changed = True
112
113 # Run the module
114
115 with set_module_args(module_args):
116 with mock_good_connection():
117 with patch_keycloak_api(get_realm_by_id=return_value_absent, create_realm=return_value_created) as (
118 mock_get_realm_by_id,
119 mock_create_realm,
120 mock_update_realm,
121 mock_delete_realm,
122 ):
123 with self.assertRaises(AnsibleExitJson) as exec_info:
124 self.module.main()
125
126 self.assertEqual(len(mock_get_realm_by_id.mock_calls), 2)
127 self.assertEqual(len(mock_create_realm.mock_calls), 1)
128 self.assertEqual(len(mock_update_realm.mock_calls), 0)
129
130 # Verify that the module's changed status matches what is expected
131 self.assertIs(exec_info.exception.args[0]["changed"], changed)
132
133 def test_create_when_present_with_change(self):
134 """Update with change a realm"""
135
136 module_args = {
137 "auth_keycloak_url": "http://keycloak.url/auth",
138 "auth_password": "admin",
139 "auth_realm": "master",
140 "auth_username": "admin",
141 "auth_client_id": "admin-cli",
142 "validate_certs": True,
143 "id": "realm-name",
144 "realm": "realm-name",
145 "enabled": False,
146 }
147 return_value_absent = [
148 {"id": "realm-name", "realm": "realm-name", "enabled": True},
149 {"id": "realm-name", "realm": "realm-name", "enabled": False},
150 ]
151 return_value_updated = [{"code": 201, "id": "realm-name", "realm": "realm-name", "enabled": False}]
152 changed = True
153
154 # Run the module
155
156 with set_module_args(module_args):
157 with mock_good_connection():
158 with patch_keycloak_api(get_realm_by_id=return_value_absent, update_realm=return_value_updated) as (
159 mock_get_realm_by_id,
160 mock_create_realm,
161 mock_update_realm,
162 mock_delete_realm,
163 ):
164 with self.assertRaises(AnsibleExitJson) as exec_info:
165 self.module.main()
166
167 self.assertEqual(len(mock_get_realm_by_id.mock_calls), 2)
168 self.assertEqual(len(mock_create_realm.mock_calls), 0)
169 self.assertEqual(len(mock_update_realm.mock_calls), 1)
170
171 # Verify that the module's changed status matches what is expected
172 self.assertIs(exec_info.exception.args[0]["changed"], changed)
173
174 def test_create_when_present_no_change(self):
175 """Update without change a realm"""
176
177 module_args = {
178 "auth_keycloak_url": "http://keycloak.url/auth",
179 "auth_password": "admin",
180 "auth_realm": "master",
181 "auth_username": "admin",
182 "auth_client_id": "admin-cli",
183 "validate_certs": True,
184 "id": "realm-name",
185 "realm": "realm-name",
186 "enabled": True,
187 }
188 return_value_absent = [
189 {"id": "realm-name", "realm": "realm-name", "enabled": True},
190 {"id": "realm-name", "realm": "realm-name", "enabled": True},
191 ]
192 return_value_updated = [{"code": 201, "id": "realm-name", "realm": "realm-name", "enabled": True}]
193 changed = False
194
195 # Run the module
196
197 with set_module_args(module_args):
198 with mock_good_connection():
199 with patch_keycloak_api(get_realm_by_id=return_value_absent, update_realm=return_value_updated) as (
200 mock_get_realm_by_id,
201 mock_create_realm,
202 mock_update_realm,
203 mock_delete_realm,
204 ):
205 with self.assertRaises(AnsibleExitJson) as exec_info:
206 self.module.main()
207
208 self.assertEqual(len(mock_get_realm_by_id.mock_calls), 2)
209 self.assertEqual(len(mock_create_realm.mock_calls), 0)
210 self.assertEqual(len(mock_update_realm.mock_calls), 1)
211
212 # Verify that the module's changed status matches what is expected
213 self.assertIs(exec_info.exception.args[0]["changed"], changed)
214
215 def test_delete_when_absent(self):
216 """Remove an absent realm"""
217
218 module_args = {
219 "auth_keycloak_url": "http://keycloak.url/auth",
220 "auth_password": "admin",
221 "auth_realm": "master",
222 "auth_username": "admin",
223 "auth_client_id": "admin-cli",
224 "validate_certs": True,
225 "id": "realm-name",
226 "realm": "realm-name",
227 "enabled": True,
228 "state": "absent",
229 }
230 return_value_absent = [None]
231 return_value_deleted = [None]
232 changed = False
233
234 # Run the module
235
236 with set_module_args(module_args):
237 with mock_good_connection():
238 with patch_keycloak_api(get_realm_by_id=return_value_absent, delete_realm=return_value_deleted) as (
239 mock_get_realm_by_id,
240 mock_create_realm,
241 mock_update_realm,
242 mock_delete_realm,
243 ):
244 with self.assertRaises(AnsibleExitJson) as exec_info:
245 self.module.main()
246
247 self.assertEqual(len(mock_get_realm_by_id.mock_calls), 1)
248 self.assertEqual(len(mock_delete_realm.mock_calls), 0)
249
250 # Verify that the module's changed status matches what is expected
251 self.assertIs(exec_info.exception.args[0]["changed"], changed)
252
253 def test_delete_when_present(self):
254 """Remove a present realm"""
255
256 module_args = {
257 "auth_keycloak_url": "http://keycloak.url/auth",
258 "auth_password": "admin",
259 "auth_realm": "master",
260 "auth_username": "admin",
261 "auth_client_id": "admin-cli",
262 "validate_certs": True,
263 "id": "realm-name",
264 "realm": "realm-name",
265 "enabled": True,
266 "state": "absent",
267 }
268 return_value_absent = [{"id": "realm-name", "realm": "realm-name"}]
269 return_value_deleted = [None]
270 changed = True
271
272 # Run the module
273
274 with set_module_args(module_args):
275 with mock_good_connection():
276 with patch_keycloak_api(get_realm_by_id=return_value_absent, delete_realm=return_value_deleted) as (
277 mock_get_realm_by_id,
278 mock_create_realm,
279 mock_update_realm,
280 mock_delete_realm,
281 ):
282 with self.assertRaises(AnsibleExitJson) as exec_info:
283 self.module.main()
284
285 self.assertEqual(len(mock_get_realm_by_id.mock_calls), 1)
286 self.assertEqual(len(mock_delete_realm.mock_calls), 1)
287
288 # Verify that the module's changed status matches what is expected
289 self.assertIs(exec_info.exception.args[0]["changed"], changed)