Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/module_utils/test__pritunl_api.py

raw
1 # Copyright (c) 2021, Florian Dambrine <[email protected]>
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 import json
8 from unittest.mock import MagicMock
9
10 import pytest
11 from ansible.module_utils.common.dict_transformations import dict_merge
12
13 from ansible_collections.community.general.plugins.module_utils import _pritunl_api as api
14
15 # Pritunl Mocks
16
17 PRITUNL_ORGS = [
18 {
19 "auth_api": False,
20 "name": "Foo",
21 "auth_token": None,
22 "user_count": 0,
23 "auth_secret": None,
24 "id": "csftwlu6uhralzi2dpmhekz3",
25 },
26 {
27 "auth_api": False,
28 "name": "GumGum",
29 "auth_token": None,
30 "user_count": 3,
31 "auth_secret": None,
32 "id": "58070daee63f3b2e6e472c36",
33 },
34 {
35 "auth_api": False,
36 "name": "Bar",
37 "auth_token": None,
38 "user_count": 0,
39 "auth_secret": None,
40 "id": "v1sncsxxybnsylc8gpqg85pg",
41 },
42 ]
43
44 NEW_PRITUNL_ORG = {
45 "auth_api": False,
46 "name": "NewOrg",
47 "auth_token": None,
48 "user_count": 0,
49 "auth_secret": None,
50 "id": "604a140ae63f3b36bc34c7bd",
51 }
52
53 PRITUNL_USERS = [
54 {
55 "auth_type": "google",
56 "dns_servers": None,
57 "pin": True,
58 "dns_suffix": None,
59 "servers": [
60 {
61 "status": False,
62 "platform": None,
63 "server_id": "580711322bb66c1d59b9568f",
64 "virt_address6": "fd00:c0a8: 9700: 0: 192: 168: 101: 27",
65 "virt_address": "192.168.101.27",
66 "name": "vpn-A",
67 "real_address": None,
68 "connected_since": None,
69 "id": "580711322bb66c1d59b9568f",
70 "device_name": None,
71 },
72 {
73 "status": False,
74 "platform": None,
75 "server_id": "5dad2cc6e63f3b3f4a6dfea5",
76 "virt_address6": "fd00:c0a8:f200: 0: 192: 168: 201: 37",
77 "virt_address": "192.168.201.37",
78 "name": "vpn-B",
79 "real_address": None,
80 "connected_since": None,
81 "id": "5dad2cc6e63f3b3f4a6dfea5",
82 "device_name": None,
83 },
84 ],
85 "disabled": False,
86 "network_links": [],
87 "port_forwarding": [],
88 "id": "58070dafe63f3b2e6e472c3b",
89 "organization_name": "GumGum",
90 "type": "server",
91 "email": "[email protected]",
92 "status": True,
93 "dns_mapping": None,
94 "otp_secret": "123456789ABCDEFG",
95 "client_to_client": False,
96 "sso": "google",
97 "bypass_secondary": False,
98 "groups": ["admin", "multiregion"],
99 "audit": False,
100 "name": "bot",
101 "gravatar": True,
102 "otp_auth": True,
103 "organization": "58070daee63f3b2e6e472c36",
104 },
105 {
106 "auth_type": "google",
107 "dns_servers": None,
108 "pin": True,
109 "dns_suffix": None,
110 "servers": [
111 {
112 "status": False,
113 "platform": None,
114 "server_id": "580711322bb66c1d59b9568f",
115 "virt_address6": "fd00:c0a8: 9700: 0: 192: 168: 101: 27",
116 "virt_address": "192.168.101.27",
117 "name": "vpn-A",
118 "real_address": None,
119 "connected_since": None,
120 "id": "580711322bb66c1d59b9568f",
121 "device_name": None,
122 },
123 {
124 "status": False,
125 "platform": None,
126 "server_id": "5dad2cc6e63f3b3f4a6dfea5",
127 "virt_address6": "fd00:c0a8:f200: 0: 192: 168: 201: 37",
128 "virt_address": "192.168.201.37",
129 "name": "vpn-B",
130 "real_address": None,
131 "connected_since": None,
132 "id": "5dad2cc6e63f3b3f4a6dfea5",
133 "device_name": None,
134 },
135 ],
136 "disabled": False,
137 "network_links": [],
138 "port_forwarding": [],
139 "id": "58070dafe63f3b2e6e472c3b",
140 "organization_name": "GumGum",
141 "type": "client",
142 "email": "[email protected]",
143 "status": True,
144 "dns_mapping": None,
145 "otp_secret": "123456789ABCDEFG",
146 "client_to_client": False,
147 "sso": "google",
148 "bypass_secondary": False,
149 "groups": ["web", "database"],
150 "audit": False,
151 "name": "florian",
152 "gravatar": True,
153 "otp_auth": True,
154 "organization": "58070daee63f3b2e6e472c36",
155 },
156 {
157 "auth_type": "google",
158 "dns_servers": None,
159 "pin": True,
160 "dns_suffix": None,
161 "servers": [
162 {
163 "status": False,
164 "platform": None,
165 "server_id": "580711322bb66c1d59b9568f",
166 "virt_address6": "fd00:c0a8: 9700: 0: 192: 168: 101: 27",
167 "virt_address": "192.168.101.27",
168 "name": "vpn-A",
169 "real_address": None,
170 "connected_since": None,
171 "id": "580711322bb66c1d59b9568f",
172 "device_name": None,
173 },
174 {
175 "status": False,
176 "platform": None,
177 "server_id": "5dad2cc6e63f3b3f4a6dfea5",
178 "virt_address6": "fd00:c0a8:f200: 0: 192: 168: 201: 37",
179 "virt_address": "192.168.201.37",
180 "name": "vpn-B",
181 "real_address": None,
182 "connected_since": None,
183 "id": "5dad2cc6e63f3b3f4a6dfea5",
184 "device_name": None,
185 },
186 ],
187 "disabled": False,
188 "network_links": [],
189 "port_forwarding": [],
190 "id": "58070dafe63f3b2e6e472c3b",
191 "organization_name": "GumGum",
192 "type": "server",
193 "email": "[email protected]",
194 "status": True,
195 "dns_mapping": None,
196 "otp_secret": "123456789ABCDEFG",
197 "client_to_client": False,
198 "sso": "google",
199 "bypass_secondary": False,
200 "groups": ["web", "database"],
201 "audit": False,
202 "name": "ops",
203 "gravatar": True,
204 "otp_auth": True,
205 "organization": "58070daee63f3b2e6e472c36",
206 },
207 ]
208
209 NEW_PRITUNL_USER = {
210 "auth_type": "local",
211 "disabled": False,
212 "dns_servers": None,
213 "otp_secret": "6M4UWP2BCJBSYZAT",
214 "name": "alice",
215 "pin": False,
216 "dns_suffix": None,
217 "client_to_client": False,
218 "email": "[email protected]",
219 "organization_name": "GumGum",
220 "bypass_secondary": False,
221 "groups": ["a", "b"],
222 "organization": "58070daee63f3b2e6e472c36",
223 "port_forwarding": [],
224 "type": "client",
225 "id": "590add71e63f3b72d8bb951a",
226 }
227
228 NEW_PRITUNL_USER_UPDATED = dict_merge(
229 NEW_PRITUNL_USER,
230 {
231 "disabled": True,
232 "name": "bob",
233 "email": "[email protected]",
234 "groups": ["c", "d"],
235 },
236 )
237
238
239 class PritunlEmptyOrganizationMock(MagicMock):
240 """Pritunl API Mock for organization GET API calls."""
241
242 def getcode(self):
243 return 200
244
245 def read(self):
246 return json.dumps([])
247
248
249 class PritunlListOrganizationMock(MagicMock):
250 """Pritunl API Mock for organization GET API calls."""
251
252 def getcode(self):
253 return 200
254
255 def read(self):
256 return json.dumps(PRITUNL_ORGS)
257
258
259 class PritunlListUserMock(MagicMock):
260 """Pritunl API Mock for user GET API calls."""
261
262 def getcode(self):
263 return 200
264
265 def read(self):
266 return json.dumps(PRITUNL_USERS)
267
268
269 class PritunlErrorMock(MagicMock):
270 """Pritunl API Mock for API call failures."""
271
272 def getcode(self):
273 return 500
274
275 def read(self):
276 return "{}"
277
278
279 class PritunlPostOrganizationMock(MagicMock):
280 def getcode(self):
281 return 200
282
283 def read(self):
284 return json.dumps(NEW_PRITUNL_ORG)
285
286
287 class PritunlListOrganizationAfterPostMock(MagicMock):
288 def getcode(self):
289 return 200
290
291 def read(self):
292 return json.dumps(PRITUNL_ORGS + [NEW_PRITUNL_ORG])
293
294
295 class PritunlPostUserMock(MagicMock):
296 """Pritunl API Mock for POST API calls."""
297
298 def getcode(self):
299 return 200
300
301 def read(self):
302 return json.dumps([NEW_PRITUNL_USER])
303
304
305 class PritunlPutUserMock(MagicMock):
306 """Pritunl API Mock for PUT API calls."""
307
308 def getcode(self):
309 return 200
310
311 def read(self):
312 return json.dumps(NEW_PRITUNL_USER_UPDATED)
313
314
315 class PritunlDeleteOrganizationMock(MagicMock):
316 """Pritunl API Mock for DELETE API calls."""
317
318 def getcode(self):
319 return 200
320
321 def read(self):
322 return "{}"
323
324
325 class PritunlDeleteUserMock(MagicMock):
326 """Pritunl API Mock for DELETE API calls."""
327
328 def getcode(self):
329 return 200
330
331 def read(self):
332 return "{}"
333
334
335 # Ansible Module Mock and Pytest mock fixtures
336
337
338 class ModuleFailException(Exception):
339 def __init__(self, msg, **kwargs):
340 super().__init__(msg)
341 self.fail_msg = msg
342 self.fail_kwargs = kwargs
343
344
345 @pytest.fixture
346 def pritunl_settings():
347 return {
348 "api_token": "token",
349 "api_secret": "secret",
350 "base_url": "https://pritunl.domain.com",
351 "validate_certs": True,
352 }
353
354
355 @pytest.fixture
356 def pritunl_organization_data():
357 return {
358 "name": NEW_PRITUNL_ORG["name"],
359 }
360
361
362 @pytest.fixture
363 def pritunl_user_data():
364 return {
365 "name": NEW_PRITUNL_USER["name"],
366 "email": NEW_PRITUNL_USER["email"],
367 "groups": NEW_PRITUNL_USER["groups"],
368 "disabled": NEW_PRITUNL_USER["disabled"],
369 "type": NEW_PRITUNL_USER["type"],
370 }
371
372
373 @pytest.fixture
374 def get_pritunl_organization_mock():
375 return PritunlListOrganizationMock()
376
377
378 @pytest.fixture
379 def get_pritunl_user_mock():
380 return PritunlListUserMock()
381
382
383 @pytest.fixture
384 def get_pritunl_error_mock():
385 return PritunlErrorMock()
386
387
388 @pytest.fixture
389 def post_pritunl_organization_mock():
390 return PritunlPostOrganizationMock()
391
392
393 @pytest.fixture
394 def post_pritunl_user_mock():
395 return PritunlPostUserMock()
396
397
398 @pytest.fixture
399 def put_pritunl_user_mock():
400 return PritunlPutUserMock()
401
402
403 @pytest.fixture
404 def delete_pritunl_organization_mock():
405 return PritunlDeleteOrganizationMock()
406
407
408 @pytest.fixture
409 def delete_pritunl_user_mock():
410 return PritunlDeleteUserMock()
411
412
413 class TestPritunlApi:
414 """
415 Test class to validate CRUD operations on Pritunl.
416 """
417
418 # Test for GET / list operation on Pritunl API
419 @pytest.mark.parametrize(
420 "org_id,org_user_count",
421 [
422 ("58070daee63f3b2e6e472c36", 3),
423 ("v1sncsxxybnsylc8gpqg85pg", 0),
424 ],
425 )
426 def test_list_all_pritunl_organization(
427 self,
428 pritunl_settings,
429 get_pritunl_organization_mock,
430 org_id,
431 org_user_count,
432 ):
433 api._get_pritunl_organizations = get_pritunl_organization_mock()
434
435 response = api.list_pritunl_organizations(**pritunl_settings)
436
437 assert len(response) == 3
438
439 for org in response:
440 if org["id"] == org_id:
441 assert org["user_count"] == org_user_count
442
443 @pytest.mark.parametrize(
444 "org_filters,org_expected",
445 [
446 ({"id": "58070daee63f3b2e6e472c36"}, "GumGum"),
447 ({"name": "GumGum"}, "GumGum"),
448 ],
449 )
450 def test_list_filtered_pritunl_organization(
451 self,
452 pritunl_settings,
453 get_pritunl_organization_mock,
454 org_filters,
455 org_expected,
456 ):
457 api._get_pritunl_organizations = get_pritunl_organization_mock()
458
459 response = api.list_pritunl_organizations(**dict_merge(pritunl_settings, {"filters": org_filters}))
460
461 assert len(response) == 1
462 assert response[0]["name"] == org_expected
463
464 @pytest.mark.parametrize(
465 "org_id,org_user_count",
466 [("58070daee63f3b2e6e472c36", 3)],
467 )
468 def test_list_all_pritunl_user(self, pritunl_settings, get_pritunl_user_mock, org_id, org_user_count):
469 api._get_pritunl_users = get_pritunl_user_mock()
470
471 response = api.list_pritunl_users(**dict_merge(pritunl_settings, {"organization_id": org_id}))
472
473 assert len(response) == org_user_count
474
475 @pytest.mark.parametrize(
476 "org_id,user_filters,user_expected",
477 [
478 ("58070daee63f3b2e6e472c36", {"email": "[email protected]"}, "bot"),
479 ("58070daee63f3b2e6e472c36", {"name": "florian"}, "florian"),
480 ],
481 )
482 def test_list_filtered_pritunl_user(
483 self,
484 pritunl_settings,
485 get_pritunl_user_mock,
486 org_id,
487 user_filters,
488 user_expected,
489 ):
490 api._get_pritunl_users = get_pritunl_user_mock()
491
492 response = api.list_pritunl_users(
493 **dict_merge(pritunl_settings, {"organization_id": org_id, "filters": user_filters})
494 )
495
496 assert len(response) > 0
497
498 for user in response:
499 assert user["organization"] == org_id
500 assert user["name"] == user_expected
501
502 # Test for POST operation on Pritunl API
503 def test_add_pritunl_organization(
504 self,
505 pritunl_settings,
506 pritunl_organization_data,
507 post_pritunl_organization_mock,
508 ):
509 api._post_pritunl_organization = post_pritunl_organization_mock()
510
511 create_response = api.post_pritunl_organization(
512 **dict_merge(
513 pritunl_settings,
514 {"organization_name": pritunl_organization_data["name"]},
515 )
516 )
517
518 # Ensure provided settings match with the ones returned by Pritunl
519 for k, v in pritunl_organization_data.items():
520 assert create_response[k] == v
521
522 @pytest.mark.parametrize("org_id", [("58070daee63f3b2e6e472c36")])
523 def test_add_and_update_pritunl_user(
524 self,
525 pritunl_settings,
526 pritunl_user_data,
527 post_pritunl_user_mock,
528 put_pritunl_user_mock,
529 org_id,
530 ):
531 api._post_pritunl_user = post_pritunl_user_mock()
532 api._put_pritunl_user = put_pritunl_user_mock()
533
534 create_response = api.post_pritunl_user(
535 **dict_merge(
536 pritunl_settings,
537 {
538 "organization_id": org_id,
539 "user_data": pritunl_user_data,
540 },
541 )
542 )
543
544 # Ensure provided settings match with the ones returned by Pritunl
545 for k, v in pritunl_user_data.items():
546 assert create_response[k] == v
547
548 # Update the newly created user to ensure only certain settings are changed
549
550 user_updates = {
551 "name": "bob",
552 "email": "[email protected]",
553 "disabled": True,
554 }
555
556 update_response = api.post_pritunl_user(
557 **dict_merge(
558 pritunl_settings,
559 {
560 "organization_id": org_id,
561 "user_id": create_response["id"],
562 "user_data": dict_merge(pritunl_user_data, user_updates),
563 },
564 )
565 )
566
567 # Ensure only certain settings changed and the rest remained untouched.
568 # TODO: there is something wrong with this check!
569 for k, v in update_response.items():
570 if k in update_response:
571 assert update_response[k] == v
572 else:
573 assert update_response[k] == create_response[k]
574
575 # Test for DELETE operation on Pritunl API
576
577 @pytest.mark.parametrize("org_id", [("58070daee63f3b2e6e472c36")])
578 def test_delete_pritunl_organization(self, pritunl_settings, org_id, delete_pritunl_organization_mock):
579 api._delete_pritunl_organization = delete_pritunl_organization_mock()
580
581 response = api.delete_pritunl_organization(
582 **dict_merge(
583 pritunl_settings,
584 {
585 "organization_id": org_id,
586 },
587 )
588 )
589
590 assert response == {}
591
592 @pytest.mark.parametrize("org_id,user_id", [("58070daee63f3b2e6e472c36", "590add71e63f3b72d8bb951a")])
593 def test_delete_pritunl_user(self, pritunl_settings, org_id, user_id, delete_pritunl_user_mock):
594 api._delete_pritunl_user = delete_pritunl_user_mock()
595
596 response = api.delete_pritunl_user(
597 **dict_merge(
598 pritunl_settings,
599 {
600 "organization_id": org_id,
601 "user_id": user_id,
602 },
603 )
604 )
605
606 assert response == {}
607
608 # Test API call errors
609 def test_pritunl_error(self, pritunl_settings, get_pritunl_error_mock):
610 api.pritunl_auth_request = get_pritunl_error_mock()
611
612 with pytest.raises(api.PritunlException):
613 api.list_pritunl_organizations(**pritunl_settings)