Debian Codegraph @

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

raw
1 # Copyright (c) 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 import json
8 from unittest.mock import MagicMock, patch
9
10 import pytest
11 from ansible_collections.community.internal_test_tools.tests.unit.plugins.modules.utils import (
12 AnsibleExitJson,
13 exit_json,
14 fail_json,
15 set_module_args,
16 )
17
18 from ansible_collections.community.general.plugins.modules import github_secrets_info
19
20 GITHUB_SECRETS_RESPONSE = {
21 "total_count": 2,
22 "secrets": [
23 {
24 "name": "SECRET1",
25 "created_at": "2026-01-01T00:00:00Z",
26 "updated_at": "2026-01-02T00:00:00Z",
27 },
28 {
29 "name": "SECRET2",
30 "created_at": "2026-01-03T00:00:00Z",
31 "updated_at": "2026-01-04T00:00:00Z",
32 },
33 ],
34 }
35
36
37 def make_fetch_url_response(body, status=200):
38 response = MagicMock()
39 response.read.return_value = json.dumps(body).encode("utf-8")
40 info = {"status": status, "msg": f"OK ({len(json.dumps(body))} bytes)"}
41 return (response, info)
42
43
44 @pytest.fixture(autouse=True)
45 def patch_module():
46 with patch.multiple(
47 "ansible.module_utils.basic.AnsibleModule",
48 exit_json=exit_json,
49 fail_json=fail_json,
50 ):
51 yield
52
53
54 @pytest.fixture
55 def fetch_url_mock():
56 with patch.object(github_secrets_info, "fetch_url") as mock:
57 yield mock
58
59
60 def test_list_repo_secrets(fetch_url_mock):
61 fetch_url_mock.side_effect = [
62 make_fetch_url_response(GITHUB_SECRETS_RESPONSE),
63 make_fetch_url_response({}, status=200),
64 ]
65
66 with set_module_args(
67 {
68 "organization": "myorg",
69 "repository": "myrepo",
70 "token": "ghp_test_token",
71 }
72 ):
73 with pytest.raises(AnsibleExitJson) as exc:
74 github_secrets_info.main()
75
76 result = exc.value.args[0]
77 assert result["changed"] is False
78 assert result["secrets"] == GITHUB_SECRETS_RESPONSE["secrets"]
79
80
81 def test_fail_list_repo_secrets(fetch_url_mock):
82 fetch_url_mock.side_effect = [
83 make_fetch_url_response({}, status=404),
84 ]
85
86 with set_module_args(
87 {
88 "organization": "myorg",
89 "repository": "myrepo",
90 "token": "ghp_test_token",
91 }
92 ):
93 with pytest.raises(AnsibleExitJson) as exc:
94 github_secrets_info.main()
95
96 result = exc.value.args[0]
97 assert result["changed"] is False
98 assert result["secrets"] == []