1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
|
#
# Copyright (C) 2019-2025 Mathieu Parent <math.parent@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
from re import escape as re_escape
from re import search as re_search
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, call, patch
from requests import Response, Session
from requests.utils import set_environ
from gitlabracadabra.packages.destination import Destination, Stream
from gitlabracadabra.packages.helm import Helm
from gitlabracadabra.packages.package_file import PackageFile
from gitlabracadabra.tests.case import TestCase
if TYPE_CHECKING:
from requests.auth import AuthBase
class TestDestination(TestCase):
"""Test Destination class."""
def test_import_source_not_found(self):
"""Test import_source method, with unexisting source."""
with patch("gitlabracadabra.packages.destination.logger", autospec=True) as logger:
destination = Destination(log_prefix="[foobar] ")
destination.session.request = MagicMock(side_effect=self._mocked_request)
source = MagicMock()
source.session.request = MagicMock(side_effect=self._mocked_request)
source.package_files.return_value = [
PackageFile("https://source.example.org/not_exists.tgz", "generic", "foobar")
]
with patch.object(Session, "request") as request_mock:
destination.import_source(source, dry_run=False)
assert request_mock.mock_calls == []
assert source.session.request.mock_calls == [call("HEAD", "https://source.example.org/not_exists.tgz")]
assert logger.mock_calls == [
call.warning(
'%sNOT uploading %s package file "%s" from "%s" version %s (%s): source not found',
"[foobar] ",
"generic",
"not_exists.tgz",
"foobar",
"0",
"https://source.example.org/not_exists.tgz",
)
]
def test_import_destination_exists(self):
"""Test import_source method, with existing destination."""
with patch("gitlabracadabra.packages.destination.logger", autospec=True) as logger:
destination = Destination(log_prefix="[foobar] ")
destination.get_url = MagicMock()
destination.get_url.return_value = "https://destination.example.org/foobar.tgz"
destination.session.request = MagicMock(side_effect=self._mocked_request)
source = MagicMock()
source.session.request = MagicMock(side_effect=self._mocked_request)
source.package_files.return_value = [
PackageFile("https://source.example.org/foobar.tgz", "generic", "foobar")
]
with patch.object(Session, "request") as request_mock:
request_mock.side_effect = self._mocked_request
destination.import_source(source, dry_run=False)
assert request_mock.mock_calls == []
assert source.session.request.mock_calls == [call("HEAD", "https://source.example.org/foobar.tgz")]
assert destination.session.request.mock_calls == [
call("HEAD", "https://destination.example.org/foobar.tgz")
]
assert logger.mock_calls == []
def test_import_dry_run(self):
"""Test import_source method, with dry_run."""
with patch("gitlabracadabra.packages.destination.logger", autospec=True) as logger:
destination = Destination(log_prefix="[foobar] ")
destination.get_url = MagicMock()
destination.get_url.return_value = "https://destination.example.org/not_exists.tgz"
destination.session.request = MagicMock(side_effect=self._mocked_request)
source = MagicMock()
source.session.request = MagicMock(side_effect=self._mocked_request)
source.package_files.return_value = [
PackageFile("https://source.example.org/foobar.tgz", "generic", "foobar")
]
with patch.object(Session, "request") as request_mock:
request_mock.side_effect = self._mocked_request
destination.import_source(source, dry_run=True)
assert request_mock.mock_calls == []
assert source.session.request.mock_calls == [call("HEAD", "https://source.example.org/foobar.tgz")]
assert destination.session.request.mock_calls == [
call("HEAD", "https://destination.example.org/not_exists.tgz")
]
assert logger.mock_calls == [
call.info(
'%sNOT uploading %s package file "%s" from "%s" version %s (%s): Dry run',
"[foobar] ",
"generic",
"foobar.tgz",
"foobar",
"0",
"https://source.example.org/foobar.tgz",
)
]
def test_import_source_proxy_error(self):
"""Test import_source method, with ProxyError raised."""
with patch("gitlabracadabra.packages.destination.logger", autospec=True) as logger:
destination = Destination(log_prefix="[foobar] ")
destination.session.request = MagicMock(side_effect=self._mocked_request)
source = MagicMock()
source.session = Session() # Not mocked
source.package_files.return_value = [
PackageFile("https://source.example.org/anything.tgz", "generic", "foobar")
]
with set_environ("HTTPS_PROXY", "http://localhost:42"):
destination.import_source(source, dry_run=False)
assert destination.session.request.mock_calls == []
_, args, _ = logger.mock_calls[0]
msg = args[8]
assert re_search(
re_escape(
"ProxyError(MaxRetryError(\"HTTPSConnectionPool(host='source.example.org', port=443): Max retries exceeded with url: /anything.tgz (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f9b3ef3c8e0>: Failed to establish a new connection: [Errno 111] Connection refused')))"
)
.replace("0x7f9b3ef3c8e0", "0x[0-9A-Fa-f]+")
.replace("Cannot\\ connect\\ to\\ proxy\\.", "(Cannot|Unable\\ to)\\ connect\\ to\\ proxy\\.?")
.replace("urllib3\\.connection\\.HTTPSConnection", "urllib3\\.connection\\.(Verified)?HTTPSConnection"),
msg,
)
assert logger.mock_calls == [
call.warning(
'%sError processing %s package file "%s" from "%s" version %s (%s %s): %s',
"[foobar] ",
"generic",
"anything.tgz",
"foobar",
"0",
"HEAD",
"https://source.example.org/anything.tgz",
msg,
)
]
def test_import_source_proxy_error2(self):
"""Test import_source method, with ProxyError raised while retrieving package files."""
with patch("gitlabracadabra.packages.destination.logger", autospec=True) as logger:
destination = Destination(log_prefix="[foobar] ")
source = Helm(log_prefix="[foobar] ", repo_url="https://source.example.org", package_name="foo")
with set_environ("HTTPS_PROXY", "http://localhost:42"):
destination.import_source(source, dry_run=False)
_, args, _ = logger.mock_calls[0]
msg = args[5]
assert re_search(
re_escape(
"ProxyError(MaxRetryError(\"HTTPSConnectionPool(host='source.example.org', port=443): Max retries exceeded with url: /index.yaml (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f9b3ef3c8e0>: Failed to establish a new connection: [Errno 111] Connection refused')))"
)
.replace("0x7f9b3ef3c8e0", "0x[0-9A-Fa-f]+")
.replace("Cannot\\ connect\\ to\\ proxy\\.", "(Cannot|Unable\\ to)\\ connect\\ to\\ proxy\\.?")
.replace("urllib3\\.connection\\.HTTPSConnection", "urllib3\\.connection\\.(Verified)?HTTPSConnection"),
msg,
)
assert logger.mock_calls == [
call.warning(
"%sError retrieving package files list from %s (%s %s): %s",
"[foobar] ",
str(source),
"GET",
"https://source.example.org/index.yaml",
msg,
)
]
def test_import_upload(self):
"""Test import_source method, without dry_run."""
with patch("gitlabracadabra.packages.destination.logger", autospec=True) as logger:
destination = Destination(log_prefix="[foobar] ")
destination.get_url = MagicMock()
destination.get_url.return_value = "https://destination.example.org/not_exists.tgz"
destination.session.request = MagicMock(side_effect=self._mocked_request)
source = MagicMock()
source.session.request = MagicMock(side_effect=self._mocked_request)
source.package_files.return_value = [
PackageFile("https://source.example.org/foobar.tgz", "generic", "foobar")
]
with patch.object(Session, "request") as request_mock:
destination.import_source(source, dry_run=False)
with patch.object(Stream, "__eq__") as stream_eq_mock:
stream_eq_mock.return_value = True
assert request_mock.mock_calls == []
assert source.session.request.mock_calls == [
call("HEAD", "https://source.example.org/foobar.tgz"),
call(
"GET",
"https://source.example.org/foobar.tgz",
stream=True,
headers={"Accept-Encoding": "*"},
),
]
assert destination.session.request.mock_calls == [
call("HEAD", "https://destination.example.org/not_exists.tgz"),
call(
"PUT", "https://destination.example.org/not_exists.tgz", data=Stream("a file-like object")
),
]
assert logger.mock_calls == [
call.info(
'%sUploading %s package file "%s" from "%s" version %s (%s)',
"[foobar] ",
"generic",
"foobar.tgz",
"foobar",
"0",
"https://source.example.org/foobar.tgz",
)
]
def _mocked_request(
self,
method: str,
url: str,
data: Stream | None = None, # noqa: ARG002
headers: dict[str, str] | None = None, # noqa: ARG002
stream: bool | None = None,
auth: AuthBase | None = None, # noqa: ARG002
) -> Response:
response = Response()
if method in {"HEAD", "GET"}:
if url in {"https://source.example.org/foobar.tgz", "https://destination.example.org/foobar.tgz"}:
response.status_code = 200
if stream is True:
response.raw = "a file-like object"
else:
response.status_code = 404
elif method == "PUT" and url == "https://destination.example.org/not_exists.tgz":
response.status_code = 201
return response
|