| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# (c) 2018 Matt Martz <[email protected]> |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import io |
| 8 |
import sys |
| 9 |
import http.client |
| 10 |
import urllib.error |
| 11 |
from http.cookiejar import Cookie |
| 12 |
|
| 13 |
from ansible.module_utils.urls import fetch_url, is_fetch_success, ConnectionError |
| 14 |
|
| 15 |
import pytest |
| 16 |
from unittest.mock import MagicMock |
| 17 |
|
| 18 |
BASE_URL = 'https://ansible.com/' |
| 19 |
|
| 20 |
|
| 21 |
class AnsibleModuleExit(Exception): |
| 22 |
def __init__(self, *args, **kwargs): |
| 23 |
self.args = args |
| 24 |
self.kwargs = kwargs |
| 25 |
|
| 26 |
|
| 27 |
class ExitJson(AnsibleModuleExit): |
| 28 |
pass |
| 29 |
|
| 30 |
|
| 31 |
class FailJson(AnsibleModuleExit): |
| 32 |
pass |
| 33 |
|
| 34 |
|
| 35 |
@pytest.fixture |
| 36 |
def open_url_mock(mocker): |
| 37 |
return mocker.patch('ansible.module_utils.urls.open_url') |
| 38 |
|
| 39 |
|
| 40 |
@pytest.fixture |
| 41 |
def fake_ansible_module(): |
| 42 |
return FakeAnsibleModule() |
| 43 |
|
| 44 |
|
| 45 |
class FakeAnsibleModule: |
| 46 |
def __init__(self): |
| 47 |
self.params = {} |
| 48 |
self.tmpdir = None |
| 49 |
|
| 50 |
def exit_json(self, *args, **kwargs): |
| 51 |
raise ExitJson(*args, **kwargs) |
| 52 |
|
| 53 |
def fail_json(self, *args, **kwargs): |
| 54 |
raise FailJson(*args, **kwargs) |
| 55 |
|
| 56 |
|
| 57 |
def test_fetch_url(open_url_mock, fake_ansible_module): |
| 58 |
r, info = fetch_url(fake_ansible_module, BASE_URL) |
| 59 |
|
| 60 |
dummy, kwargs = open_url_mock.call_args |
| 61 |
|
| 62 |
open_url_mock.assert_called_once_with(BASE_URL, client_cert=None, client_key=None, cookies=kwargs['cookies'], data=None, |
| 63 |
follow_redirects='urllib2', force=False, force_basic_auth='', headers=None, |
| 64 |
http_agent='ansible-httpget', last_mod_time=None, method=None, timeout=10, url_password='', url_username='', |
| 65 |
use_proxy=True, validate_certs=True, use_gssapi=False, unix_socket=None, ca_path=None, unredirected_headers=None, |
| 66 |
decompress=True, ciphers=None, use_netrc=True) |
| 67 |
|
| 68 |
|
| 69 |
def test_fetch_url_params(open_url_mock, fake_ansible_module): |
| 70 |
fake_ansible_module.params = { |
| 71 |
'validate_certs': False, |
| 72 |
'url_username': 'user', |
| 73 |
'url_password': 'passwd', |
| 74 |
'http_agent': 'ansible-test', |
| 75 |
'force_basic_auth': True, |
| 76 |
'follow_redirects': 'all', |
| 77 |
'client_cert': 'client.pem', |
| 78 |
'client_key': 'client.key', |
| 79 |
} |
| 80 |
|
| 81 |
r, info = fetch_url(fake_ansible_module, BASE_URL) |
| 82 |
|
| 83 |
dummy, kwargs = open_url_mock.call_args |
| 84 |
|
| 85 |
open_url_mock.assert_called_once_with(BASE_URL, client_cert='client.pem', client_key='client.key', cookies=kwargs['cookies'], data=None, |
| 86 |
follow_redirects='all', force=False, force_basic_auth=True, headers=None, |
| 87 |
http_agent='ansible-test', last_mod_time=None, method=None, timeout=10, url_password='passwd', url_username='user', |
| 88 |
use_proxy=True, validate_certs=False, use_gssapi=False, unix_socket=None, ca_path=None, unredirected_headers=None, |
| 89 |
decompress=True, ciphers=None, use_netrc=True) |
| 90 |
|
| 91 |
|
| 92 |
def test_fetch_url_cookies(mocker, fake_ansible_module): |
| 93 |
def make_cookies(*args, **kwargs): |
| 94 |
cookies = kwargs['cookies'] |
| 95 |
r = MagicMock() |
| 96 |
r.headers = http.client.HTTPMessage() |
| 97 |
add_header = r.headers.add_header |
| 98 |
r.info.return_value = r.headers |
| 99 |
for name, value in (('Foo', 'bar'), ('Baz', 'qux')): |
| 100 |
cookie = Cookie( |
| 101 |
version=0, |
| 102 |
name=name, |
| 103 |
value=value, |
| 104 |
port=None, |
| 105 |
port_specified=False, |
| 106 |
domain="ansible.com", |
| 107 |
domain_specified=True, |
| 108 |
domain_initial_dot=False, |
| 109 |
path="/", |
| 110 |
path_specified=True, |
| 111 |
secure=False, |
| 112 |
expires=None, |
| 113 |
discard=False, |
| 114 |
comment=None, |
| 115 |
comment_url=None, |
| 116 |
rest=None |
| 117 |
) |
| 118 |
cookies.set_cookie(cookie) |
| 119 |
add_header('Set-Cookie', '%s=%s' % (name, value)) |
| 120 |
|
| 121 |
return r |
| 122 |
|
| 123 |
mocker = mocker.patch('ansible.module_utils.urls.open_url', new=make_cookies) |
| 124 |
|
| 125 |
r, info = fetch_url(fake_ansible_module, BASE_URL) |
| 126 |
|
| 127 |
assert info['cookies'] == {'Baz': 'qux', 'Foo': 'bar'} |
| 128 |
|
| 129 |
if sys.version_info < (3, 11): |
| 130 |
# Python sorts cookies in order of most specific (ie. longest) path first |
| 131 |
# items with the same path are reversed from response order |
| 132 |
assert info['cookies_string'] == 'Baz=qux; Foo=bar' |
| 133 |
else: |
| 134 |
# Python 3.11 and later preserve the Set-Cookie order. |
| 135 |
# See: https://github.com/python/cpython/pull/22745/ |
| 136 |
assert info['cookies_string'] == 'Foo=bar; Baz=qux' |
| 137 |
|
| 138 |
# The key here has a `-` as opposed to what we see in the `uri` module that converts to `_` |
| 139 |
# Note: this is response order, which differs from cookies_string |
| 140 |
assert info['set-cookie'] == 'Foo=bar, Baz=qux' |
| 141 |
|
| 142 |
|
| 143 |
def test_fetch_url_connectionerror(open_url_mock, fake_ansible_module): |
| 144 |
open_url_mock.side_effect = ConnectionError('TESTS') |
| 145 |
with pytest.raises(FailJson) as excinfo: |
| 146 |
fetch_url(fake_ansible_module, BASE_URL) |
| 147 |
|
| 148 |
assert excinfo.value.kwargs['msg'] == 'TESTS' |
| 149 |
assert BASE_URL == excinfo.value.kwargs['url'] |
| 150 |
assert excinfo.value.kwargs['status'] == -1 |
| 151 |
|
| 152 |
open_url_mock.side_effect = ValueError('TESTS') |
| 153 |
with pytest.raises(FailJson) as excinfo: |
| 154 |
fetch_url(fake_ansible_module, BASE_URL) |
| 155 |
|
| 156 |
assert excinfo.value.kwargs['msg'] == 'TESTS' |
| 157 |
assert BASE_URL == excinfo.value.kwargs['url'] |
| 158 |
assert excinfo.value.kwargs['status'] == -1 |
| 159 |
|
| 160 |
|
| 161 |
def test_fetch_url_httperror(open_url_mock, fake_ansible_module): |
| 162 |
open_url_mock.side_effect = urllib.error.HTTPError( |
| 163 |
BASE_URL, |
| 164 |
500, |
| 165 |
'Internal Server Error', |
| 166 |
{'Content-Type': 'application/json'}, |
| 167 |
io.StringIO('TESTS') |
| 168 |
) |
| 169 |
|
| 170 |
r, info = fetch_url(fake_ansible_module, BASE_URL) |
| 171 |
|
| 172 |
assert info == {'msg': 'HTTP Error 500: Internal Server Error', 'body': 'TESTS', |
| 173 |
'status': 500, 'url': BASE_URL, 'content-type': 'application/json'} |
| 174 |
|
| 175 |
|
| 176 |
def test_fetch_url_urlerror(open_url_mock, fake_ansible_module): |
| 177 |
open_url_mock.side_effect = urllib.error.URLError('TESTS') |
| 178 |
r, info = fetch_url(fake_ansible_module, BASE_URL) |
| 179 |
assert info == {'msg': 'Request failed: <urlopen error TESTS>', 'status': -1, 'url': BASE_URL} |
| 180 |
|
| 181 |
|
| 182 |
def test_fetch_url_socketerror(open_url_mock, fake_ansible_module): |
| 183 |
open_url_mock.side_effect = OSError('TESTS') |
| 184 |
r, info = fetch_url(fake_ansible_module, BASE_URL) |
| 185 |
assert info == {'msg': 'Connection failure: TESTS', 'status': -1, 'url': BASE_URL} |
| 186 |
|
| 187 |
|
| 188 |
def test_fetch_url_exception(open_url_mock, fake_ansible_module): |
| 189 |
open_url_mock.side_effect = Exception('TESTS') |
| 190 |
r, info = fetch_url(fake_ansible_module, BASE_URL) |
| 191 |
exception = info.pop('exception') |
| 192 |
assert info == {'msg': 'An unknown error occurred: TESTS', 'status': -1, 'url': BASE_URL} |
| 193 |
assert "Exception: TESTS" in exception |
| 194 |
|
| 195 |
|
| 196 |
def test_fetch_url_badstatusline(open_url_mock, fake_ansible_module): |
| 197 |
open_url_mock.side_effect = http.client.BadStatusLine('TESTS') |
| 198 |
r, info = fetch_url(fake_ansible_module, BASE_URL) |
| 199 |
assert info == {'msg': 'Connection failure: connection was closed before a valid response was received: TESTS', 'status': -1, 'url': BASE_URL} |
| 200 |
|
| 201 |
|
| 202 |
# is_fetch_success is highly coupled to fetch_url, unit test here. |
| 203 |
@pytest.mark.parametrize( |
| 204 |
'url, status, additional, expected', |
| 205 |
[ |
| 206 |
pytest.param('ftp://some/dir/file.txt', None, None, True, id='ftp_success'), |
| 207 |
pytest.param('ftps://another/dir/f.txt', -1, None, False, id='ftps_failure'), |
| 208 |
pytest.param('ftp://foo/dir/f.md', None, (-1,), True, id='ftp_failure'), |
| 209 |
pytest.param('ftp://foo/dir/f.md', -1, (-1,), True, id='ftp_failure_additional'), |
| 210 |
pytest.param('https://foo.com/file', 200, None, True, id='https_success'), |
| 211 |
pytest.param('https://foo.com/file', 400, None, False, id='https_failure'), |
| 212 |
pytest.param('http://foo.com/file', 200, None, True, id='http_success'), |
| 213 |
pytest.param('http://foo.com/file', 400, None, False, id='http_failure'), |
| 214 |
pytest.param('http://foo.com/file', 220, (220,), True, id='http_success_additional'), |
| 215 |
pytest.param('http://foo.com/file', 200, (220,), True, id='http_success_additional_2'), |
| 216 |
pytest.param('http://foo.com/file', 400, (220,), False, id='http_failure_additional'), |
| 217 |
pytest.param("Some nonsense fetch didn't catch", -1, None, False, id='nonsense_failure'), |
| 218 |
] |
| 219 |
) |
| 220 |
def test_is_fetch_success(url, status, additional, expected): |
| 221 |
assert expected == is_fetch_success(dict(url=url, status=status), additional_codes=additional) |