| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright: (c) 2019, Ansible Project |
| 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 json |
| 8 |
import os |
| 9 |
import pytest |
| 10 |
import re |
| 11 |
import tarfile |
| 12 |
import tempfile |
| 13 |
import uuid |
| 14 |
|
| 15 |
from hashlib import sha256 |
| 16 |
from io import BytesIO |
| 17 |
from unittest.mock import MagicMock, mock_open, patch |
| 18 |
|
| 19 |
import ansible.constants as C |
| 20 |
from ansible import context |
| 21 |
from ansible.cli.galaxy import GalaxyCLI |
| 22 |
from ansible.config import manager |
| 23 |
from ansible.errors import AnsibleError |
| 24 |
from ansible.galaxy import api, collection, token |
| 25 |
from ansible.module_utils.common.sentinel import Sentinel |
| 26 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 27 |
from ansible.module_utils.common.file import S_IRWU_RG_RO |
| 28 |
import builtins |
| 29 |
from ansible.utils import context_objects as co |
| 30 |
from ansible.utils.display import Display |
| 31 |
from ansible.utils.hashing import secure_hash_s |
| 32 |
|
| 33 |
|
| 34 |
@pytest.fixture(autouse=True) |
| 35 |
def reset_cli_args(): |
| 36 |
co.GlobalCLIArgs._Singleton__instance = None |
| 37 |
yield |
| 38 |
co.GlobalCLIArgs._Singleton__instance = None |
| 39 |
|
| 40 |
|
| 41 |
@pytest.fixture |
| 42 |
def collection_path_suffix(request): |
| 43 |
"""Return test collection path suffix or the default.""" |
| 44 |
return getattr(request, 'param', 'test-ÅÑŚÌβŁÈ Collections Input') |
| 45 |
|
| 46 |
|
| 47 |
@pytest.fixture |
| 48 |
def collection_input(tmp_path_factory, collection_path_suffix): |
| 49 |
"""Create a collection skeleton directory for build tests.""" |
| 50 |
test_dir = to_text(tmp_path_factory.mktemp(collection_path_suffix)) |
| 51 |
|
| 52 |
namespace = 'ansible_namespace' |
| 53 |
collection = 'collection' |
| 54 |
skeleton = os.path.join(os.path.dirname(os.path.split(__file__)[0]), 'cli', 'test_data', 'collection_skeleton') |
| 55 |
|
| 56 |
galaxy_args = ['ansible-galaxy', 'collection', 'init', '%s.%s' % (namespace, collection), |
| 57 |
'-c', '--init-path', test_dir, '--collection-skeleton', skeleton] |
| 58 |
GalaxyCLI(args=galaxy_args).run() |
| 59 |
collection_dir = os.path.join(test_dir, namespace, collection) |
| 60 |
output_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Output')) |
| 61 |
|
| 62 |
return collection_dir, output_dir |
| 63 |
|
| 64 |
|
| 65 |
@pytest.fixture() |
| 66 |
def collection_artifact(monkeypatch, tmp_path_factory): |
| 67 |
""" Creates a temp collection artifact and mocked open_url instance for publishing tests """ |
| 68 |
mock_open = MagicMock() |
| 69 |
monkeypatch.setattr(collection.concrete_artifact_manager, 'open_url', mock_open) |
| 70 |
|
| 71 |
mock_uuid = MagicMock() |
| 72 |
mock_uuid.return_value.hex = 'uuid' |
| 73 |
monkeypatch.setattr(uuid, 'uuid4', mock_uuid) |
| 74 |
|
| 75 |
tmp_path = tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections') |
| 76 |
input_file = to_text(tmp_path / 'collection.tar.gz') |
| 77 |
|
| 78 |
with tarfile.open(input_file, 'w:gz') as tfile: |
| 79 |
b_io = BytesIO(b"\x00\x01\x02\x03") |
| 80 |
tar_info = tarfile.TarInfo('test') |
| 81 |
tar_info.size = 4 |
| 82 |
tar_info.mode = S_IRWU_RG_RO |
| 83 |
tfile.addfile(tarinfo=tar_info, fileobj=b_io) |
| 84 |
|
| 85 |
return input_file, mock_open |
| 86 |
|
| 87 |
|
| 88 |
@pytest.fixture() |
| 89 |
def galaxy_yml_dir(request, tmp_path_factory): |
| 90 |
b_test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections')) |
| 91 |
b_galaxy_yml = os.path.join(b_test_dir, b'galaxy.yml') |
| 92 |
with open(b_galaxy_yml, 'wb') as galaxy_obj: |
| 93 |
galaxy_obj.write(to_bytes(request.param)) |
| 94 |
|
| 95 |
yield b_test_dir |
| 96 |
|
| 97 |
|
| 98 |
@pytest.fixture() |
| 99 |
def tmp_tarfile(tmp_path_factory, manifest_info): |
| 100 |
""" Creates a temporary tar file for _extract_tar_file tests """ |
| 101 |
filename = u'ÅÑŚÌβŁÈ' |
| 102 |
temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Collections' % to_native(filename))) |
| 103 |
tar_file = os.path.join(temp_dir, to_bytes('%s.tar.gz' % filename)) |
| 104 |
data = os.urandom(8) |
| 105 |
|
| 106 |
with tarfile.open(tar_file, 'w:gz') as tfile: |
| 107 |
b_io = BytesIO(data) |
| 108 |
tar_info = tarfile.TarInfo(filename) |
| 109 |
tar_info.size = len(data) |
| 110 |
tar_info.mode = S_IRWU_RG_RO |
| 111 |
tfile.addfile(tarinfo=tar_info, fileobj=b_io) |
| 112 |
|
| 113 |
b_data = to_bytes(json.dumps(manifest_info, indent=True), errors='surrogate_or_strict') |
| 114 |
b_io = BytesIO(b_data) |
| 115 |
tar_info = tarfile.TarInfo('MANIFEST.json') |
| 116 |
tar_info.size = len(b_data) |
| 117 |
tar_info.mode = S_IRWU_RG_RO |
| 118 |
tfile.addfile(tarinfo=tar_info, fileobj=b_io) |
| 119 |
|
| 120 |
sha256_hash = sha256() |
| 121 |
sha256_hash.update(data) |
| 122 |
|
| 123 |
with tarfile.open(tar_file, 'r') as tfile: |
| 124 |
yield temp_dir, tfile, filename, sha256_hash.hexdigest() |
| 125 |
|
| 126 |
|
| 127 |
@pytest.fixture() |
| 128 |
def galaxy_server(): |
| 129 |
context.CLIARGS._store = {'ignore_certs': False} |
| 130 |
galaxy_api = api.GalaxyAPI(None, 'test_server', 'https://galaxy.ansible.com', |
| 131 |
token=token.GalaxyToken(token='key')) |
| 132 |
return galaxy_api |
| 133 |
|
| 134 |
|
| 135 |
@pytest.fixture() |
| 136 |
def manifest_template(): |
| 137 |
def get_manifest_info(namespace='ansible_namespace', name='collection', version='0.1.0'): |
| 138 |
return { |
| 139 |
"collection_info": { |
| 140 |
"namespace": namespace, |
| 141 |
"name": name, |
| 142 |
"version": version, |
| 143 |
"authors": [ |
| 144 |
"shertel" |
| 145 |
], |
| 146 |
"readme": "README.md", |
| 147 |
"tags": [ |
| 148 |
"test", |
| 149 |
"collection" |
| 150 |
], |
| 151 |
"description": "Test", |
| 152 |
"license": [ |
| 153 |
"MIT" |
| 154 |
], |
| 155 |
"license_file": None, |
| 156 |
"dependencies": {}, |
| 157 |
"repository": "https://github.com/{0}/{1}".format(namespace, name), |
| 158 |
"documentation": None, |
| 159 |
"homepage": None, |
| 160 |
"issues": None |
| 161 |
}, |
| 162 |
"file_manifest_file": { |
| 163 |
"name": "FILES.json", |
| 164 |
"ftype": "file", |
| 165 |
"chksum_type": "sha256", |
| 166 |
"chksum_sha256": "files_manifest_checksum", |
| 167 |
"format": 1 |
| 168 |
}, |
| 169 |
"format": 1 |
| 170 |
} |
| 171 |
|
| 172 |
return get_manifest_info |
| 173 |
|
| 174 |
|
| 175 |
@pytest.fixture() |
| 176 |
def manifest_info(manifest_template): |
| 177 |
return manifest_template() |
| 178 |
|
| 179 |
|
| 180 |
@pytest.fixture() |
| 181 |
def manifest(manifest_info): |
| 182 |
b_data = to_bytes(json.dumps(manifest_info)) |
| 183 |
|
| 184 |
with patch.object(builtins, 'open', mock_open(read_data=b_data)) as m: |
| 185 |
with open('MANIFEST.json', mode='rb') as fake_file: |
| 186 |
yield fake_file, sha256(b_data).hexdigest() |
| 187 |
|
| 188 |
|
| 189 |
@pytest.mark.parametrize( |
| 190 |
'required_signature_count,valid', |
| 191 |
[ |
| 192 |
("1", True), |
| 193 |
("+1", True), |
| 194 |
("all", True), |
| 195 |
("+all", True), |
| 196 |
("-1", False), |
| 197 |
("invalid", False), |
| 198 |
("1.5", False), |
| 199 |
("+", False), |
| 200 |
] |
| 201 |
) |
| 202 |
def test_cli_options(required_signature_count, valid, monkeypatch): |
| 203 |
cli_args = [ |
| 204 |
'ansible-galaxy', |
| 205 |
'collection', |
| 206 |
'install', |
| 207 |
'namespace.collection:1.0.0', |
| 208 |
'--keyring', |
| 209 |
'~/.ansible/pubring.kbx', |
| 210 |
'--required-valid-signature-count', |
| 211 |
required_signature_count |
| 212 |
] |
| 213 |
|
| 214 |
galaxy_cli = GalaxyCLI(args=cli_args) |
| 215 |
mock_execute_install = MagicMock() |
| 216 |
monkeypatch.setattr(galaxy_cli, '_execute_install_collection', mock_execute_install) |
| 217 |
|
| 218 |
if valid: |
| 219 |
galaxy_cli.run() |
| 220 |
else: |
| 221 |
with pytest.raises(SystemExit, match='2') as error: |
| 222 |
galaxy_cli.run() |
| 223 |
|
| 224 |
|
| 225 |
@pytest.mark.parametrize( |
| 226 |
"config,server", |
| 227 |
[ |
| 228 |
( |
| 229 |
# Options to create ini config |
| 230 |
{ |
| 231 |
'url': 'https://galaxy.ansible.com', |
| 232 |
'validate_certs': 'False', |
| 233 |
}, |
| 234 |
# Expected server attributes |
| 235 |
{ |
| 236 |
'validate_certs': False, |
| 237 |
}, |
| 238 |
), |
| 239 |
( |
| 240 |
{ |
| 241 |
'url': 'https://galaxy.ansible.com', |
| 242 |
'validate_certs': 'True', |
| 243 |
}, |
| 244 |
{ |
| 245 |
'validate_certs': True, |
| 246 |
}, |
| 247 |
), |
| 248 |
], |
| 249 |
) |
| 250 |
def test_bool_type_server_config_options(config, server, monkeypatch): |
| 251 |
cli_args = [ |
| 252 |
'ansible-galaxy', |
| 253 |
'collection', |
| 254 |
'install', |
| 255 |
'namespace.collection:1.0.0', |
| 256 |
] |
| 257 |
|
| 258 |
config_lines = [ |
| 259 |
"[galaxy]", |
| 260 |
"server_list=server1\n", |
| 261 |
"[galaxy_server.server1]", |
| 262 |
"url=%s" % config['url'], |
| 263 |
"validate_certs=%s\n" % config['validate_certs'], |
| 264 |
] |
| 265 |
|
| 266 |
with tempfile.NamedTemporaryFile(suffix='.cfg') as tmp_file: |
| 267 |
tmp_file.write( |
| 268 |
to_bytes('\n'.join(config_lines)) |
| 269 |
) |
| 270 |
tmp_file.flush() |
| 271 |
|
| 272 |
with patch.object(C, 'GALAXY_SERVER_LIST', ['server1']): |
| 273 |
with patch.object(C.config, '_config_file', tmp_file.name): |
| 274 |
C.config._parse_config_file() |
| 275 |
galaxy_cli = GalaxyCLI(args=cli_args) |
| 276 |
mock_execute_install = MagicMock() |
| 277 |
monkeypatch.setattr(galaxy_cli, '_execute_install_collection', mock_execute_install) |
| 278 |
galaxy_cli.run() |
| 279 |
|
| 280 |
assert galaxy_cli.api_servers[0].name == 'server1' |
| 281 |
assert galaxy_cli.api_servers[0].validate_certs == server['validate_certs'] |
| 282 |
|
| 283 |
|
| 284 |
@pytest.mark.parametrize('global_ignore_certs', [True, False]) |
| 285 |
def test_validate_certs(global_ignore_certs, monkeypatch): |
| 286 |
cli_args = [ |
| 287 |
'ansible-galaxy', |
| 288 |
'collection', |
| 289 |
'install', |
| 290 |
'namespace.collection:1.0.0', |
| 291 |
] |
| 292 |
if global_ignore_certs: |
| 293 |
cli_args.append('--ignore-certs') |
| 294 |
|
| 295 |
galaxy_cli = GalaxyCLI(args=cli_args) |
| 296 |
mock_execute_install = MagicMock() |
| 297 |
monkeypatch.setattr(galaxy_cli, '_execute_install_collection', mock_execute_install) |
| 298 |
galaxy_cli.run() |
| 299 |
|
| 300 |
assert len(galaxy_cli.api_servers) == 1 |
| 301 |
assert galaxy_cli.api_servers[0].validate_certs is not global_ignore_certs |
| 302 |
|
| 303 |
|
| 304 |
@pytest.mark.parametrize( |
| 305 |
["ignore_certs_cli", "ignore_certs_cfg", "expected_validate_certs"], |
| 306 |
[ |
| 307 |
(None, None, True), |
| 308 |
(None, True, False), |
| 309 |
(None, False, True), |
| 310 |
(True, None, False), |
| 311 |
(True, True, False), |
| 312 |
(True, False, False), |
| 313 |
] |
| 314 |
) |
| 315 |
def test_validate_certs_with_server_url(ignore_certs_cli, ignore_certs_cfg, expected_validate_certs, monkeypatch): |
| 316 |
cli_args = [ |
| 317 |
'ansible-galaxy', |
| 318 |
'collection', |
| 319 |
'install', |
| 320 |
'namespace.collection:1.0.0', |
| 321 |
'-s', |
| 322 |
'https://galaxy.ansible.com' |
| 323 |
] |
| 324 |
if ignore_certs_cli: |
| 325 |
cli_args.append('--ignore-certs') |
| 326 |
if ignore_certs_cfg is not None: |
| 327 |
monkeypatch.setattr(C, 'GALAXY_IGNORE_CERTS', ignore_certs_cfg) |
| 328 |
|
| 329 |
galaxy_cli = GalaxyCLI(args=cli_args) |
| 330 |
mock_execute_install = MagicMock() |
| 331 |
monkeypatch.setattr(galaxy_cli, '_execute_install_collection', mock_execute_install) |
| 332 |
galaxy_cli.run() |
| 333 |
|
| 334 |
assert len(galaxy_cli.api_servers) == 1 |
| 335 |
assert galaxy_cli.api_servers[0].validate_certs == expected_validate_certs |
| 336 |
|
| 337 |
|
| 338 |
@pytest.mark.parametrize( |
| 339 |
["ignore_certs_cli", "ignore_certs_cfg", "expected_server2_validate_certs", "expected_server3_validate_certs"], |
| 340 |
[ |
| 341 |
(None, None, True, True), |
| 342 |
(None, True, True, False), |
| 343 |
(None, False, True, True), |
| 344 |
(True, None, False, False), |
| 345 |
(True, True, False, False), |
| 346 |
(True, False, False, False), |
| 347 |
] |
| 348 |
) |
| 349 |
def test_validate_certs_server_config(ignore_certs_cfg, ignore_certs_cli, expected_server2_validate_certs, expected_server3_validate_certs, monkeypatch): |
| 350 |
server_names = ['server1', 'server2', 'server3'] |
| 351 |
cfg_lines = [ |
| 352 |
"[galaxy]", |
| 353 |
"server_list=server1,server2,server3", |
| 354 |
"[galaxy_server.server1]", |
| 355 |
"url=https://galaxy.ansible.com/api/", |
| 356 |
"validate_certs=False", |
| 357 |
"[galaxy_server.server2]", |
| 358 |
"url=https://galaxy.ansible.com/api/", |
| 359 |
"validate_certs=True", |
| 360 |
"[galaxy_server.server3]", |
| 361 |
"url=https://galaxy.ansible.com/api/", |
| 362 |
] |
| 363 |
cli_args = [ |
| 364 |
'ansible-galaxy', |
| 365 |
'collection', |
| 366 |
'install', |
| 367 |
'namespace.collection:1.0.0', |
| 368 |
] |
| 369 |
if ignore_certs_cli: |
| 370 |
cli_args.append('--ignore-certs') |
| 371 |
if ignore_certs_cfg is not None: |
| 372 |
monkeypatch.setattr(C, 'GALAXY_IGNORE_CERTS', ignore_certs_cfg) |
| 373 |
|
| 374 |
monkeypatch.setattr(C, 'GALAXY_SERVER_LIST', server_names) |
| 375 |
|
| 376 |
with tempfile.NamedTemporaryFile(suffix='.cfg') as tmp_file: |
| 377 |
tmp_file.write(to_bytes('\n'.join(cfg_lines), errors='surrogate_or_strict')) |
| 378 |
tmp_file.flush() |
| 379 |
|
| 380 |
monkeypatch.setattr(C.config, '_config_file', tmp_file.name) |
| 381 |
C.config._parse_config_file() |
| 382 |
galaxy_cli = GalaxyCLI(args=cli_args) |
| 383 |
mock_execute_install = MagicMock() |
| 384 |
monkeypatch.setattr(galaxy_cli, '_execute_install_collection', mock_execute_install) |
| 385 |
galaxy_cli.run() |
| 386 |
|
| 387 |
# (not) --ignore-certs > server's validate_certs > (not) GALAXY_IGNORE_CERTS > True |
| 388 |
assert galaxy_cli.api_servers[0].validate_certs is False |
| 389 |
assert galaxy_cli.api_servers[1].validate_certs is expected_server2_validate_certs |
| 390 |
assert galaxy_cli.api_servers[2].validate_certs is expected_server3_validate_certs |
| 391 |
|
| 392 |
|
| 393 |
@pytest.mark.parametrize( |
| 394 |
["timeout_cli", "timeout_cfg", "timeout_fallback", "expected_timeout"], |
| 395 |
[ |
| 396 |
(None, None, None, 60), |
| 397 |
(None, None, 10, 10), |
| 398 |
(None, 20, 10, 20), |
| 399 |
(30, 20, 10, 30), |
| 400 |
] |
| 401 |
) |
| 402 |
def test_timeout_server_config(timeout_cli, timeout_cfg, timeout_fallback, expected_timeout, monkeypatch): |
| 403 |
cli_args = [ |
| 404 |
'ansible-galaxy', |
| 405 |
'collection', |
| 406 |
'install', |
| 407 |
'namespace.collection:1.0.0', |
| 408 |
] |
| 409 |
if timeout_cli is not None: |
| 410 |
cli_args.extend(["--timeout", f"{timeout_cli}"]) |
| 411 |
|
| 412 |
cfg_lines = ["[galaxy]", "server_list=server1"] |
| 413 |
if timeout_fallback is not None: |
| 414 |
cfg_lines.append(f"server_timeout={timeout_fallback}") |
| 415 |
|
| 416 |
# fix default in server config since C.GALAXY_SERVER_TIMEOUT was already evaluated |
| 417 |
server_additional = manager.GALAXY_SERVER_ADDITIONAL.copy() |
| 418 |
server_additional['timeout']['default'] = timeout_fallback |
| 419 |
monkeypatch.setattr(manager, 'GALAXY_SERVER_ADDITIONAL', server_additional) |
| 420 |
|
| 421 |
cfg_lines.extend(["[galaxy_server.server1]", "url=https://galaxy.ansible.com/api/"]) |
| 422 |
if timeout_cfg is not None: |
| 423 |
cfg_lines.append(f"timeout={timeout_cfg}") |
| 424 |
|
| 425 |
monkeypatch.setattr(C, 'GALAXY_SERVER_LIST', ['server1']) |
| 426 |
|
| 427 |
with tempfile.NamedTemporaryFile(suffix='.cfg') as tmp_file: |
| 428 |
tmp_file.write(to_bytes('\n'.join(cfg_lines), errors='surrogate_or_strict')) |
| 429 |
tmp_file.flush() |
| 430 |
|
| 431 |
monkeypatch.setattr(C.config, '_config_file', tmp_file.name) |
| 432 |
C.config._parse_config_file() |
| 433 |
|
| 434 |
galaxy_cli = GalaxyCLI(args=cli_args) |
| 435 |
mock_execute_install = MagicMock() |
| 436 |
monkeypatch.setattr(galaxy_cli, '_execute_install_collection', mock_execute_install) |
| 437 |
galaxy_cli.run() |
| 438 |
|
| 439 |
assert galaxy_cli.api_servers[0].timeout == expected_timeout |
| 440 |
|
| 441 |
|
| 442 |
def test_build_collection_no_galaxy_yaml(): |
| 443 |
fake_path = u'/fake/ÅÑŚÌβŁÈ/path' |
| 444 |
expected = to_native("The collection galaxy.yml path '%s/galaxy.yml' does not exist." % fake_path) |
| 445 |
|
| 446 |
with pytest.raises(AnsibleError, match=expected): |
| 447 |
collection.build_collection(fake_path, u'output', False) |
| 448 |
|
| 449 |
|
| 450 |
def test_build_existing_output_file(collection_input): |
| 451 |
input_dir, output_dir = collection_input |
| 452 |
|
| 453 |
existing_output_dir = os.path.join(output_dir, 'ansible_namespace-collection-0.1.0.tar.gz') |
| 454 |
os.makedirs(existing_output_dir) |
| 455 |
|
| 456 |
expected = "The output collection artifact '%s' already exists, but is a directory - aborting" \ |
| 457 |
% to_native(existing_output_dir) |
| 458 |
with pytest.raises(AnsibleError, match=expected): |
| 459 |
collection.build_collection(to_text(input_dir, errors='surrogate_or_strict'), to_text(output_dir, errors='surrogate_or_strict'), False) |
| 460 |
|
| 461 |
|
| 462 |
def test_build_existing_output_without_force(collection_input): |
| 463 |
input_dir, output_dir = collection_input |
| 464 |
|
| 465 |
existing_output = os.path.join(output_dir, 'ansible_namespace-collection-0.1.0.tar.gz') |
| 466 |
with open(existing_output, 'w+') as out_file: |
| 467 |
out_file.write("random garbage") |
| 468 |
out_file.flush() |
| 469 |
|
| 470 |
expected = "The file '%s' already exists. You can use --force to re-create the collection artifact." \ |
| 471 |
% to_native(existing_output) |
| 472 |
with pytest.raises(AnsibleError, match=expected): |
| 473 |
collection.build_collection(to_text(input_dir, errors='surrogate_or_strict'), to_text(output_dir, errors='surrogate_or_strict'), False) |
| 474 |
|
| 475 |
|
| 476 |
@pytest.mark.parametrize( |
| 477 |
'collection_path_suffix', |
| 478 |
( |
| 479 |
'test-ÅÑŚÌβŁÈ Collections Input 1 with_slash/', |
| 480 |
'test-ÅÑŚÌβŁÈ Collections Input 2 no slash', |
| 481 |
), |
| 482 |
indirect=('collection_path_suffix', ), |
| 483 |
) |
| 484 |
def test_build_existing_output_with_force(collection_input): |
| 485 |
input_dir, output_dir = collection_input |
| 486 |
|
| 487 |
existing_output = os.path.join(output_dir, 'ansible_namespace-collection-0.1.0.tar.gz') |
| 488 |
with open(existing_output, 'w+') as out_file: |
| 489 |
out_file.write("random garbage") |
| 490 |
out_file.flush() |
| 491 |
|
| 492 |
collection.build_collection(to_text(input_dir, errors='surrogate_or_strict'), to_text(output_dir, errors='surrogate_or_strict'), True) |
| 493 |
|
| 494 |
# Verify the file was replaced with an actual tar file |
| 495 |
assert tarfile.is_tarfile(existing_output) |
| 496 |
|
| 497 |
|
| 498 |
def test_build_with_existing_files_and_manifest(collection_input): |
| 499 |
input_dir, output_dir = collection_input |
| 500 |
|
| 501 |
with open(os.path.join(input_dir, 'MANIFEST.json'), "wb") as fd: |
| 502 |
fd.write(b'{"collection_info": {"version": "6.6.6"}, "version": 1}') |
| 503 |
|
| 504 |
with open(os.path.join(input_dir, 'FILES.json'), "wb") as fd: |
| 505 |
fd.write(b'{"files": [], "format": 1}') |
| 506 |
|
| 507 |
with open(os.path.join(input_dir, "plugins", "MANIFEST.json"), "wb") as fd: |
| 508 |
fd.write(b"test data that should be in build") |
| 509 |
|
| 510 |
collection.build_collection(to_text(input_dir, errors='surrogate_or_strict'), to_text(output_dir, errors='surrogate_or_strict'), False) |
| 511 |
|
| 512 |
output_artifact = os.path.join(output_dir, 'ansible_namespace-collection-0.1.0.tar.gz') |
| 513 |
assert tarfile.is_tarfile(output_artifact) |
| 514 |
|
| 515 |
with tarfile.open(output_artifact, mode='r') as actual: |
| 516 |
members = actual.getmembers() |
| 517 |
|
| 518 |
manifest_file = [m for m in members if m.path == "MANIFEST.json"][0] |
| 519 |
manifest_file_obj = actual.extractfile(manifest_file.name) |
| 520 |
manifest_file_text = manifest_file_obj.read() |
| 521 |
manifest_file_obj.close() |
| 522 |
assert manifest_file_text != b'{"collection_info": {"version": "6.6.6"}, "version": 1}' |
| 523 |
|
| 524 |
json_file = [m for m in members if m.path == "MANIFEST.json"][0] |
| 525 |
json_file_obj = actual.extractfile(json_file.name) |
| 526 |
json_file_text = json_file_obj.read() |
| 527 |
json_file_obj.close() |
| 528 |
assert json_file_text != b'{"files": [], "format": 1}' |
| 529 |
|
| 530 |
sub_manifest_file = [m for m in members if m.path == "plugins/MANIFEST.json"][0] |
| 531 |
sub_manifest_file_obj = actual.extractfile(sub_manifest_file.name) |
| 532 |
sub_manifest_file_text = sub_manifest_file_obj.read() |
| 533 |
sub_manifest_file_obj.close() |
| 534 |
assert sub_manifest_file_text == b"test data that should be in build" |
| 535 |
|
| 536 |
|
| 537 |
@pytest.mark.parametrize('galaxy_yml_dir', [b'namespace: value: broken'], indirect=True) |
| 538 |
def test_invalid_yaml_galaxy_file(galaxy_yml_dir): |
| 539 |
galaxy_file = os.path.join(galaxy_yml_dir, b'galaxy.yml') |
| 540 |
expected = to_native(b"Failed to parse the galaxy.yml at '%s' with the following error:" % galaxy_file) |
| 541 |
|
| 542 |
with pytest.raises(AnsibleError, match=expected): |
| 543 |
collection.concrete_artifact_manager._get_meta_from_src_dir(galaxy_yml_dir) |
| 544 |
|
| 545 |
|
| 546 |
@pytest.mark.parametrize('galaxy_yml_dir', [b'namespace: test_namespace'], indirect=True) |
| 547 |
def test_missing_required_galaxy_key(galaxy_yml_dir): |
| 548 |
galaxy_file = os.path.join(galaxy_yml_dir, b'galaxy.yml') |
| 549 |
expected = "The collection galaxy.yml at '%s' is missing the following mandatory keys: authors, name, " \ |
| 550 |
"readme, version" % to_native(galaxy_file) |
| 551 |
|
| 552 |
with pytest.raises(AnsibleError, match=expected): |
| 553 |
collection.concrete_artifact_manager._get_meta_from_src_dir(galaxy_yml_dir) |
| 554 |
|
| 555 |
|
| 556 |
@pytest.mark.parametrize('galaxy_yml_dir', [b'namespace: test_namespace'], indirect=True) |
| 557 |
def test_galaxy_yaml_no_mandatory_keys(galaxy_yml_dir): |
| 558 |
expected = "The collection galaxy.yml at '%s/galaxy.yml' is missing the " \ |
| 559 |
"following mandatory keys: authors, name, readme, version" % to_native(galaxy_yml_dir) |
| 560 |
|
| 561 |
with pytest.raises(ValueError, match=expected): |
| 562 |
assert collection.concrete_artifact_manager._get_meta_from_src_dir(galaxy_yml_dir, require_build_metadata=False) == expected |
| 563 |
|
| 564 |
|
| 565 |
@pytest.mark.parametrize('galaxy_yml_dir', [b'My life story is so very interesting'], indirect=True) |
| 566 |
def test_galaxy_yaml_no_mandatory_keys_bad_yaml(galaxy_yml_dir): |
| 567 |
expected = "The collection galaxy.yml at '%s/galaxy.yml' is incorrectly formatted." % to_native(galaxy_yml_dir) |
| 568 |
|
| 569 |
with pytest.raises(AnsibleError, match=expected): |
| 570 |
collection.concrete_artifact_manager._get_meta_from_src_dir(galaxy_yml_dir) |
| 571 |
|
| 572 |
|
| 573 |
@pytest.mark.parametrize('galaxy_yml_dir', [b""" |
| 574 |
namespace: namespace |
| 575 |
name: collection |
| 576 |
authors: Jordan |
| 577 |
version: 0.1.0 |
| 578 |
readme: README.md |
| 579 |
invalid: value"""], indirect=True) |
| 580 |
def test_warning_extra_keys(galaxy_yml_dir, monkeypatch): |
| 581 |
display_mock = MagicMock() |
| 582 |
monkeypatch.setattr(Display, 'warning', display_mock) |
| 583 |
|
| 584 |
collection.concrete_artifact_manager._get_meta_from_src_dir(galaxy_yml_dir) |
| 585 |
|
| 586 |
assert display_mock.call_count == 1 |
| 587 |
assert display_mock.call_args[0][0] == "Found unknown keys in collection galaxy.yml at '%s/galaxy.yml': invalid"\ |
| 588 |
% to_text(galaxy_yml_dir) |
| 589 |
|
| 590 |
|
| 591 |
@pytest.mark.parametrize('galaxy_yml_dir', [b""" |
| 592 |
namespace: namespace |
| 593 |
name: collection |
| 594 |
authors: Jordan |
| 595 |
version: 0.1.0 |
| 596 |
readme: README.md"""], indirect=True) |
| 597 |
def test_defaults_galaxy_yml(galaxy_yml_dir): |
| 598 |
actual = collection.concrete_artifact_manager._get_meta_from_src_dir(galaxy_yml_dir) |
| 599 |
|
| 600 |
assert actual['namespace'] == 'namespace' |
| 601 |
assert actual['name'] == 'collection' |
| 602 |
assert actual['authors'] == ['Jordan'] |
| 603 |
assert actual['version'] == '0.1.0' |
| 604 |
assert actual['readme'] == 'README.md' |
| 605 |
assert actual['description'] is None |
| 606 |
assert actual['repository'] is None |
| 607 |
assert actual['documentation'] is None |
| 608 |
assert actual['homepage'] is None |
| 609 |
assert actual['issues'] is None |
| 610 |
assert actual['tags'] == [] |
| 611 |
assert actual['dependencies'] == {} |
| 612 |
assert actual['license'] == [] |
| 613 |
|
| 614 |
|
| 615 |
@pytest.mark.parametrize('galaxy_yml_dir', [(b""" |
| 616 |
namespace: namespace |
| 617 |
name: collection |
| 618 |
authors: Jordan |
| 619 |
version: 0.1.0 |
| 620 |
readme: README.md |
| 621 |
license: MIT"""), (b""" |
| 622 |
namespace: namespace |
| 623 |
name: collection |
| 624 |
authors: Jordan |
| 625 |
version: 0.1.0 |
| 626 |
readme: README.md |
| 627 |
license: |
| 628 |
- MIT""")], indirect=True) |
| 629 |
def test_galaxy_yml_list_value(galaxy_yml_dir): |
| 630 |
actual = collection.concrete_artifact_manager._get_meta_from_src_dir(galaxy_yml_dir) |
| 631 |
assert actual['license'] == ['MIT'] |
| 632 |
|
| 633 |
|
| 634 |
def test_build_ignore_files_and_folders(collection_input, monkeypatch): |
| 635 |
input_dir = collection_input[0] |
| 636 |
|
| 637 |
mock_display = MagicMock() |
| 638 |
monkeypatch.setattr(Display, 'vvv', mock_display) |
| 639 |
|
| 640 |
git_folder = os.path.join(input_dir, '.git') |
| 641 |
retry_file = os.path.join(input_dir, 'ansible.retry') |
| 642 |
|
| 643 |
tests_folder = os.path.join(input_dir, 'tests', 'output') |
| 644 |
tests_output_file = os.path.join(tests_folder, 'result.txt') |
| 645 |
|
| 646 |
os.makedirs(git_folder) |
| 647 |
os.makedirs(tests_folder) |
| 648 |
|
| 649 |
with open(retry_file, 'w+') as ignore_file: |
| 650 |
ignore_file.write('random') |
| 651 |
ignore_file.flush() |
| 652 |
|
| 653 |
with open(tests_output_file, 'w+') as tests_file: |
| 654 |
tests_file.write('random') |
| 655 |
tests_file.flush() |
| 656 |
|
| 657 |
actual = collection._build_files_manifest(to_bytes(input_dir), 'namespace', 'collection', [], Sentinel, None) |
| 658 |
|
| 659 |
assert actual['format'] == 1 |
| 660 |
for manifest_entry in actual['files']: |
| 661 |
assert manifest_entry['name'] not in ['.git', 'ansible.retry', 'galaxy.yml', 'tests/output', 'tests/output/result.txt'] |
| 662 |
|
| 663 |
expected_msgs = [ |
| 664 |
"Skipping '%s/galaxy.yml' for collection build" % to_text(input_dir), |
| 665 |
"Skipping '%s' for collection build" % to_text(retry_file), |
| 666 |
"Skipping '%s' for collection build" % to_text(git_folder), |
| 667 |
"Skipping '%s' for collection build" % to_text(tests_folder), |
| 668 |
] |
| 669 |
assert mock_display.call_count == 4 |
| 670 |
assert mock_display.mock_calls[0][1][0] in expected_msgs |
| 671 |
assert mock_display.mock_calls[1][1][0] in expected_msgs |
| 672 |
assert mock_display.mock_calls[2][1][0] in expected_msgs |
| 673 |
assert mock_display.mock_calls[3][1][0] in expected_msgs |
| 674 |
|
| 675 |
|
| 676 |
def test_build_ignore_older_release_in_root(collection_input, monkeypatch): |
| 677 |
input_dir = collection_input[0] |
| 678 |
|
| 679 |
mock_display = MagicMock() |
| 680 |
monkeypatch.setattr(Display, 'vvv', mock_display) |
| 681 |
|
| 682 |
# This is expected to be ignored because it is in the root collection dir. |
| 683 |
release_file = os.path.join(input_dir, 'namespace-collection-0.0.0.tar.gz') |
| 684 |
|
| 685 |
# This is not expected to be ignored because it is not in the root collection dir. |
| 686 |
fake_release_file = os.path.join(input_dir, 'plugins', 'namespace-collection-0.0.0.tar.gz') |
| 687 |
|
| 688 |
for filename in [release_file, fake_release_file]: |
| 689 |
with open(filename, 'w+') as file_obj: |
| 690 |
file_obj.write('random') |
| 691 |
file_obj.flush() |
| 692 |
|
| 693 |
actual = collection._build_files_manifest(to_bytes(input_dir), 'namespace', 'collection', [], Sentinel, None) |
| 694 |
assert actual['format'] == 1 |
| 695 |
|
| 696 |
plugin_release_found = False |
| 697 |
for manifest_entry in actual['files']: |
| 698 |
assert manifest_entry['name'] != 'namespace-collection-0.0.0.tar.gz' |
| 699 |
if manifest_entry['name'] == 'plugins/namespace-collection-0.0.0.tar.gz': |
| 700 |
plugin_release_found = True |
| 701 |
|
| 702 |
assert plugin_release_found |
| 703 |
|
| 704 |
expected_msgs = [ |
| 705 |
"Skipping '%s/galaxy.yml' for collection build" % to_text(input_dir), |
| 706 |
"Skipping '%s' for collection build" % to_text(release_file) |
| 707 |
] |
| 708 |
assert mock_display.call_count == 2 |
| 709 |
assert mock_display.mock_calls[0][1][0] in expected_msgs |
| 710 |
assert mock_display.mock_calls[1][1][0] in expected_msgs |
| 711 |
|
| 712 |
|
| 713 |
def test_build_ignore_patterns(collection_input, monkeypatch): |
| 714 |
input_dir = collection_input[0] |
| 715 |
|
| 716 |
mock_display = MagicMock() |
| 717 |
monkeypatch.setattr(Display, 'vvv', mock_display) |
| 718 |
|
| 719 |
actual = collection._build_files_manifest(to_bytes(input_dir), 'namespace', 'collection', |
| 720 |
['*.md', 'plugins/action', 'playbooks/*.j2'], |
| 721 |
Sentinel, None) |
| 722 |
assert actual['format'] == 1 |
| 723 |
|
| 724 |
expected_missing = [ |
| 725 |
'README.md', |
| 726 |
'docs/My Collection.md', |
| 727 |
'plugins/action', |
| 728 |
'playbooks/templates/test.conf.j2', |
| 729 |
'playbooks/templates/subfolder/test.conf.j2', |
| 730 |
] |
| 731 |
|
| 732 |
# Files or dirs that are close to a match but are not, make sure they are present |
| 733 |
expected_present = [ |
| 734 |
'docs', |
| 735 |
'roles/common/templates/test.conf.j2', |
| 736 |
'roles/common/templates/subfolder/test.conf.j2', |
| 737 |
] |
| 738 |
|
| 739 |
actual_files = [e['name'] for e in actual['files']] |
| 740 |
for m in expected_missing: |
| 741 |
assert m not in actual_files |
| 742 |
|
| 743 |
for p in expected_present: |
| 744 |
assert p in actual_files |
| 745 |
|
| 746 |
expected_msgs = [ |
| 747 |
"Skipping '%s/galaxy.yml' for collection build" % to_text(input_dir), |
| 748 |
"Skipping '%s/README.md' for collection build" % to_text(input_dir), |
| 749 |
"Skipping '%s/docs/My Collection.md' for collection build" % to_text(input_dir), |
| 750 |
"Skipping '%s/plugins/action' for collection build" % to_text(input_dir), |
| 751 |
"Skipping '%s/playbooks/templates/test.conf.j2' for collection build" % to_text(input_dir), |
| 752 |
"Skipping '%s/playbooks/templates/subfolder/test.conf.j2' for collection build" % to_text(input_dir), |
| 753 |
] |
| 754 |
assert mock_display.call_count == len(expected_msgs) |
| 755 |
assert mock_display.mock_calls[0][1][0] in expected_msgs |
| 756 |
assert mock_display.mock_calls[1][1][0] in expected_msgs |
| 757 |
assert mock_display.mock_calls[2][1][0] in expected_msgs |
| 758 |
assert mock_display.mock_calls[3][1][0] in expected_msgs |
| 759 |
assert mock_display.mock_calls[4][1][0] in expected_msgs |
| 760 |
assert mock_display.mock_calls[5][1][0] in expected_msgs |
| 761 |
|
| 762 |
|
| 763 |
def test_build_ignore_symlink_target_outside_collection(collection_input, monkeypatch): |
| 764 |
input_dir, outside_dir = collection_input |
| 765 |
|
| 766 |
mock_display = MagicMock() |
| 767 |
monkeypatch.setattr(Display, 'warning', mock_display) |
| 768 |
|
| 769 |
link_path = os.path.join(input_dir, 'plugins', 'connection') |
| 770 |
os.symlink(outside_dir, link_path) |
| 771 |
|
| 772 |
actual = collection._build_files_manifest(to_bytes(input_dir), 'namespace', 'collection', [], Sentinel, None) |
| 773 |
for manifest_entry in actual['files']: |
| 774 |
assert manifest_entry['name'] != 'plugins/connection' |
| 775 |
|
| 776 |
assert mock_display.call_count == 1 |
| 777 |
assert mock_display.mock_calls[0][1][0] == "Skipping '%s' as it is a symbolic link to a directory outside " \ |
| 778 |
"the collection" % to_text(link_path) |
| 779 |
|
| 780 |
|
| 781 |
def test_build_copy_symlink_target_inside_collection(collection_input): |
| 782 |
input_dir = collection_input[0] |
| 783 |
|
| 784 |
os.makedirs(os.path.join(input_dir, 'playbooks', 'roles')) |
| 785 |
roles_link = os.path.join(input_dir, 'playbooks', 'roles', 'linked') |
| 786 |
|
| 787 |
roles_target = os.path.join(input_dir, 'roles', 'linked') |
| 788 |
roles_target_tasks = os.path.join(roles_target, 'tasks') |
| 789 |
os.makedirs(roles_target_tasks) |
| 790 |
with open(os.path.join(roles_target_tasks, 'main.yml'), 'w+') as tasks_main: |
| 791 |
tasks_main.write("---\n- hosts: localhost\n tasks:\n - ping:") |
| 792 |
tasks_main.flush() |
| 793 |
|
| 794 |
os.symlink(roles_target, roles_link) |
| 795 |
|
| 796 |
actual = collection._build_files_manifest(to_bytes(input_dir), 'namespace', 'collection', [], Sentinel, None) |
| 797 |
|
| 798 |
linked_entries = [e for e in actual['files'] if e['name'].startswith('playbooks/roles/linked')] |
| 799 |
assert len(linked_entries) == 1 |
| 800 |
assert linked_entries[0]['name'] == 'playbooks/roles/linked' |
| 801 |
assert linked_entries[0]['ftype'] == 'dir' |
| 802 |
|
| 803 |
|
| 804 |
def test_build_with_symlink_inside_collection(collection_input): |
| 805 |
input_dir, output_dir = collection_input |
| 806 |
|
| 807 |
os.makedirs(os.path.join(input_dir, 'playbooks', 'roles')) |
| 808 |
roles_link = os.path.join(input_dir, 'playbooks', 'roles', 'linked') |
| 809 |
file_link = os.path.join(input_dir, 'docs', 'README.md') |
| 810 |
|
| 811 |
roles_target = os.path.join(input_dir, 'roles', 'linked') |
| 812 |
roles_target_tasks = os.path.join(roles_target, 'tasks') |
| 813 |
os.makedirs(roles_target_tasks) |
| 814 |
with open(os.path.join(roles_target_tasks, 'main.yml'), 'w+') as tasks_main: |
| 815 |
tasks_main.write("---\n- hosts: localhost\n tasks:\n - ping:") |
| 816 |
tasks_main.flush() |
| 817 |
|
| 818 |
os.symlink(roles_target, roles_link) |
| 819 |
os.symlink(os.path.join(input_dir, 'README.md'), file_link) |
| 820 |
|
| 821 |
collection.build_collection(to_text(input_dir, errors='surrogate_or_strict'), to_text(output_dir, errors='surrogate_or_strict'), False) |
| 822 |
|
| 823 |
output_artifact = os.path.join(output_dir, 'ansible_namespace-collection-0.1.0.tar.gz') |
| 824 |
assert tarfile.is_tarfile(output_artifact) |
| 825 |
|
| 826 |
with tarfile.open(output_artifact, mode='r') as actual: |
| 827 |
members = actual.getmembers() |
| 828 |
|
| 829 |
linked_folder = [m for m in members if m.path == 'playbooks/roles/linked'][0] |
| 830 |
assert linked_folder.type == tarfile.SYMTYPE |
| 831 |
assert linked_folder.linkname == '../../roles/linked' |
| 832 |
|
| 833 |
linked_file = [m for m in members if m.path == 'docs/README.md'][0] |
| 834 |
assert linked_file.type == tarfile.SYMTYPE |
| 835 |
assert linked_file.linkname == '../README.md' |
| 836 |
|
| 837 |
linked_file_obj = actual.extractfile(linked_file.name) |
| 838 |
actual_file = secure_hash_s(linked_file_obj.read()) |
| 839 |
linked_file_obj.close() |
| 840 |
|
| 841 |
assert actual_file == '08f24200b9fbe18903e7a50930c9d0df0b8d7da3' # shasum test/units/cli/test_data/collection_skeleton/README.md |
| 842 |
|
| 843 |
|
| 844 |
def test_build_files_manifest_sorted_by_name(collection_input): |
| 845 |
"""Verify _build_files_manifest returns files sorted by name.""" |
| 846 |
input_dir = collection_input[0] |
| 847 |
|
| 848 |
for filename in ['z.txt', 'a.txt', 'm.txt']: |
| 849 |
with open(os.path.join(input_dir, filename), 'w') as f: |
| 850 |
f.write('test') |
| 851 |
|
| 852 |
manifest = collection._build_files_manifest(to_bytes(input_dir), 'namespace', 'collection', [], Sentinel, None) |
| 853 |
names = [entry['name'] for entry in manifest['files']] |
| 854 |
|
| 855 |
assert names == sorted(names) |
| 856 |
|
| 857 |
|
| 858 |
def test_publish_no_wait(galaxy_server, collection_artifact, monkeypatch): |
| 859 |
mock_display = MagicMock() |
| 860 |
monkeypatch.setattr(Display, 'display', mock_display) |
| 861 |
|
| 862 |
artifact_path, mock_open = collection_artifact |
| 863 |
fake_import_uri = 'https://galaxy.server.com/api/v3/import/1234' |
| 864 |
|
| 865 |
mock_publish = MagicMock() |
| 866 |
mock_publish.return_value = fake_import_uri |
| 867 |
monkeypatch.setattr(galaxy_server, 'publish_collection', mock_publish) |
| 868 |
|
| 869 |
collection.publish_collection(artifact_path, galaxy_server, False, 0) |
| 870 |
|
| 871 |
assert mock_publish.call_count == 1 |
| 872 |
assert mock_publish.mock_calls[0][1][0] == artifact_path |
| 873 |
|
| 874 |
assert mock_display.call_count == 1 |
| 875 |
assert mock_display.mock_calls[0][1][0] == \ |
| 876 |
"Collection has been pushed to the Galaxy server %s %s, not waiting until import has completed due to " \ |
| 877 |
"--no-wait being set. Import task results can be found at %s" % (galaxy_server.name, galaxy_server.api_server, |
| 878 |
fake_import_uri) |
| 879 |
|
| 880 |
|
| 881 |
def test_publish_with_wait(galaxy_server, collection_artifact, monkeypatch): |
| 882 |
mock_display = MagicMock() |
| 883 |
monkeypatch.setattr(Display, 'display', mock_display) |
| 884 |
|
| 885 |
artifact_path, mock_open = collection_artifact |
| 886 |
fake_import_uri = 'https://galaxy.server.com/api/v3/import/1234' |
| 887 |
|
| 888 |
mock_publish = MagicMock() |
| 889 |
mock_publish.return_value = fake_import_uri |
| 890 |
monkeypatch.setattr(galaxy_server, 'publish_collection', mock_publish) |
| 891 |
|
| 892 |
mock_wait = MagicMock() |
| 893 |
monkeypatch.setattr(galaxy_server, 'wait_import_task', mock_wait) |
| 894 |
|
| 895 |
collection.publish_collection(artifact_path, galaxy_server, True, 0) |
| 896 |
|
| 897 |
assert mock_publish.call_count == 1 |
| 898 |
assert mock_publish.mock_calls[0][1][0] == artifact_path |
| 899 |
|
| 900 |
assert mock_wait.call_count == 1 |
| 901 |
assert mock_wait.mock_calls[0][1][0] == fake_import_uri |
| 902 |
|
| 903 |
assert mock_display.mock_calls[0][1][0] == "Collection has been published to the Galaxy server test_server %s" \ |
| 904 |
% galaxy_server.api_server |
| 905 |
|
| 906 |
|
| 907 |
class MockHTTPResponses: |
| 908 |
def __init__(self, responses: list[tuple[bytes, int | None]]) -> None: |
| 909 |
self._body, self.length = responses[0] |
| 910 |
self._responses = responses[1:] |
| 911 |
self._stream = BytesIO(self._body) |
| 912 |
|
| 913 |
def read(self, size: int = -1) -> bytes: |
| 914 |
data = self._stream.read(size) |
| 915 |
|
| 916 |
if not data: |
| 917 |
# reset the stream to simulate retries |
| 918 |
if self._responses: |
| 919 |
self._body, self.length = self._responses[0] |
| 920 |
del self._responses[0] |
| 921 |
self._stream = BytesIO(self._body) |
| 922 |
|
| 923 |
return data |
| 924 |
|
| 925 |
|
| 926 |
def test_download_file(tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch) -> None: |
| 927 |
temp_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections')) |
| 928 |
|
| 929 |
data = b"\x00\x01\x02\x03" |
| 930 |
sha256_hash = sha256() |
| 931 |
sha256_hash.update(data) |
| 932 |
|
| 933 |
mock_open = MagicMock() |
| 934 |
mock_open.return_value = MockHTTPResponses([(data, len(data))]) |
| 935 |
monkeypatch.setattr(collection.concrete_artifact_manager, 'open_url', mock_open) |
| 936 |
|
| 937 |
expected = temp_dir |
| 938 |
actual = collection._download_file('http://google.com/file', temp_dir, sha256_hash.hexdigest(), True) |
| 939 |
|
| 940 |
assert actual.startswith(expected) |
| 941 |
assert os.path.isfile(actual) |
| 942 |
with open(actual, 'rb') as file_obj: |
| 943 |
assert file_obj.read() == data |
| 944 |
|
| 945 |
assert mock_open.call_count == 1 |
| 946 |
assert mock_open.mock_calls[0][1][0] == 'http://google.com/file' |
| 947 |
|
| 948 |
|
| 949 |
def test_download_file_hash_mismatch(tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch) -> None: |
| 950 |
temp_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections')) |
| 951 |
|
| 952 |
data = b"\x00\x01\x02\x03" |
| 953 |
|
| 954 |
mock_open = MagicMock() |
| 955 |
mock_open.return_value = MockHTTPResponses([(data, len(data))]) |
| 956 |
monkeypatch.setattr(collection.concrete_artifact_manager, 'open_url', mock_open) |
| 957 |
|
| 958 |
expected = "Mismatch artifact hash with downloaded file" |
| 959 |
with pytest.raises(AnsibleError, match=expected): |
| 960 |
collection._download_file('http://google.com/file', temp_dir, 'bad', True) |
| 961 |
|
| 962 |
|
| 963 |
def test_download_file_incomplete_read( |
| 964 |
tmp_path_factory: pytest.TempPathFactory, |
| 965 |
monkeypatch: pytest.MonkeyPatch |
| 966 |
) -> None: |
| 967 |
temp_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections')) |
| 968 |
|
| 969 |
incomplete_data = b"\x00\x01\x02\x03" |
| 970 |
data = incomplete_data + b"\x04" |
| 971 |
sha256_hash = sha256(data) |
| 972 |
|
| 973 |
# Test retries succeed |
| 974 |
responses = [(incomplete_data, len(data)), (data, len(data))] |
| 975 |
mock_open = MagicMock(return_value=MockHTTPResponses(responses)) |
| 976 |
monkeypatch.setattr(collection.concrete_artifact_manager, 'open_url', mock_open) |
| 977 |
|
| 978 |
collection._download_file('http://google.com/file', temp_dir, sha256_hash.hexdigest(), True) |
| 979 |
|
| 980 |
# Test error is correct |
| 981 |
mock_open.return_value = MockHTTPResponses([(data, len(data) + 1)]) |
| 982 |
monkeypatch.setattr(collection.concrete_artifact_manager, 'open_url', mock_open) |
| 983 |
|
| 984 |
expected_error = re.escape( |
| 985 |
"Downloading http://google.com/file failed: " |
| 986 |
"IncompleteRead(5 bytes read, 1 more expected)" |
| 987 |
) |
| 988 |
with pytest.raises(AnsibleError, match=expected_error): |
| 989 |
collection._download_file('http://google.com/file', temp_dir, sha256_hash.hexdigest(), True) |
| 990 |
|
| 991 |
|
| 992 |
def test_extract_tar_file_invalid_hash(tmp_tarfile): |
| 993 |
temp_dir, tfile, filename, dummy = tmp_tarfile |
| 994 |
|
| 995 |
expected = "Checksum mismatch for '%s' inside collection at '%s'" % (to_native(filename), to_native(tfile.name)) |
| 996 |
with pytest.raises(AnsibleError, match=expected): |
| 997 |
collection._extract_tar_file(tfile, filename, temp_dir, temp_dir, "fakehash") |
| 998 |
|
| 999 |
|
| 1000 |
def test_extract_tar_file_missing_member(tmp_tarfile): |
| 1001 |
temp_dir, tfile, dummy, dummy = tmp_tarfile |
| 1002 |
|
| 1003 |
expected = "Collection tar at '%s' does not contain the expected file 'missing'." % to_native(tfile.name) |
| 1004 |
with pytest.raises(AnsibleError, match=expected): |
| 1005 |
collection._extract_tar_file(tfile, 'missing', temp_dir, temp_dir) |
| 1006 |
|
| 1007 |
|
| 1008 |
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): |
| 1009 |
temp_dir, tfile, filename, checksum = tmp_tarfile |
| 1010 |
output_dir = os.path.join(temp_dir, b'output') |
| 1011 |
output_file = os.path.join(output_dir, to_bytes(filename)) |
| 1012 |
|
| 1013 |
collection._extract_tar_file(tfile, filename, output_dir, temp_dir, checksum) |
| 1014 |
os.path.isfile(output_file) |
| 1015 |
|
| 1016 |
|
| 1017 |
def test_extract_tar_file_outside_dir(tmp_path_factory): |
| 1018 |
filename = u'ÅÑŚÌβŁÈ' |
| 1019 |
temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Collections' % to_native(filename))) |
| 1020 |
tar_file = os.path.join(temp_dir, to_bytes('%s.tar.gz' % filename)) |
| 1021 |
data = os.urandom(8) |
| 1022 |
|
| 1023 |
tar_filename = '../%s.sh' % filename |
| 1024 |
with tarfile.open(tar_file, 'w:gz') as tfile: |
| 1025 |
b_io = BytesIO(data) |
| 1026 |
tar_info = tarfile.TarInfo(tar_filename) |
| 1027 |
tar_info.size = len(data) |
| 1028 |
tar_info.mode = S_IRWU_RG_RO |
| 1029 |
tfile.addfile(tarinfo=tar_info, fileobj=b_io) |
| 1030 |
|
| 1031 |
expected = re.escape("Cannot extract tar entry '%s' as it will be placed outside the collection directory" |
| 1032 |
% to_native(tar_filename)) |
| 1033 |
with tarfile.open(tar_file, 'r') as tfile: |
| 1034 |
with pytest.raises(AnsibleError, match=expected): |
| 1035 |
collection._extract_tar_file(tfile, tar_filename, os.path.join(temp_dir, to_bytes(filename)), temp_dir) |
| 1036 |
|
| 1037 |
|
| 1038 |
def test_require_one_of_collections_requirements_with_both(): |
| 1039 |
cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'verify', 'namespace.collection', '-r', 'requirements.yml']) |
| 1040 |
|
| 1041 |
with pytest.raises(AnsibleError) as req_err: |
| 1042 |
cli._require_one_of_collections_requirements(('namespace.collection',), 'requirements.yml') |
| 1043 |
|
| 1044 |
with pytest.raises(AnsibleError) as cli_err: |
| 1045 |
cli.run() |
| 1046 |
|
| 1047 |
assert req_err.value.message == cli_err.value.message == 'The positional collection_name arg and --requirements-file are mutually exclusive.' |
| 1048 |
|
| 1049 |
|
| 1050 |
def test_require_one_of_collections_requirements_with_neither(): |
| 1051 |
cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'verify']) |
| 1052 |
|
| 1053 |
with pytest.raises(AnsibleError) as req_err: |
| 1054 |
cli._require_one_of_collections_requirements((), '') |
| 1055 |
|
| 1056 |
with pytest.raises(AnsibleError) as cli_err: |
| 1057 |
cli.run() |
| 1058 |
|
| 1059 |
assert req_err.value.message == cli_err.value.message == 'You must specify a collection name or a requirements file.' |
| 1060 |
|
| 1061 |
|
| 1062 |
def test_require_one_of_collections_requirements_with_collections(): |
| 1063 |
cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'verify', 'namespace1.collection1', 'namespace2.collection1:1.0.0']) |
| 1064 |
collections = ('namespace1.collection1', 'namespace2.collection1:1.0.0',) |
| 1065 |
|
| 1066 |
requirements = cli._require_one_of_collections_requirements(collections, '')['collections'] |
| 1067 |
|
| 1068 |
req_tuples = [('%s.%s' % (req.namespace, req.name), req.ver, req.src, req.type,) for req in requirements] |
| 1069 |
assert req_tuples == [('namespace1.collection1', '*', None, 'galaxy'), ('namespace2.collection1', '1.0.0', None, 'galaxy')] |
| 1070 |
|
| 1071 |
|
| 1072 |
@patch('ansible.cli.galaxy.GalaxyCLI._parse_requirements_file') |
| 1073 |
def test_require_one_of_collections_requirements_with_requirements(mock_parse_requirements_file, galaxy_server): |
| 1074 |
cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'verify', '-r', 'requirements.yml', 'namespace.collection']) |
| 1075 |
mock_parse_requirements_file.return_value = {'collections': [('namespace.collection', '1.0.5', galaxy_server)]} |
| 1076 |
requirements = cli._require_one_of_collections_requirements((), 'requirements.yml')['collections'] |
| 1077 |
|
| 1078 |
assert mock_parse_requirements_file.call_count == 1 |
| 1079 |
assert requirements == [('namespace.collection', '1.0.5', galaxy_server)] |
| 1080 |
|
| 1081 |
|
| 1082 |
@patch('ansible.cli.galaxy.GalaxyCLI.execute_verify', spec=True) |
| 1083 |
def test_call_GalaxyCLI(execute_verify): |
| 1084 |
galaxy_args = ['ansible-galaxy', 'collection', 'verify', 'namespace.collection'] |
| 1085 |
|
| 1086 |
GalaxyCLI(args=galaxy_args).run() |
| 1087 |
|
| 1088 |
assert execute_verify.call_count == 1 |
| 1089 |
|
| 1090 |
|
| 1091 |
@patch('ansible.cli.galaxy.GalaxyCLI.execute_verify') |
| 1092 |
def test_call_GalaxyCLI_with_implicit_role(execute_verify): |
| 1093 |
galaxy_args = ['ansible-galaxy', 'verify', 'namespace.implicit_role'] |
| 1094 |
|
| 1095 |
with pytest.raises(SystemExit): |
| 1096 |
GalaxyCLI(args=galaxy_args).run() |
| 1097 |
|
| 1098 |
assert not execute_verify.called |
| 1099 |
|
| 1100 |
|
| 1101 |
@patch('ansible.cli.galaxy.GalaxyCLI.execute_verify') |
| 1102 |
def test_call_GalaxyCLI_with_role(execute_verify): |
| 1103 |
galaxy_args = ['ansible-galaxy', 'role', 'verify', 'namespace.role'] |
| 1104 |
|
| 1105 |
with pytest.raises(SystemExit): |
| 1106 |
GalaxyCLI(args=galaxy_args).run() |
| 1107 |
|
| 1108 |
assert not execute_verify.called |
| 1109 |
|
| 1110 |
|
| 1111 |
@patch('ansible.cli.galaxy.verify_collections', spec=True) |
| 1112 |
def test_execute_verify_with_defaults(mock_verify_collections): |
| 1113 |
galaxy_args = ['ansible-galaxy', 'collection', 'verify', 'namespace.collection:1.0.4'] |
| 1114 |
GalaxyCLI(args=galaxy_args).run() |
| 1115 |
|
| 1116 |
assert mock_verify_collections.call_count == 1 |
| 1117 |
|
| 1118 |
print("Call args {0}".format(mock_verify_collections.call_args[0])) |
| 1119 |
requirements, search_paths, galaxy_apis, ignore_errors = mock_verify_collections.call_args[0] |
| 1120 |
|
| 1121 |
assert [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type) for r in requirements] == [('namespace.collection', '1.0.4', None, 'galaxy')] |
| 1122 |
for install_path in search_paths: |
| 1123 |
assert install_path.endswith('ansible_collections') |
| 1124 |
assert galaxy_apis[0].api_server == 'https://galaxy.ansible.com' |
| 1125 |
assert ignore_errors is False |
| 1126 |
|
| 1127 |
|
| 1128 |
@patch('ansible.cli.galaxy.verify_collections', spec=True) |
| 1129 |
def test_execute_verify(mock_verify_collections): |
| 1130 |
GalaxyCLI(args=[ |
| 1131 |
'ansible-galaxy', 'collection', 'verify', 'namespace.collection:1.0.4', '--ignore-certs', |
| 1132 |
'-p', '~/.ansible', '--ignore-errors', '--server', 'http://galaxy-dev.com', |
| 1133 |
]).run() |
| 1134 |
|
| 1135 |
assert mock_verify_collections.call_count == 1 |
| 1136 |
|
| 1137 |
requirements, search_paths, galaxy_apis, ignore_errors = mock_verify_collections.call_args[0] |
| 1138 |
|
| 1139 |
assert [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type) for r in requirements] == [('namespace.collection', '1.0.4', None, 'galaxy')] |
| 1140 |
for install_path in search_paths: |
| 1141 |
assert install_path.endswith('ansible_collections') |
| 1142 |
assert galaxy_apis[0].api_server == 'http://galaxy-dev.com' |
| 1143 |
assert ignore_errors is True |
| 1144 |
|
| 1145 |
|
| 1146 |
def test_verify_file_hash_deleted_file(manifest_info): |
| 1147 |
data = to_bytes(json.dumps(manifest_info)) |
| 1148 |
digest = sha256(data).hexdigest() |
| 1149 |
|
| 1150 |
namespace = manifest_info['collection_info']['namespace'] |
| 1151 |
name = manifest_info['collection_info']['name'] |
| 1152 |
version = manifest_info['collection_info']['version'] |
| 1153 |
server = 'http://galaxy.ansible.com' |
| 1154 |
|
| 1155 |
error_queue = [] |
| 1156 |
|
| 1157 |
with patch.object(builtins, 'open', mock_open(read_data=data)) as m: |
| 1158 |
with patch.object(collection.os.path, 'isfile', MagicMock(return_value=False)) as mock_isfile: |
| 1159 |
collection._verify_file_hash(b'path/', 'file', digest, error_queue) |
| 1160 |
|
| 1161 |
mock_isfile.assert_called_once() |
| 1162 |
|
| 1163 |
assert len(error_queue) == 1 |
| 1164 |
assert error_queue[0].installed is None |
| 1165 |
assert error_queue[0].expected == digest |
| 1166 |
|
| 1167 |
|
| 1168 |
def test_verify_file_hash_matching_hash(manifest_info): |
| 1169 |
|
| 1170 |
data = to_bytes(json.dumps(manifest_info)) |
| 1171 |
digest = sha256(data).hexdigest() |
| 1172 |
|
| 1173 |
namespace = manifest_info['collection_info']['namespace'] |
| 1174 |
name = manifest_info['collection_info']['name'] |
| 1175 |
version = manifest_info['collection_info']['version'] |
| 1176 |
server = 'http://galaxy.ansible.com' |
| 1177 |
|
| 1178 |
error_queue = [] |
| 1179 |
|
| 1180 |
with patch.object(builtins, 'open', mock_open(read_data=data)) as m: |
| 1181 |
with patch.object(collection.os.path, 'isfile', MagicMock(return_value=True)) as mock_isfile: |
| 1182 |
collection._verify_file_hash(b'path/', 'file', digest, error_queue) |
| 1183 |
|
| 1184 |
mock_isfile.assert_called_once() |
| 1185 |
|
| 1186 |
assert error_queue == [] |
| 1187 |
|
| 1188 |
|
| 1189 |
def test_verify_file_hash_mismatching_hash(manifest_info): |
| 1190 |
|
| 1191 |
data = to_bytes(json.dumps(manifest_info)) |
| 1192 |
digest = sha256(data).hexdigest() |
| 1193 |
different_digest = 'not_{0}'.format(digest) |
| 1194 |
|
| 1195 |
namespace = manifest_info['collection_info']['namespace'] |
| 1196 |
name = manifest_info['collection_info']['name'] |
| 1197 |
version = manifest_info['collection_info']['version'] |
| 1198 |
server = 'http://galaxy.ansible.com' |
| 1199 |
|
| 1200 |
error_queue = [] |
| 1201 |
|
| 1202 |
with patch.object(builtins, 'open', mock_open(read_data=data)) as m: |
| 1203 |
with patch.object(collection.os.path, 'isfile', MagicMock(return_value=True)) as mock_isfile: |
| 1204 |
collection._verify_file_hash(b'path/', 'file', different_digest, error_queue) |
| 1205 |
|
| 1206 |
mock_isfile.assert_called_once() |
| 1207 |
|
| 1208 |
assert len(error_queue) == 1 |
| 1209 |
assert error_queue[0].installed == digest |
| 1210 |
assert error_queue[0].expected == different_digest |
| 1211 |
|
| 1212 |
|
| 1213 |
def test_consume_file(manifest): |
| 1214 |
|
| 1215 |
manifest_file, checksum = manifest |
| 1216 |
assert checksum == collection._consume_file(manifest_file) |
| 1217 |
|
| 1218 |
|
| 1219 |
def test_consume_file_and_write_contents(manifest, manifest_info): |
| 1220 |
|
| 1221 |
manifest_file, checksum = manifest |
| 1222 |
|
| 1223 |
write_to = BytesIO() |
| 1224 |
actual_hash = collection._consume_file(manifest_file, write_to) |
| 1225 |
|
| 1226 |
write_to.seek(0) |
| 1227 |
assert to_bytes(json.dumps(manifest_info)) == write_to.read() |
| 1228 |
assert actual_hash == checksum |
| 1229 |
|
| 1230 |
|
| 1231 |
def test_get_tar_file_member(tmp_tarfile): |
| 1232 |
|
| 1233 |
temp_dir, tfile, filename, checksum = tmp_tarfile |
| 1234 |
|
| 1235 |
with collection._get_tar_file_member(tfile, filename) as (tar_file_member, tar_file_obj): |
| 1236 |
assert isinstance(tar_file_member, tarfile.TarInfo) |
| 1237 |
assert isinstance(tar_file_obj, tarfile.ExFileObject) |
| 1238 |
|
| 1239 |
|
| 1240 |
def test_get_nonexistent_tar_file_member(tmp_tarfile): |
| 1241 |
temp_dir, tfile, filename, checksum = tmp_tarfile |
| 1242 |
|
| 1243 |
file_does_not_exist = filename + 'nonexistent' |
| 1244 |
|
| 1245 |
with pytest.raises(AnsibleError) as err: |
| 1246 |
collection._get_tar_file_member(tfile, file_does_not_exist) |
| 1247 |
|
| 1248 |
assert to_text(err.value.message) == "Collection tar at '%s' does not contain the expected file '%s'." % (to_text(tfile.name), file_does_not_exist) |
| 1249 |
|
| 1250 |
|
| 1251 |
def test_get_tar_file_hash(tmp_tarfile): |
| 1252 |
temp_dir, tfile, filename, checksum = tmp_tarfile |
| 1253 |
|
| 1254 |
assert checksum == collection._get_tar_file_hash(tfile.name, filename) |
| 1255 |
|
| 1256 |
|
| 1257 |
def test_get_json_from_tar_file(tmp_tarfile): |
| 1258 |
temp_dir, tfile, filename, checksum = tmp_tarfile |
| 1259 |
|
| 1260 |
assert 'MANIFEST.json' in tfile.getnames() |
| 1261 |
|
| 1262 |
data = collection._get_json_from_tar_file(tfile.name, 'MANIFEST.json') |
| 1263 |
|
| 1264 |
assert isinstance(data, dict) |