Debian Codegraph @

test/units/galaxy/test_collection_install.py

raw
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 copy
8 import json
9 import os
10 import pytest
11 import re
12 import shutil
13 import stat
14 import tarfile
15 import yaml
16
17 from io import BytesIO, StringIO
18 from unittest.mock import MagicMock, patch
19
20 import urllib.error
21
22 from ansible import context
23 from ansible.cli.galaxy import GalaxyCLI
24 from ansible.errors import AnsibleError
25 from ansible.galaxy import collection, api, dependency_resolution
26 from ansible.galaxy.dependency_resolution.dataclasses import Candidate, Requirement
27 from ansible.module_utils.common.file import S_IRWU_RG_RO, S_IRWXU_RXG_RXO
28 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
29 from ansible.module_utils.common.process import get_bin_path
30 from ansible.utils import context_objects as co
31 from ansible.utils.display import Display
32
33 import ansible.constants as C
34
35
36 class RequirementCandidates():
37 def __init__(self):
38 self.candidates = []
39
40 def func_wrapper(self, func):
41 def run(*args, **kwargs):
42 self.candidates = func(*args, **kwargs)
43 return self.candidates
44 return run
45
46
47 def call_galaxy_cli(args):
48 orig = co.GlobalCLIArgs._Singleton__instance
49 co.GlobalCLIArgs._Singleton__instance = None
50 try:
51 GalaxyCLI(args=['ansible-galaxy', 'collection'] + args).run()
52 finally:
53 co.GlobalCLIArgs._Singleton__instance = orig
54
55
56 @pytest.fixture(autouse=True)
57 def reset_cli_args():
58 co.GlobalCLIArgs._Singleton__instance = None
59 yield
60 co.GlobalCLIArgs._Singleton__instance = None
61
62
63 @pytest.fixture()
64 def collection_artifact(request, tmp_path_factory):
65 test_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
66 namespace = 'ansible_namespace'
67 collection = 'collection'
68
69 skeleton_path = os.path.join(os.path.dirname(os.path.split(__file__)[0]), 'cli', 'test_data', 'collection_skeleton')
70 collection_path = os.path.join(test_dir, namespace, collection)
71
72 call_galaxy_cli(['init', '%s.%s' % (namespace, collection), '-c', '--init-path', test_dir,
73 '--collection-skeleton', skeleton_path])
74 dependencies = getattr(request, 'param', {})
75
76 galaxy_yml = os.path.join(collection_path, 'galaxy.yml')
77 with open(galaxy_yml, 'rb+') as galaxy_obj:
78 existing_yaml = yaml.safe_load(galaxy_obj)
79 existing_yaml['dependencies'] = dependencies
80
81 galaxy_obj.seek(0)
82 galaxy_obj.write(to_bytes(yaml.safe_dump(existing_yaml)))
83 galaxy_obj.truncate()
84
85 # Create a file with +x in the collection so we can test the permissions
86 execute_path = os.path.join(collection_path, 'runme.sh')
87 with open(execute_path, mode='wb') as fd:
88 fd.write(b"echo hi")
89 os.chmod(execute_path, os.stat(execute_path).st_mode | stat.S_IEXEC)
90
91 call_galaxy_cli(['build', collection_path, '--output-path', test_dir])
92
93 collection_tar = os.path.join(test_dir, '%s-%s-0.1.0.tar.gz' % (namespace, collection))
94 return to_bytes(collection_path), to_bytes(collection_tar)
95
96
97 @pytest.fixture()
98 def galaxy_server():
99 context.CLIARGS._store = {'ignore_certs': False}
100 galaxy_api = api.GalaxyAPI(None, 'test_server', 'https://galaxy.ansible.com')
101 galaxy_api.get_collection_signatures = MagicMock(return_value=[])
102 return galaxy_api
103
104
105 def test_concrete_artifact_manager_scm_no_executable(monkeypatch):
106 url = 'https://github.com/org/repo'
107 version = 'commitish'
108 mock_subprocess_check_call = MagicMock()
109 monkeypatch.setattr(collection.concrete_artifact_manager.subprocess, 'check_call', mock_subprocess_check_call)
110 mock_mkdtemp = MagicMock(return_value='')
111 monkeypatch.setattr(collection.concrete_artifact_manager, 'mkdtemp', mock_mkdtemp)
112 mock_get_bin_path = MagicMock(side_effect=[ValueError('Failed to find required executable')])
113 monkeypatch.setattr(collection.concrete_artifact_manager, 'get_bin_path', mock_get_bin_path)
114
115 error = re.escape(
116 "Could not find git executable to extract the collection from the Git repository `https://github.com/org/repo`"
117 )
118 with pytest.raises(AnsibleError, match=error):
119 collection.concrete_artifact_manager._extract_collection_from_git(url, version, b'path')
120
121
122 @pytest.mark.parametrize(
123 'url,version,trailing_slash',
124 [
125 ('https://github.com/org/repo', 'commitish', False),
126 ('https://github.com/org/repo,commitish', None, False),
127 ('https://github.com/org/repo/,commitish', None, True),
128 ('https://github.com/org/repo#,commitish', None, False),
129 ]
130 )
131 def test_concrete_artifact_manager_scm_cmd(url, version, trailing_slash, monkeypatch):
132 context.CLIARGS._store = {'ignore_certs': False}
133 mock_subprocess_check_call = MagicMock()
134 monkeypatch.setattr(collection.concrete_artifact_manager.subprocess, 'check_call', mock_subprocess_check_call)
135 mock_mkdtemp = MagicMock(return_value='')
136 monkeypatch.setattr(collection.concrete_artifact_manager, 'mkdtemp', mock_mkdtemp)
137
138 collection.concrete_artifact_manager._extract_collection_from_git(url, version, b'path')
139
140 assert mock_subprocess_check_call.call_count == 2
141
142 repo = 'https://github.com/org/repo'
143 if trailing_slash:
144 repo += '/'
145
146 git_executable = get_bin_path('git')
147 clone_cmd = [git_executable, 'clone', repo, '']
148
149 assert mock_subprocess_check_call.call_args_list[0].args[0] == clone_cmd
150 assert mock_subprocess_check_call.call_args_list[1].args[0] == (git_executable, '-c', 'advice.detachedHead=false', 'checkout', 'commitish')
151
152
153 @pytest.mark.parametrize(
154 'url,version,trailing_slash',
155 [
156 ('https://github.com/org/repo', 'HEAD', False),
157 ('https://github.com/org/repo,HEAD', None, False),
158 ('https://github.com/org/repo/,HEAD', None, True),
159 ('https://github.com/org/repo#,HEAD', None, False),
160 ('https://github.com/org/repo', None, False),
161 ]
162 )
163 def test_concrete_artifact_manager_scm_cmd_shallow(url, version, trailing_slash, monkeypatch):
164 context.CLIARGS._store = {'ignore_certs': False}
165 mock_subprocess_check_call = MagicMock()
166 monkeypatch.setattr(collection.concrete_artifact_manager.subprocess, 'check_call', mock_subprocess_check_call)
167 mock_mkdtemp = MagicMock(return_value='')
168 monkeypatch.setattr(collection.concrete_artifact_manager, 'mkdtemp', mock_mkdtemp)
169
170 collection.concrete_artifact_manager._extract_collection_from_git(url, version, b'path')
171
172 assert mock_subprocess_check_call.call_count == 2
173
174 repo = 'https://github.com/org/repo'
175 if trailing_slash:
176 repo += '/'
177 git_executable = get_bin_path('git')
178 shallow_clone_cmd = [git_executable, 'clone', '--depth=1', repo, '']
179
180 assert mock_subprocess_check_call.call_args_list[0].args[0] == shallow_clone_cmd
181 assert mock_subprocess_check_call.call_args_list[1].args[0] == (git_executable, 'checkout', 'HEAD')
182
183
184 @pytest.mark.parametrize(
185 'ignore_certs_cli,ignore_certs_config,expected_ignore_certs',
186 [
187 (False, False, False),
188 (False, True, True),
189 (True, False, True),
190 ]
191 )
192 def test_concrete_artifact_manager_scm_cmd_validate_certs(ignore_certs_cli, ignore_certs_config, expected_ignore_certs, monkeypatch):
193 context.CLIARGS._store = {'ignore_certs': ignore_certs_cli}
194 monkeypatch.setattr(C, 'GALAXY_IGNORE_CERTS', ignore_certs_config)
195
196 mock_subprocess_check_call = MagicMock()
197 monkeypatch.setattr(collection.concrete_artifact_manager.subprocess, 'check_call', mock_subprocess_check_call)
198 mock_mkdtemp = MagicMock(return_value='')
199 monkeypatch.setattr(collection.concrete_artifact_manager, 'mkdtemp', mock_mkdtemp)
200
201 url = 'https://github.com/org/repo'
202 version = 'HEAD'
203 collection.concrete_artifact_manager._extract_collection_from_git(url, version, b'path')
204
205 assert mock_subprocess_check_call.call_count == 2
206
207 git_executable = get_bin_path('git')
208 clone_cmd = [git_executable, 'clone', '--depth=1', url, '']
209 if expected_ignore_certs:
210 clone_cmd.extend(['-c', 'http.sslVerify=false'])
211
212 assert mock_subprocess_check_call.call_args_list[0].args[0] == clone_cmd
213 assert mock_subprocess_check_call.call_args_list[1].args[0] == (git_executable, 'checkout', 'HEAD')
214
215
216 def test_build_requirement_from_path(collection_artifact):
217 tmp_path = os.path.join(os.path.split(collection_artifact[1])[0], b'temp')
218 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(tmp_path, validate_certs=False)
219 actual = Requirement.from_dir_path_as_unknown(collection_artifact[0], concrete_artifact_cm)
220
221 assert actual.namespace == u'ansible_namespace'
222 assert actual.name == u'collection'
223 assert actual.src == collection_artifact[0]
224 assert actual.ver == u'0.1.0'
225
226
227 @pytest.mark.parametrize('version', ['1.1.1', '1.1.0', '1.0.0'])
228 def test_build_requirement_from_path_with_manifest(version, collection_artifact):
229 manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
230 manifest_value = json.dumps({
231 'collection_info': {
232 'namespace': 'namespace',
233 'name': 'name',
234 'version': version,
235 'dependencies': {
236 'ansible_namespace.collection': '*'
237 }
238 }
239 })
240 with open(manifest_path, 'wb') as manifest_obj:
241 manifest_obj.write(to_bytes(manifest_value))
242
243 tmp_path = os.path.join(os.path.split(collection_artifact[1])[0], b'temp')
244 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(tmp_path, validate_certs=False)
245 actual = Requirement.from_dir_path_as_unknown(collection_artifact[0], concrete_artifact_cm)
246
247 # While the folder name suggests a different collection, we treat MANIFEST.json as the source of truth.
248 assert actual.namespace == u'namespace'
249 assert actual.name == u'name'
250 assert actual.src == collection_artifact[0]
251 assert actual.ver == to_text(version)
252
253
254 def test_build_requirement_from_path_invalid_manifest(collection_artifact):
255 manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
256 with open(manifest_path, 'wb') as manifest_obj:
257 manifest_obj.write(b"not json")
258
259 tmp_path = os.path.join(os.path.split(collection_artifact[1])[0], b'temp')
260 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(tmp_path, validate_certs=False)
261
262 expected = "Collection tar file member MANIFEST.json does not contain a valid json string."
263 with pytest.raises(AnsibleError, match=expected):
264 Requirement.from_dir_path_as_unknown(collection_artifact[0], concrete_artifact_cm)
265
266
267 def test_build_artifact_from_path_no_version(collection_artifact, monkeypatch):
268 mock_display = MagicMock()
269 monkeypatch.setattr(Display, 'display', mock_display)
270
271 # a collection artifact should always contain a valid version
272 manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json')
273 manifest_value = json.dumps({
274 'collection_info': {
275 'namespace': 'namespace',
276 'name': 'name',
277 'version': '',
278 'dependencies': {}
279 }
280 })
281 with open(manifest_path, 'wb') as manifest_obj:
282 manifest_obj.write(to_bytes(manifest_value))
283
284 tmp_path = os.path.join(os.path.split(collection_artifact[1])[0], b'temp')
285 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(tmp_path, validate_certs=False)
286
287 expected = (
288 '^Collection metadata file `.*` at `.*` is expected to have a valid SemVer '
289 'version value but got {empty_unicode_string!r}$'.
290 format(empty_unicode_string=u'')
291 )
292 with pytest.raises(AnsibleError, match=expected):
293 Requirement.from_dir_path_as_unknown(collection_artifact[0], concrete_artifact_cm)
294
295
296 def test_build_requirement_from_path_no_version(collection_artifact, monkeypatch):
297 mock_display = MagicMock()
298 monkeypatch.setattr(Display, 'display', mock_display)
299
300 # version may be falsey/arbitrary strings for collections in development
301 manifest_path = os.path.join(collection_artifact[0], b'galaxy.yml')
302 metadata = {
303 'authors': ['Ansible'],
304 'readme': 'README.md',
305 'namespace': 'namespace',
306 'name': 'name',
307 'version': '',
308 'dependencies': {},
309 }
310 with open(manifest_path, 'wb') as manifest_obj:
311 manifest_obj.write(to_bytes(yaml.safe_dump(metadata)))
312
313 tmp_path = os.path.join(os.path.split(collection_artifact[1])[0], b'temp')
314 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(tmp_path, validate_certs=False)
315 actual = Requirement.from_dir_path_as_unknown(collection_artifact[0], concrete_artifact_cm)
316
317 # While the folder name suggests a different collection, we treat MANIFEST.json as the source of truth.
318 assert actual.namespace == u'namespace'
319 assert actual.name == u'name'
320 assert actual.src == collection_artifact[0]
321 assert actual.ver == u'*'
322
323
324 def test_build_requirement_from_tar(collection_artifact):
325 tmp_path = os.path.join(os.path.split(collection_artifact[1])[0], b'temp')
326 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(tmp_path, validate_certs=False)
327
328 actual = Requirement.from_requirement_dict({'name': to_text(collection_artifact[1])}, concrete_artifact_cm)
329
330 assert actual.namespace == u'ansible_namespace'
331 assert actual.name == u'collection'
332 assert actual.src == to_text(collection_artifact[1])
333 assert actual.ver == u'0.1.0'
334
335
336 def test_build_requirement_from_tar_url(tmp_path_factory):
337 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
338 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
339 test_url = 'https://example.com/org/repo/sample.tar.gz'
340 expected = fr"^Failed to download collection tar from '{to_text(test_url)}'"
341
342 with pytest.raises(AnsibleError, match=expected):
343 Requirement.from_requirement_dict({'name': test_url, 'type': 'url'}, concrete_artifact_cm)
344
345
346 def test_build_requirement_from_tar_url_wrong_type(tmp_path_factory):
347 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
348 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
349 test_url = 'https://example.com/org/repo/sample.tar.gz'
350 expected = fr"^Unable to find collection artifact file at '{to_text(test_url)}'\.$"
351
352 with pytest.raises(AnsibleError, match=expected):
353 # Specified wrong collection type for http URL
354 Requirement.from_requirement_dict({'name': test_url, 'type': 'file'}, concrete_artifact_cm)
355
356
357 def test_build_requirement_from_tar_fail_not_tar(tmp_path_factory):
358 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
359 test_file = os.path.join(test_dir, b'fake.tar.gz')
360 with open(test_file, 'wb') as test_obj:
361 test_obj.write(b"\x00\x01\x02\x03")
362
363 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
364
365 expected = "Collection artifact at '%s' is not a valid tar file." % to_native(test_file)
366 with pytest.raises(AnsibleError, match=expected):
367 Requirement.from_requirement_dict({'name': to_text(test_file)}, concrete_artifact_cm)
368
369
370 def test_build_requirement_from_tar_no_manifest(tmp_path_factory):
371 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
372
373 json_data = to_bytes(json.dumps(
374 {
375 'files': [],
376 'format': 1,
377 }
378 ))
379
380 tar_path = os.path.join(test_dir, b'ansible-collections.tar.gz')
381 with tarfile.open(tar_path, 'w:gz') as tfile:
382 b_io = BytesIO(json_data)
383 tar_info = tarfile.TarInfo('FILES.json')
384 tar_info.size = len(json_data)
385 tar_info.mode = S_IRWU_RG_RO
386 tfile.addfile(tarinfo=tar_info, fileobj=b_io)
387
388 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
389
390 expected = "Collection at '%s' does not contain the required file MANIFEST.json." % to_native(tar_path)
391 with pytest.raises(AnsibleError, match=expected):
392 Requirement.from_requirement_dict({'name': to_text(tar_path)}, concrete_artifact_cm)
393
394
395 def test_build_requirement_from_tar_no_files(tmp_path_factory):
396 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
397
398 json_data = to_bytes(json.dumps(
399 {
400 'collection_info': {},
401 }
402 ))
403
404 tar_path = os.path.join(test_dir, b'ansible-collections.tar.gz')
405 with tarfile.open(tar_path, 'w:gz') as tfile:
406 b_io = BytesIO(json_data)
407 tar_info = tarfile.TarInfo('MANIFEST.json')
408 tar_info.size = len(json_data)
409 tar_info.mode = S_IRWU_RG_RO
410 tfile.addfile(tarinfo=tar_info, fileobj=b_io)
411
412 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
413 with pytest.raises(KeyError, match='namespace'):
414 Requirement.from_requirement_dict({'name': to_text(tar_path)}, concrete_artifact_cm)
415
416
417 def test_build_requirement_from_tar_invalid_manifest(tmp_path_factory):
418 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
419
420 json_data = b"not a json"
421
422 tar_path = os.path.join(test_dir, b'ansible-collections.tar.gz')
423 with tarfile.open(tar_path, 'w:gz') as tfile:
424 b_io = BytesIO(json_data)
425 tar_info = tarfile.TarInfo('MANIFEST.json')
426 tar_info.size = len(json_data)
427 tar_info.mode = S_IRWU_RG_RO
428 tfile.addfile(tarinfo=tar_info, fileobj=b_io)
429
430 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
431
432 expected = "Collection tar file member MANIFEST.json does not contain a valid json string."
433 with pytest.raises(AnsibleError, match=expected):
434 Requirement.from_requirement_dict({'name': to_text(tar_path)}, concrete_artifact_cm)
435
436
437 def test_build_requirement_from_name(galaxy_server, monkeypatch, tmp_path_factory):
438 mock_get_versions = MagicMock()
439 mock_get_versions.return_value = ['2.1.9', '2.1.10']
440 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
441
442 mock_version_metadata = MagicMock(
443 namespace='namespace', name='collection',
444 version='2.1.10', artifact_sha256='', dependencies={}
445 )
446 monkeypatch.setattr(api.GalaxyAPI, 'get_collection_version_metadata', mock_version_metadata)
447
448 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
449 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
450
451 collections = ['namespace.collection']
452 requirements_file = None
453
454 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', collections[0]])
455 requirements = cli._require_one_of_collections_requirements(
456 collections, requirements_file, artifacts_manager=concrete_artifact_cm
457 )['collections']
458 actual = collection._resolve_depenency_map(
459 requirements, [galaxy_server], concrete_artifact_cm, None, True, False, False, False, False
460 )['namespace.collection']
461
462 assert actual.namespace == u'namespace'
463 assert actual.name == u'collection'
464 assert actual.ver == u'2.1.10'
465 assert actual.src == galaxy_server
466
467 assert mock_get_versions.call_count == 1
468 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection')
469
470
471 def test_build_requirement_from_name_with_prerelease(galaxy_server, monkeypatch, tmp_path_factory):
472 mock_get_versions = MagicMock()
473 mock_get_versions.return_value = ['1.0.1', '2.0.1-beta.1', '2.0.1']
474 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
475
476 mock_get_info = MagicMock()
477 mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '2.0.1', None, None, {}, None, None)
478 monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info)
479
480 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
481 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
482
483 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection'])
484 requirements = cli._require_one_of_collections_requirements(
485 ['namespace.collection'], None, artifacts_manager=concrete_artifact_cm
486 )['collections']
487 actual = collection._resolve_depenency_map(
488 requirements, [galaxy_server], concrete_artifact_cm, None, True, False, False, False, False
489 )['namespace.collection']
490
491 assert actual.namespace == u'namespace'
492 assert actual.name == u'collection'
493 assert actual.src == galaxy_server
494 assert actual.ver == u'2.0.1'
495
496 assert mock_get_versions.call_count == 1
497 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection')
498
499
500 def test_build_requirement_from_name_with_prerelease_explicit(galaxy_server, monkeypatch, tmp_path_factory):
501 mock_get_versions = MagicMock()
502 mock_get_versions.return_value = ['1.0.1', '2.0.1-beta.1', '2.0.1']
503 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
504
505 mock_get_info = MagicMock()
506 mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '2.0.1-beta.1', None, None,
507 {}, None, None)
508 monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info)
509
510 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
511 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
512
513 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection:2.0.1-beta.1'])
514 requirements = cli._require_one_of_collections_requirements(
515 ['namespace.collection:2.0.1-beta.1'], None, artifacts_manager=concrete_artifact_cm
516 )['collections']
517 actual = collection._resolve_depenency_map(
518 requirements, [galaxy_server], concrete_artifact_cm, None, True, False, False, False, False
519 )['namespace.collection']
520
521 assert actual.namespace == u'namespace'
522 assert actual.name == u'collection'
523 assert actual.src == galaxy_server
524 assert actual.ver == u'2.0.1-beta.1'
525
526 assert mock_get_info.call_count == 1
527 assert mock_get_info.mock_calls[0][1] == ('namespace', 'collection', '2.0.1-beta.1')
528
529
530 def test_build_requirement_from_name_second_server(galaxy_server, monkeypatch, tmp_path_factory):
531 mock_get_versions = MagicMock()
532 mock_get_versions.return_value = ['1.0.1', '1.0.2', '1.0.3']
533 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
534
535 mock_get_info = MagicMock()
536 mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '1.0.3', None, None, {}, None, None)
537 monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info)
538
539 broken_server = copy.copy(galaxy_server)
540 broken_server.api_server = 'https://broken.com/'
541 mock_version_list = MagicMock()
542 mock_version_list.return_value = []
543 monkeypatch.setattr(broken_server, 'get_collection_versions', mock_version_list)
544
545 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
546 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
547
548 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection:>1.0.1'])
549 requirements = cli._require_one_of_collections_requirements(
550 ['namespace.collection:>1.0.1'], None, artifacts_manager=concrete_artifact_cm
551 )['collections']
552 actual = collection._resolve_depenency_map(
553 requirements, [broken_server, galaxy_server], concrete_artifact_cm, None, True, False, False, False, False
554 )['namespace.collection']
555
556 assert actual.namespace == u'namespace'
557 assert actual.name == u'collection'
558 assert actual.src == galaxy_server
559 assert actual.ver == u'1.0.3'
560
561 assert mock_version_list.call_count == 1
562 assert mock_version_list.mock_calls[0][1] == ('namespace', 'collection')
563
564 assert mock_get_versions.call_count == 1
565 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection')
566
567
568 def test_build_requirement_from_name_missing(galaxy_server, monkeypatch, tmp_path_factory):
569 mock_open = MagicMock()
570 mock_open.return_value = []
571
572 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_open)
573
574 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
575 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
576
577 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection:>1.0.1'])
578 requirements = cli._require_one_of_collections_requirements(
579 ['namespace.collection'], None, artifacts_manager=concrete_artifact_cm
580 )['collections']
581
582 expected = "Failed to resolve the requested dependencies map. Could not satisfy the following requirements:\n* namespace.collection:* (direct request)"
583 with pytest.raises(AnsibleError, match=re.escape(expected)):
584 collection._resolve_depenency_map(requirements, [galaxy_server, galaxy_server], concrete_artifact_cm, None, False, True, False, False, False)
585
586
587 def test_build_requirement_from_name_401_unauthorized(galaxy_server, monkeypatch, tmp_path_factory):
588 mock_open = MagicMock()
589 mock_open.side_effect = api.GalaxyError(urllib.error.HTTPError('https://galaxy.server.com', 401, 'msg', {},
590 StringIO()), "error")
591
592 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_open)
593
594 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
595 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
596
597 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection:>1.0.1'])
598 requirements = cli._require_one_of_collections_requirements(
599 ['namespace.collection'], None, artifacts_manager=concrete_artifact_cm
600 )['collections']
601
602 expected = "error (HTTP Code: 401, Message: msg)"
603 with pytest.raises(api.GalaxyError, match=re.escape(expected)):
604 collection._resolve_depenency_map(requirements, [galaxy_server, galaxy_server], concrete_artifact_cm, None, False, False, False, False, False)
605
606
607 def test_build_requirement_from_name_single_version(galaxy_server, monkeypatch, tmp_path_factory):
608 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
609 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
610 multi_api_proxy = collection.galaxy_api_proxy.MultiGalaxyAPIProxy([galaxy_server], concrete_artifact_cm)
611 dep_provider = dependency_resolution.providers.CollectionDependencyProvider(apis=multi_api_proxy, concrete_artifacts_manager=concrete_artifact_cm)
612
613 matches = RequirementCandidates()
614 mock_find_matches = MagicMock(side_effect=matches.func_wrapper(dep_provider.find_matches), autospec=True)
615 monkeypatch.setattr(dependency_resolution.providers.CollectionDependencyProvider, 'find_matches', mock_find_matches)
616
617 mock_get_versions = MagicMock()
618 mock_get_versions.return_value = ['2.0.0']
619 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
620
621 mock_get_info = MagicMock()
622 mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '2.0.0', None, None,
623 {}, None, None)
624 monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info)
625
626 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection:==2.0.0'])
627 requirements = cli._require_one_of_collections_requirements(
628 ['namespace.collection:==2.0.0'], None, artifacts_manager=concrete_artifact_cm
629 )['collections']
630
631 actual = collection._resolve_depenency_map(
632 requirements, [galaxy_server], concrete_artifact_cm, None, False, True, False, False, False)['namespace.collection']
633
634 assert actual.namespace == u'namespace'
635 assert actual.name == u'collection'
636 assert actual.src == galaxy_server
637 assert actual.ver == u'2.0.0'
638 assert [c.ver for c in matches.candidates] == [u'2.0.0']
639
640 assert mock_get_info.call_count == 1
641 assert mock_get_info.mock_calls[0][1] == ('namespace', 'collection', '2.0.0')
642
643
644 def test_build_requirement_from_name_multiple_versions_one_match(galaxy_server, monkeypatch, tmp_path_factory):
645 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
646 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
647 multi_api_proxy = collection.galaxy_api_proxy.MultiGalaxyAPIProxy([galaxy_server], concrete_artifact_cm)
648 dep_provider = dependency_resolution.providers.CollectionDependencyProvider(apis=multi_api_proxy, concrete_artifacts_manager=concrete_artifact_cm)
649
650 matches = RequirementCandidates()
651 mock_find_matches = MagicMock(side_effect=matches.func_wrapper(dep_provider.find_matches), autospec=True)
652 monkeypatch.setattr(dependency_resolution.providers.CollectionDependencyProvider, 'find_matches', mock_find_matches)
653
654 mock_get_versions = MagicMock()
655 mock_get_versions.return_value = ['2.0.0', '2.0.1', '2.0.2']
656 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
657
658 mock_get_info = MagicMock()
659 mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '2.0.1', None, None,
660 {}, None, None)
661 monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info)
662
663 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection:>=2.0.1,<2.0.2'])
664 requirements = cli._require_one_of_collections_requirements(
665 ['namespace.collection:>=2.0.1,<2.0.2'], None, artifacts_manager=concrete_artifact_cm
666 )['collections']
667
668 actual = collection._resolve_depenency_map(
669 requirements, [galaxy_server], concrete_artifact_cm, None, False, True, False, False, False)['namespace.collection']
670
671 assert actual.namespace == u'namespace'
672 assert actual.name == u'collection'
673 assert actual.src == galaxy_server
674 assert actual.ver == u'2.0.1'
675 assert [c.ver for c in matches.candidates] == [u'2.0.1']
676
677 assert mock_get_versions.call_count == 1
678 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection')
679
680 assert mock_get_info.call_count == 1
681 assert mock_get_info.mock_calls[0][1] == ('namespace', 'collection', '2.0.1')
682
683
684 def test_build_requirement_from_name_multiple_version_results(galaxy_server, monkeypatch, tmp_path_factory):
685 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
686 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
687 multi_api_proxy = collection.galaxy_api_proxy.MultiGalaxyAPIProxy([galaxy_server], concrete_artifact_cm)
688 dep_provider = dependency_resolution.providers.CollectionDependencyProvider(apis=multi_api_proxy, concrete_artifacts_manager=concrete_artifact_cm)
689
690 matches = RequirementCandidates()
691 mock_find_matches = MagicMock(side_effect=matches.func_wrapper(dep_provider.find_matches), autospec=True)
692 monkeypatch.setattr(dependency_resolution.providers.CollectionDependencyProvider, 'find_matches', mock_find_matches)
693
694 mock_get_info = MagicMock()
695 mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '2.0.5', None, None, {}, None, None)
696 monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info)
697
698 mock_get_versions = MagicMock()
699 mock_get_versions.return_value = ['1.0.1', '1.0.2', '1.0.3']
700 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
701
702 mock_get_versions.return_value = ['2.0.0', '2.0.1', '2.0.2', '2.0.3', '2.0.4', '2.0.5']
703 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
704
705 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection:!=2.0.2'])
706 requirements = cli._require_one_of_collections_requirements(
707 ['namespace.collection:!=2.0.2'], None, artifacts_manager=concrete_artifact_cm
708 )['collections']
709
710 actual = collection._resolve_depenency_map(
711 requirements, [galaxy_server], concrete_artifact_cm, None, False, True, False, False, False)['namespace.collection']
712
713 assert actual.namespace == u'namespace'
714 assert actual.name == u'collection'
715 assert actual.src == galaxy_server
716 assert actual.ver == u'2.0.5'
717 # should be ordered latest to earliest
718 assert [c.ver for c in matches.candidates] == [u'2.0.5', u'2.0.4', u'2.0.3', u'2.0.1', u'2.0.0']
719
720 assert mock_get_versions.call_count == 1
721 assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection')
722
723
724 def test_candidate_with_conflict(monkeypatch, tmp_path_factory, galaxy_server):
725
726 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
727 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
728
729 mock_get_info = MagicMock()
730 mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '2.0.5', None, None, {}, None, None)
731 monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info)
732
733 mock_get_versions = MagicMock()
734 mock_get_versions.return_value = ['2.0.5']
735 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
736
737 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection:!=2.0.5'])
738 requirements = cli._require_one_of_collections_requirements(
739 ['namespace.collection:!=2.0.5'], None, artifacts_manager=concrete_artifact_cm
740 )['collections']
741
742 expected = "Failed to resolve the requested dependencies map. Could not satisfy the following requirements:\n"
743 expected += "* namespace.collection:!=2.0.5 (direct request)"
744 with pytest.raises(AnsibleError, match=re.escape(expected)):
745 collection._resolve_depenency_map(requirements, [galaxy_server], concrete_artifact_cm, None, False, True, False, False, False)
746
747
748 def test_dep_candidate_with_conflict(monkeypatch, tmp_path_factory, galaxy_server):
749 test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
750 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
751
752 mock_get_info_return = [
753 api.CollectionVersionMetadata('parent', 'collection', '2.0.5', None, None, {'namespace.collection': '!=1.0.0'}, None, None),
754 api.CollectionVersionMetadata('namespace', 'collection', '1.0.0', None, None, {}, None, None),
755 ]
756 mock_get_info = MagicMock(side_effect=mock_get_info_return)
757 monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info)
758
759 mock_get_versions = MagicMock(side_effect=[['2.0.5'], ['1.0.0']])
760 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
761
762 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'parent.collection:2.0.5'])
763 requirements = cli._require_one_of_collections_requirements(
764 ['parent.collection:2.0.5'], None, artifacts_manager=concrete_artifact_cm
765 )['collections']
766
767 expected = "Failed to resolve the requested dependencies map. Could not satisfy the following requirements:\n"
768 expected += "* namespace.collection:!=1.0.0 (dependency of parent.collection:2.0.5)"
769 with pytest.raises(AnsibleError, match=re.escape(expected)):
770 collection._resolve_depenency_map(requirements, [galaxy_server], concrete_artifact_cm, None, False, True, False, False, False)
771
772
773 def test_install_installed_collection(monkeypatch, tmp_path_factory, galaxy_server):
774
775 mock_installed_collections = MagicMock(return_value=[Candidate('namespace.collection', '1.2.3', None, 'dir', None)])
776
777 monkeypatch.setattr(collection, 'find_existing_collections', mock_installed_collections)
778
779 test_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))
780 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(test_dir, validate_certs=False)
781
782 mock_display = MagicMock()
783 monkeypatch.setattr(Display, 'display', mock_display)
784
785 mock_get_info = MagicMock()
786 mock_get_info.return_value = api.CollectionVersionMetadata('namespace', 'collection', '1.2.3', None, None, {}, None, None)
787 monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata', mock_get_info)
788
789 mock_get_versions = MagicMock(return_value=['1.2.3', '1.3.0'])
790 monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_get_versions)
791
792 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection'])
793 cli.run()
794
795 expected = "Nothing to do. All requested collections are already installed. If you want to reinstall them, consider using `--force`."
796 assert mock_display.mock_calls[1][1][0] == expected
797
798
799 def test_install_collection(collection_artifact, monkeypatch):
800 mock_display = MagicMock()
801 monkeypatch.setattr(Display, 'display', mock_display)
802
803 collection_tar = collection_artifact[1]
804
805 temp_path = os.path.join(os.path.split(collection_tar)[0], b'temp')
806 os.makedirs(temp_path)
807 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(temp_path, validate_certs=False)
808
809 output_path = os.path.join(os.path.split(collection_tar)[0])
810 collection_path = os.path.join(output_path, b'ansible_namespace', b'collection')
811 os.makedirs(os.path.join(collection_path, b'delete_me')) # Create a folder to verify the install cleans out the dir
812
813 candidate = Candidate('ansible_namespace.collection', '0.1.0', to_text(collection_tar), 'file', None)
814 collection.install(candidate, to_text(output_path), concrete_artifact_cm)
815
816 # Ensure the temp directory is empty, nothing is left behind
817 assert os.listdir(temp_path) == []
818
819 actual_files = os.listdir(collection_path)
820 actual_files.sort()
821 assert actual_files == [b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks', b'plugins', b'roles',
822 b'runme.sh']
823
824 assert stat.S_IMODE(os.stat(os.path.join(collection_path, b'plugins')).st_mode) == S_IRWXU_RXG_RXO
825 assert stat.S_IMODE(os.stat(os.path.join(collection_path, b'README.md')).st_mode) == S_IRWU_RG_RO
826 assert stat.S_IMODE(os.stat(os.path.join(collection_path, b'runme.sh')).st_mode) == S_IRWXU_RXG_RXO
827
828 assert mock_display.call_count == 2
829 assert mock_display.mock_calls[0][1][0] == "Installing 'ansible_namespace.collection:0.1.0' to '%s'" \
830 % to_text(collection_path)
831 assert mock_display.mock_calls[1][1][0] == "ansible_namespace.collection:0.1.0 was installed successfully"
832
833
834 def test_install_collection_with_download(galaxy_server, collection_artifact, monkeypatch):
835 collection_path, collection_tar = collection_artifact
836 shutil.rmtree(collection_path)
837
838 collections_dir = ('%s' % os.path.sep).join(to_text(collection_path).split('%s' % os.path.sep)[:-2])
839
840 temp_path = os.path.join(os.path.split(collection_tar)[0], b'temp')
841 os.makedirs(temp_path)
842
843 mock_display = MagicMock()
844 monkeypatch.setattr(Display, 'display', mock_display)
845
846 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(temp_path, validate_certs=False)
847
848 mock_download = MagicMock()
849 mock_download.return_value = collection_tar
850 monkeypatch.setattr(concrete_artifact_cm, 'get_galaxy_artifact_path', mock_download)
851
852 req = Candidate('ansible_namespace.collection', '0.1.0', 'https://downloadme.com', 'galaxy', None)
853 collection.install(req, to_text(collections_dir), concrete_artifact_cm)
854
855 actual_files = os.listdir(collection_path)
856 actual_files.sort()
857 assert actual_files == [b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks', b'plugins', b'roles',
858 b'runme.sh']
859
860 assert mock_display.call_count == 2
861 assert mock_display.mock_calls[0][1][0] == "Installing 'ansible_namespace.collection:0.1.0' to '%s'" \
862 % to_text(collection_path)
863 assert mock_display.mock_calls[1][1][0] == "ansible_namespace.collection:0.1.0 was installed successfully"
864
865 assert mock_download.call_count == 1
866 assert mock_download.mock_calls[0][1][0].src == 'https://downloadme.com'
867 assert mock_download.mock_calls[0][1][0].type == 'galaxy'
868
869
870 def test_install_collections_from_tar(collection_artifact, monkeypatch):
871 collection_path, collection_tar = collection_artifact
872 temp_path = os.path.split(collection_tar)[0]
873 shutil.rmtree(collection_path)
874
875 mock_display = MagicMock()
876 monkeypatch.setattr(Display, 'display', mock_display)
877
878 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(temp_path, validate_certs=False)
879
880 requirements = [Requirement('ansible_namespace.collection', '0.1.0', to_text(collection_tar), 'file', None)]
881 collection.install_collections(
882 requirements, to_text(temp_path), [], False, False, False, False, False, False, concrete_artifact_cm, True, False, set())
883
884 assert os.path.isdir(collection_path)
885
886 actual_files = os.listdir(collection_path)
887 actual_files.sort()
888 assert actual_files == [b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks', b'plugins', b'roles',
889 b'runme.sh']
890
891 with open(os.path.join(collection_path, b'MANIFEST.json'), 'rb') as manifest_obj:
892 actual_manifest = json.loads(to_text(manifest_obj.read()))
893
894 assert actual_manifest['collection_info']['namespace'] == 'ansible_namespace'
895 assert actual_manifest['collection_info']['name'] == 'collection'
896 assert actual_manifest['collection_info']['version'] == '0.1.0'
897
898 # Filter out the progress cursor display calls.
899 display_msgs = [m[1][0] for m in mock_display.mock_calls if 'newline' not in m[2] and len(m[1]) == 1]
900 assert len(display_msgs) == 5
901 assert display_msgs[0] == "Process install dependency map"
902 assert display_msgs[1] == "[WARNING]: ansible_namespace.collection:0.1.0 does not have requires_ansible metadata.\n"
903 assert display_msgs[2] == "Starting collection install process"
904 assert display_msgs[3] == "Installing 'ansible_namespace.collection:0.1.0' to '%s'" % to_text(collection_path)
905
906
907 # Makes sure we don't get stuck in some recursive loop
908 @pytest.mark.parametrize('collection_artifact', [
909 {'ansible_namespace.collection': '>=0.0.1'},
910 ], indirect=True)
911 def test_install_collection_with_circular_dependency(collection_artifact, monkeypatch):
912 collection_path, collection_tar = collection_artifact
913 temp_path = os.path.split(collection_tar)[0]
914 shutil.rmtree(collection_path)
915
916 mock_display = MagicMock()
917 monkeypatch.setattr(Display, 'display', mock_display)
918
919 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(temp_path, validate_certs=False)
920 requirements = [Requirement('ansible_namespace.collection', '0.1.0', to_text(collection_tar), 'file', None)]
921 collection.install_collections(
922 requirements, to_text(temp_path), [], False, False, False, False, False, False, concrete_artifact_cm, True, False, set())
923
924 assert os.path.isdir(collection_path)
925
926 actual_files = os.listdir(collection_path)
927 actual_files.sort()
928 assert actual_files == [b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks', b'plugins', b'roles',
929 b'runme.sh']
930
931 with open(os.path.join(collection_path, b'MANIFEST.json'), 'rb') as manifest_obj:
932 actual_manifest = json.loads(to_text(manifest_obj.read()))
933
934 assert actual_manifest['collection_info']['namespace'] == 'ansible_namespace'
935 assert actual_manifest['collection_info']['name'] == 'collection'
936 assert actual_manifest['collection_info']['version'] == '0.1.0'
937 assert actual_manifest['collection_info']['dependencies'] == {'ansible_namespace.collection': '>=0.0.1'}
938
939 # Filter out the progress cursor display calls.
940 display_msgs = [m[1][0] for m in mock_display.mock_calls if 'newline' not in m[2] and len(m[1]) == 1]
941 assert len(display_msgs) == 5
942 assert display_msgs[0] == "Process install dependency map"
943 assert display_msgs[1] == "[WARNING]: ansible_namespace.collection:0.1.0 does not have requires_ansible metadata.\n"
944 assert display_msgs[2] == "Starting collection install process"
945 assert display_msgs[3] == "Installing 'ansible_namespace.collection:0.1.0' to '%s'" % to_text(collection_path)
946 assert display_msgs[4] == "ansible_namespace.collection:0.1.0 was installed successfully"
947
948
949 @pytest.mark.parametrize('collection_artifact', [
950 None,
951 {},
952 ], indirect=True)
953 def test_install_collection_with_no_dependency(collection_artifact, monkeypatch):
954 collection_path, collection_tar = collection_artifact
955 temp_path = os.path.split(collection_tar)[0]
956 shutil.rmtree(collection_path)
957
958 concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(temp_path, validate_certs=False)
959 requirements = [Requirement('ansible_namespace.collection', '0.1.0', to_text(collection_tar), 'file', None)]
960 collection.install_collections(
961 requirements, to_text(temp_path), [], False, False, False, False, False, False, concrete_artifact_cm, True, False, set())
962
963 assert os.path.isdir(collection_path)
964
965 with open(os.path.join(collection_path, b'MANIFEST.json'), 'rb') as manifest_obj:
966 actual_manifest = json.loads(to_text(manifest_obj.read()))
967
968 assert not actual_manifest['collection_info']['dependencies']
969 assert actual_manifest['collection_info']['namespace'] == 'ansible_namespace'
970 assert actual_manifest['collection_info']['name'] == 'collection'
971 assert actual_manifest['collection_info']['version'] == '0.1.0'
972
973
974 @pytest.mark.parametrize(
975 "signatures,required_successful_count,ignore_errors,expected_success",
976 [
977 ([], 'all', [], True),
978 (["good_signature"], 'all', [], True),
979 (["good_signature", collection.gpg.GpgBadArmor(status='failed')], 'all', [], False),
980 ([collection.gpg.GpgBadArmor(status='failed')], 'all', [], False),
981 # This is expected to succeed because ignored does not increment failed signatures.
982 # "all" signatures is not a specific number, so all == no (non-ignored) signatures in this case.
983 ([collection.gpg.GpgBadArmor(status='failed')], 'all', ["BADARMOR"], True),
984 ([collection.gpg.GpgBadArmor(status='failed'), "good_signature"], 'all', ["BADARMOR"], True),
985 ([], '+all', [], False),
986 ([collection.gpg.GpgBadArmor(status='failed')], '+all', ["BADARMOR"], False),
987 ([], '1', [], True),
988 ([], '+1', [], False),
989 (["good_signature"], '2', [], False),
990 (["good_signature", collection.gpg.GpgBadArmor(status='failed')], '2', [], False),
991 # This is expected to fail because ignored does not increment successful signatures.
992 # 2 signatures are required, but only 1 is successful.
993 (["good_signature", collection.gpg.GpgBadArmor(status='failed')], '2', ["BADARMOR"], False),
994 (["good_signature", "good_signature"], '2', [], True),
995 ]
996 )
997 def test_verify_file_signatures(signatures: list[str], required_successful_count: str, ignore_errors: list[str], expected_success: bool) -> None:
998 def gpg_error_generator(results):
999 for result in results:
1000 if isinstance(result, collection.gpg.GpgBaseError):
1001 yield result
1002
1003 fqcn = 'ns.coll'
1004 manifest_file = 'MANIFEST.json'
1005 keyring = '~/.ansible/pubring.kbx'
1006
1007 with patch.object(collection, 'run_gpg_verify', MagicMock(return_value=("somestdout", 0,))):
1008 with patch.object(collection, 'parse_gpg_errors', MagicMock(return_value=gpg_error_generator(signatures))):
1009 assert collection.verify_file_signatures(
1010 fqcn,
1011 manifest_file,
1012 signatures,
1013 keyring,
1014 required_successful_count,
1015 ignore_errors
1016 ) == expected_success