Debian Codegraph @

ansible_collections/community/dns/tests/unit/plugins/module_utils/test__http.py

raw
1 # Copyright (c) 2025, Felix Fontein <[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 pytest
8 from ansible.module_utils.urls import ConnectionError, NoSSLError # noqa: A004
9 from ansible_collections.community.internal_test_tools.tests.unit.utils.open_url_framework import (
10 OpenUrlCall,
11 OpenUrlProxy,
12 )
13
14 from ansible_collections.community.dns.plugins.module_utils._http import (
15 NetworkError,
16 OpenURLHelper,
17 )
18
19
20 def test_open_url_helper_1(mocker):
21 open_url = OpenUrlProxy(
22 [
23 OpenUrlCall("GET", 400)
24 .expect_url("https://dns.hetzner.com/api/v1/zones")
25 .result_error(body="foo"),
26 ]
27 )
28 mocker.patch(
29 "ansible_collections.community.dns.plugins.module_utils._http.open_url",
30 open_url,
31 )
32 helper = OpenURLHelper()
33 content, info = helper.fetch_url("https://dns.hetzner.com/api/v1/zones")
34 open_url.assert_is_done()
35 assert content == "foo"
36 assert info == {
37 "status": 400,
38 }
39
40
41 def test_open_url_helper_2(mocker):
42 open_url = OpenUrlProxy(
43 [
44 OpenUrlCall("GET", 400)
45 .expect_url("https://dns.hetzner.com/api/v1/zones")
46 .result_error(),
47 ]
48 )
49 mocker.patch(
50 "ansible_collections.community.dns.plugins.module_utils._http.open_url",
51 open_url,
52 )
53 helper = OpenURLHelper()
54 content, info = helper.fetch_url("https://dns.hetzner.com/api/v1/zones")
55 open_url.assert_is_done()
56 assert content == ""
57 assert info == {
58 "status": 400,
59 }
60
61
62 def test_open_url_helper_3(mocker):
63 open_url = OpenUrlProxy(
64 [
65 OpenUrlCall("GET", 400)
66 .expect_url("https://dns.hetzner.com/api/v1/zones")
67 .exception(lambda: NoSSLError("foo")),
68 ]
69 )
70 mocker.patch(
71 "ansible_collections.community.dns.plugins.module_utils._http.open_url",
72 open_url,
73 )
74 helper = OpenURLHelper()
75 with pytest.raises(NetworkError) as exc:
76 helper.fetch_url("https://dns.hetzner.com/api/v1/zones")
77 open_url.assert_is_done()
78 print(exc.value.args[0])
79 assert exc.value.args[0] == "Cannot connect via SSL: foo"
80
81
82 def test_open_url_helper_4(mocker):
83 open_url = OpenUrlProxy(
84 [
85 OpenUrlCall("GET", 400)
86 .expect_url("https://dns.hetzner.com/api/v1/zones")
87 .exception(lambda: ConnectionError("foo")),
88 ]
89 )
90 mocker.patch(
91 "ansible_collections.community.dns.plugins.module_utils._http.open_url",
92 open_url,
93 )
94 helper = OpenURLHelper()
95 with pytest.raises(NetworkError) as exc:
96 helper.fetch_url("https://dns.hetzner.com/api/v1/zones")
97 open_url.assert_is_done()
98 print(exc.value.args[0])
99 assert exc.value.args[0] == "Connection error: foo"