Debian Codegraph @

test/units/cli/test_galaxy.py

raw
1 # -*- coding: utf-8 -*-
2 # (c) 2016, Adrian Likins <[email protected]>
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18
19 from __future__ import annotations
20
21 import contextlib
22
23 import ansible
24 from io import BytesIO
25 import json
26 import os
27 import pytest
28 import shutil
29 import stat
30 import tarfile
31 import tempfile
32 import yaml
33
34 import ansible.constants as C
35 from ansible import context
36 from ansible.cli.galaxy import GalaxyCLI
37 from ansible.galaxy import collection
38 from ansible.galaxy.api import GalaxyAPI
39 from ansible.errors import AnsibleError
40 from ansible.module_utils.common.file import S_IRWU_RG_RO, S_IRWXU_RXG_RXO
41 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
42 from ansible.utils import context_objects as co
43 from ansible.utils.display import Display
44 import unittest
45 from unittest.mock import patch, MagicMock
46
47 pytestmark = pytest.mark.usefixtures('collection_loader')
48
49
50 @pytest.fixture(autouse=True)
51 def reset_cli_args():
52 co.GlobalCLIArgs._Singleton__instance = None
53 yield
54 co.GlobalCLIArgs._Singleton__instance = None
55
56
57 class TestGalaxy(unittest.TestCase):
58 @classmethod
59 def setUpClass(cls):
60 """creating prerequisites for installing a role; setUpClass occurs ONCE whereas setUp occurs with every method tested."""
61 # class data for easy viewing: role_dir, role_tar, role_name, role_req, role_path
62
63 cls.temp_dir = tempfile.mkdtemp(prefix='ansible-test_galaxy-')
64 os.chdir(cls.temp_dir)
65
66 shutil.rmtree("./delete_me", ignore_errors=True)
67
68 # creating framework for a role
69 gc = GalaxyCLI(args=["ansible-galaxy", "init", "--offline", "delete_me"])
70 gc.run()
71 cls.role_dir = "./delete_me"
72 cls.role_name = "delete_me"
73
74 # making a temp dir for role installation
75 cls.role_path = os.path.join(tempfile.mkdtemp(), "roles")
76 os.makedirs(cls.role_path)
77
78 # creating a tar file name for class data
79 cls.role_tar = './delete_me.tar.gz'
80 cls.makeTar(cls.role_tar, cls.role_dir)
81
82 # creating a temp file with installation requirements
83 cls.role_req = './delete_me_requirements.yml'
84 with open(cls.role_req, "w") as fd:
85 fd.write("- 'src': '%s'\n 'name': '%s'\n 'path': '%s'" % (cls.role_tar, cls.role_name, cls.role_path))
86
87 # DTFIX-FUTURE: use a proper fixture for all of this
88 from ansible.utils.collection_loader._collection_finder import _AnsibleCollectionFinder
89 _AnsibleCollectionFinder._remove()
90
91 @classmethod
92 def makeTar(cls, output_file, source_dir):
93 """ used for making a tarfile from a role directory """
94 # adding directory into a tar file
95 with tarfile.open(output_file, "w:gz") as tar:
96 tar.add(source_dir, arcname=os.path.basename(source_dir))
97
98 @classmethod
99 def tearDownClass(cls):
100 """After tests are finished removes things created in setUpClass"""
101 # deleting the temp role directory
102 shutil.rmtree(cls.role_dir, ignore_errors=True)
103 with contextlib.suppress(FileNotFoundError):
104 os.remove(cls.role_req)
105 with contextlib.suppress(FileNotFoundError):
106 os.remove(cls.role_tar)
107 shutil.rmtree(cls.role_path, ignore_errors=True)
108
109 os.chdir('/')
110 shutil.rmtree(cls.temp_dir, ignore_errors=True)
111
112 def setUp(self):
113 # Reset the stored command line args
114 co.GlobalCLIArgs._Singleton__instance = None
115 self.default_args = ['ansible-galaxy']
116
117 def tearDown(self):
118 # Reset the stored command line args
119 co.GlobalCLIArgs._Singleton__instance = None
120
121 def test_init(self):
122 galaxy_cli = GalaxyCLI(args=self.default_args)
123 assert isinstance(galaxy_cli, GalaxyCLI)
124
125 def test_display_min(self):
126 gc = GalaxyCLI(args=self.default_args)
127 role_info = {'name': 'some_role_name'}
128 display_result = gc._display_role_info(role_info)
129 assert display_result.find('some_role_name') > -1
130
131 def test_display_galaxy_info(self):
132 gc = GalaxyCLI(args=self.default_args)
133 galaxy_info = {}
134 role_info = {'name': 'some_role_name',
135 'galaxy_info': galaxy_info}
136 display_result = gc._display_role_info(role_info)
137 self.assertNotEqual(display_result.find('\n\tgalaxy_info:'), -1, 'Expected galaxy_info to be indented once')
138
139 def test_run(self):
140 """ verifies that the GalaxyCLI object's api is created and that execute() is called. """
141 gc = GalaxyCLI(args=["ansible-galaxy", "install", "--ignore-errors", "imaginary_role"])
142 gc.parse()
143 with patch.object(ansible.cli.CLI, "run", return_value=None) as mock_run:
144 gc.run()
145 # testing
146 self.assertIsInstance(gc.galaxy, ansible.galaxy.Galaxy)
147 self.assertEqual(mock_run.call_count, 1)
148 assert isinstance(gc.api, ansible.galaxy.api.GalaxyAPI)
149
150 def test_execute_remove(self):
151 # installing role
152 gc = GalaxyCLI(args=["ansible-galaxy", "install", "-p", self.role_path, "-r", self.role_req, '--force'])
153 gc.run()
154
155 # location where the role was installed
156 role_file = os.path.join(self.role_path, self.role_name)
157
158 # removing role
159 # Have to reset the arguments in the context object manually since we're doing the
160 # equivalent of running the command line program twice
161 co.GlobalCLIArgs._Singleton__instance = None
162 gc = GalaxyCLI(args=["ansible-galaxy", "remove", role_file, self.role_name])
163 gc.run()
164
165 # testing role was removed
166 removed_role = not os.path.exists(role_file)
167 self.assertTrue(removed_role)
168
169 def test_exit_without_ignore_without_flag(self):
170 """ tests that GalaxyCLI exits with the error specified if the --ignore-errors flag is not used """
171 gc = GalaxyCLI(args=["ansible-galaxy", "install", "--server=None", "fake_role_name"])
172 with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display:
173 # testing that error expected is raised
174 self.assertRaises(AnsibleError, gc.run)
175 assert mocked_display.call_count == 2
176 assert mocked_display.mock_calls[0].args[0] == "Starting galaxy role install process"
177 assert "fake_role_name was NOT installed successfully" in mocked_display.mock_calls[1].args[0]
178
179 def test_exit_without_ignore_with_flag(self):
180 """ tests that GalaxyCLI exits without the error specified if the --ignore-errors flag is used """
181 # testing with --ignore-errors flag
182 gc = GalaxyCLI(args=["ansible-galaxy", "install", "--server=None", "fake_role_name", "--ignore-errors"])
183 with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display:
184 gc.run()
185 assert mocked_display.call_count == 2
186 assert mocked_display.mock_calls[0].args[0] == "Starting galaxy role install process"
187 assert "fake_role_name was NOT installed successfully" in mocked_display.mock_calls[1].args[0]
188
189 def test_parse_no_action(self):
190 """ testing the options parser when no action is given """
191 gc = GalaxyCLI(args=["ansible-galaxy", ""])
192 self.assertRaises(SystemExit, gc.parse)
193
194 def test_parse_invalid_action(self):
195 """ testing the options parser when an invalid action is given """
196 gc = GalaxyCLI(args=["ansible-galaxy", "NOT_ACTION"])
197 self.assertRaises(SystemExit, gc.parse)
198
199 def test_parse_delete(self):
200 """ testing the options parser when the action 'delete' is given """
201 gc = GalaxyCLI(args=["ansible-galaxy", "delete", "foo", "bar"])
202 gc.parse()
203 self.assertEqual(context.CLIARGS['verbosity'], 0)
204
205 def test_parse_import(self):
206 """ testing the options parser when the action 'import' is given """
207 gc = GalaxyCLI(args=["ansible-galaxy", "import", "foo", "bar"])
208 gc.parse()
209 assert context.CLIARGS['wait']
210 assert context.CLIARGS['reference'] is None
211 assert not context.CLIARGS['check_status']
212 assert context.CLIARGS['verbosity'] == 0
213
214 def test_parse_info(self):
215 """ testing the options parser when the action 'info' is given """
216 gc = GalaxyCLI(args=["ansible-galaxy", "info", "foo", "bar"])
217 gc.parse()
218 assert not context.CLIARGS['offline']
219
220 def test_parse_init(self):
221 """ testing the options parser when the action 'init' is given """
222 gc = GalaxyCLI(args=["ansible-galaxy", "init", "foo"])
223 gc.parse()
224 assert not context.CLIARGS['offline']
225 assert not context.CLIARGS['force']
226
227 def test_parse_install(self):
228 """ testing the options parser when the action 'install' is given """
229 gc = GalaxyCLI(args=["ansible-galaxy", "install"])
230 gc.parse()
231 assert not context.CLIARGS['ignore_errors']
232 assert not context.CLIARGS['no_deps']
233 assert context.CLIARGS['requirements'] is None
234 assert not context.CLIARGS['force']
235
236 def test_parse_list(self):
237 """ testing the options parser when the action 'list' is given """
238 gc = GalaxyCLI(args=["ansible-galaxy", "list"])
239 gc.parse()
240 self.assertEqual(context.CLIARGS['verbosity'], 0)
241
242 def test_parse_remove(self):
243 """ testing the options parser when the action 'remove' is given """
244 gc = GalaxyCLI(args=["ansible-galaxy", "remove", "foo"])
245 gc.parse()
246 self.assertEqual(context.CLIARGS['verbosity'], 0)
247
248 def test_parse_search(self):
249 """ testing the options parswer when the action 'search' is given """
250 gc = GalaxyCLI(args=["ansible-galaxy", "search"])
251 gc.parse()
252 assert context.CLIARGS['platforms'] is None
253 assert context.CLIARGS['galaxy_tags'] is None
254 assert context.CLIARGS['author'] is None
255
256 def test_parse_setup(self):
257 """ testing the options parser when the action 'setup' is given """
258 gc = GalaxyCLI(args=["ansible-galaxy", "setup", "source", "github_user", "github_repo", "secret"])
259 gc.parse()
260 assert context.CLIARGS['verbosity'] == 0
261 assert context.CLIARGS['remove_id'] is None
262 assert not context.CLIARGS['setup_list']
263
264
265 class ValidRoleTests(object):
266
267 expected_role_dirs = ('defaults', 'files', 'handlers', 'meta', 'tasks', 'templates', 'vars', 'tests')
268
269 @classmethod
270 def setUpRole(cls, role_name, galaxy_args=None, skeleton_path=None, use_explicit_type=False):
271 if galaxy_args is None:
272 galaxy_args = []
273
274 if skeleton_path is not None:
275 cls.role_skeleton_path = skeleton_path
276 galaxy_args += ['--role-skeleton', skeleton_path]
277
278 # Make temp directory for testing
279 cls.test_dir = tempfile.mkdtemp()
280
281 cls.role_dir = os.path.join(cls.test_dir, role_name)
282 cls.role_name = role_name
283
284 # create role using default skeleton
285 args = ['ansible-galaxy']
286 if use_explicit_type:
287 args += ['role']
288 args += ['init', '-c', '--offline'] + galaxy_args + ['--init-path', cls.test_dir, cls.role_name]
289
290 gc = GalaxyCLI(args=args)
291 gc.run()
292 cls.gc = gc
293
294 if skeleton_path is None:
295 cls.role_skeleton_path = gc.galaxy.default_role_skeleton_path
296
297 # DTFIX-FUTURE: use a proper fixture for all of this
298 from ansible.utils.collection_loader._collection_finder import _AnsibleCollectionFinder
299 _AnsibleCollectionFinder._remove()
300
301 @classmethod
302 def tearDownRole(cls):
303 shutil.rmtree(cls.test_dir, ignore_errors=True)
304
305 def test_metadata(self):
306 with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
307 metadata = yaml.safe_load(mf)
308 self.assertIn('galaxy_info', metadata, msg='unable to find galaxy_info in metadata')
309 self.assertIn('dependencies', metadata, msg='unable to find dependencies in metadata')
310
311 def test_readme(self):
312 readme_path = os.path.join(self.role_dir, 'README.md')
313 self.assertTrue(os.path.exists(readme_path), msg='Readme doesn\'t exist')
314
315 def test_main_ymls(self):
316 need_main_ymls = set(self.expected_role_dirs) - set(['meta', 'tests', 'files', 'templates'])
317 for d in need_main_ymls:
318 main_yml = os.path.join(self.role_dir, d, 'main.yml')
319 self.assertTrue(os.path.exists(main_yml))
320 if self.role_name == 'delete_me_skeleton':
321 expected_string = "---\n# {0} file for {1}".format(d, self.role_name)
322 else:
323 expected_string = "#SPDX-License-Identifier: MIT-0\n---\n# {0} file for {1}".format(d, self.role_name)
324 with open(main_yml, 'r') as f:
325 self.assertEqual(expected_string, f.read().strip())
326
327 def test_role_dirs(self):
328 for d in self.expected_role_dirs:
329 self.assertTrue(os.path.isdir(os.path.join(self.role_dir, d)), msg="Expected role subdirectory {0} doesn't exist".format(d))
330
331 def test_readme_contents(self):
332 with open(os.path.join(self.role_dir, 'README.md'), 'r') as readme:
333 contents = readme.read()
334
335 with open(os.path.join(self.role_skeleton_path, 'README.md'), 'r') as f:
336 expected_contents = f.read()
337
338 self.assertEqual(expected_contents, contents, msg='README.md does not match expected')
339
340 def test_test_yml(self):
341 with open(os.path.join(self.role_dir, 'tests', 'test.yml'), 'r') as f:
342 test_playbook = yaml.safe_load(f)
343 print(test_playbook)
344 self.assertEqual(len(test_playbook), 1)
345 self.assertEqual(test_playbook[0]['hosts'], 'localhost')
346 self.assertEqual(test_playbook[0]['remote_user'], 'root')
347 self.assertListEqual(test_playbook[0]['roles'], [self.role_name], msg='The list of roles included in the test play doesn\'t match')
348
349
350 class TestGalaxyInitDefault(unittest.TestCase, ValidRoleTests):
351
352 @classmethod
353 def setUpClass(cls):
354 cls.setUpRole(role_name='delete_me')
355
356 @classmethod
357 def tearDownClass(cls):
358 cls.tearDownRole()
359
360 def test_metadata_contents(self):
361 with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
362 metadata = yaml.safe_load(mf)
363 self.assertEqual(metadata.get('galaxy_info', dict()).get('author'), 'your name', msg='author was not set properly in metadata')
364
365
366 class TestGalaxyInitAPB(unittest.TestCase, ValidRoleTests):
367
368 @classmethod
369 def setUpClass(cls):
370 cls.setUpRole('delete_me_apb', galaxy_args=['--type=apb'])
371
372 @classmethod
373 def tearDownClass(cls):
374 cls.tearDownRole()
375
376 def test_metadata_apb_tag(self):
377 with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
378 metadata = yaml.safe_load(mf)
379 self.assertIn('apb', metadata.get('galaxy_info', dict()).get('galaxy_tags', []), msg='apb tag not set in role metadata')
380
381 def test_metadata_contents(self):
382 with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
383 metadata = yaml.safe_load(mf)
384 self.assertEqual(metadata.get('galaxy_info', dict()).get('author'), 'your name', msg='author was not set properly in metadata')
385
386 def test_apb_yml(self):
387 self.assertTrue(os.path.exists(os.path.join(self.role_dir, 'apb.yml')), msg='apb.yml was not created')
388
389 def test_test_yml(self):
390 with open(os.path.join(self.role_dir, 'tests', 'test.yml'), 'r') as f:
391 test_playbook = yaml.safe_load(f)
392 print(test_playbook)
393 self.assertEqual(len(test_playbook), 1)
394 self.assertEqual(test_playbook[0]['hosts'], 'localhost')
395 self.assertFalse(test_playbook[0]['gather_facts'])
396 self.assertEqual(test_playbook[0]['connection'], 'local')
397 self.assertIsNone(test_playbook[0]['tasks'], msg='We\'re expecting an unset list of tasks in test.yml')
398
399
400 class TestGalaxyInitContainer(unittest.TestCase, ValidRoleTests):
401
402 @classmethod
403 def setUpClass(cls):
404 cls.setUpRole('delete_me_container', galaxy_args=['--type=container'])
405
406 @classmethod
407 def tearDownClass(cls):
408 cls.tearDownRole()
409
410 def test_metadata_container_tag(self):
411 with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
412 metadata = yaml.safe_load(mf)
413 self.assertIn('container', metadata.get('galaxy_info', dict()).get('galaxy_tags', []), msg='container tag not set in role metadata')
414
415 def test_metadata_contents(self):
416 with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
417 metadata = yaml.safe_load(mf)
418 self.assertEqual(metadata.get('galaxy_info', dict()).get('author'), 'your name', msg='author was not set properly in metadata')
419
420 def test_meta_container_yml(self):
421 self.assertTrue(os.path.exists(os.path.join(self.role_dir, 'meta', 'container.yml')), msg='container.yml was not created')
422
423 def test_test_yml(self):
424 with open(os.path.join(self.role_dir, 'tests', 'test.yml'), 'r') as f:
425 test_playbook = yaml.safe_load(f)
426 print(test_playbook)
427 self.assertEqual(len(test_playbook), 1)
428 self.assertEqual(test_playbook[0]['hosts'], 'localhost')
429 self.assertFalse(test_playbook[0]['gather_facts'])
430 self.assertEqual(test_playbook[0]['connection'], 'local')
431 self.assertIsNone(test_playbook[0]['tasks'], msg='We\'re expecting an unset list of tasks in test.yml')
432
433
434 class TestGalaxyInitSkeleton(unittest.TestCase, ValidRoleTests):
435
436 @classmethod
437 def setUpClass(cls):
438 role_skeleton_path = os.path.join(os.path.split(__file__)[0], 'test_data', 'role_skeleton')
439 cls.setUpRole('delete_me_skeleton', skeleton_path=role_skeleton_path, use_explicit_type=True)
440
441 @classmethod
442 def tearDownClass(cls):
443 cls.tearDownRole()
444
445 def test_empty_files_dir(self):
446 files_dir = os.path.join(self.role_dir, 'files')
447 self.assertTrue(os.path.isdir(files_dir))
448 self.assertListEqual(os.listdir(files_dir), [], msg='we expect the files directory to be empty, is ignore working?')
449
450 def test_template_ignore_jinja(self):
451 test_conf_j2 = os.path.join(self.role_dir, 'templates', 'test.conf.j2')
452 self.assertTrue(os.path.exists(test_conf_j2), msg="The test.conf.j2 template doesn't seem to exist, is it being rendered as test.conf?")
453 with open(test_conf_j2, 'r') as f:
454 contents = f.read()
455 expected_contents = '[defaults]\ntest_key = {{ test_variable }}'
456 self.assertEqual(expected_contents, contents.strip(), msg="test.conf.j2 doesn't contain what it should, is it being rendered?")
457
458 def test_template_ignore_jinja_subfolder(self):
459 test_conf_j2 = os.path.join(self.role_dir, 'templates', 'subfolder', 'test.conf.j2')
460 self.assertTrue(os.path.exists(test_conf_j2), msg="The test.conf.j2 template doesn't seem to exist, is it being rendered as test.conf?")
461 with open(test_conf_j2, 'r') as f:
462 contents = f.read()
463 expected_contents = '[defaults]\ntest_key = {{ test_variable }}'
464 self.assertEqual(expected_contents, contents.strip(), msg="test.conf.j2 doesn't contain what it should, is it being rendered?")
465
466 def test_template_ignore_similar_folder(self):
467 self.assertTrue(os.path.exists(os.path.join(self.role_dir, 'templates_extra', 'templates.txt')))
468
469 def test_skeleton_option(self):
470 self.assertEqual(self.role_skeleton_path, context.CLIARGS['role_skeleton'], msg='Skeleton path was not parsed properly from the command line')
471
472
473 @pytest.mark.parametrize('cli_args, expected', [
474 (['ansible-galaxy', 'collection', 'init', 'abc._def'], 0),
475 (['ansible-galaxy', 'collection', 'init', 'abc._def', '-vvv'], 3),
476 (['ansible-galaxy', 'collection', 'init', 'abc._def', '-vv'], 2),
477 ])
478 def test_verbosity_arguments(cli_args, expected, monkeypatch):
479 # Mock out the functions so we don't actually execute anything
480 for func_name in [f for f in dir(GalaxyCLI) if f.startswith("execute_")]:
481 monkeypatch.setattr(GalaxyCLI, func_name, MagicMock())
482
483 cli = GalaxyCLI(args=cli_args)
484 cli.run()
485
486 assert context.CLIARGS['verbosity'] == expected
487
488
489 @pytest.fixture()
490 def collection_skeleton(request, tmp_path_factory):
491 name, skeleton_path = request.param
492
493 galaxy_args = ['ansible-galaxy', 'collection', 'init', '-c']
494
495 if skeleton_path is not None:
496 galaxy_args += ['--collection-skeleton', skeleton_path]
497
498 test_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))
499 galaxy_args += ['--init-path', test_dir, name]
500
501 GalaxyCLI(args=galaxy_args).run()
502 namespace_name, collection_name = name.split('.', 1)
503 collection_dir = os.path.join(test_dir, namespace_name, collection_name)
504
505 return collection_dir
506
507
508 @pytest.mark.parametrize('collection_skeleton', [
509 ('ansible_test.my_collection', None),
510 ], indirect=True)
511 def test_collection_default(collection_skeleton):
512 meta_path = os.path.join(collection_skeleton, 'galaxy.yml')
513
514 with open(meta_path, 'r') as galaxy_meta:
515 metadata = yaml.safe_load(galaxy_meta)
516
517 assert metadata['namespace'] == 'ansible_test'
518 assert metadata['name'] == 'my_collection'
519 assert metadata['authors'] == ['your name <[email protected]>']
520 assert metadata['readme'] == 'README.md'
521 assert metadata['version'] == '1.0.0'
522 assert metadata['description'] == 'your collection description'
523 assert metadata['license'] == ['GPL-2.0-or-later']
524 assert metadata['tags'] == []
525 assert metadata['dependencies'] == {}
526 assert metadata['documentation'] == 'http://docs.example.com'
527 assert metadata['repository'] == 'http://example.com/repository'
528 assert metadata['homepage'] == 'http://example.com'
529 assert metadata['issues'] == 'http://example.com/issue/tracker'
530
531 for d in ['docs', 'plugins', 'roles']:
532 assert os.path.isdir(os.path.join(collection_skeleton, d)), \
533 "Expected collection subdirectory {0} doesn't exist".format(d)
534
535
536 @pytest.mark.parametrize('collection_skeleton', [
537 ('ansible_test.delete_me_skeleton', os.path.join(os.path.split(__file__)[0], 'test_data', 'collection_skeleton')),
538 ], indirect=True)
539 def test_collection_skeleton(collection_skeleton):
540 meta_path = os.path.join(collection_skeleton, 'galaxy.yml')
541
542 with open(meta_path, 'r') as galaxy_meta:
543 metadata = yaml.safe_load(galaxy_meta)
544
545 assert metadata['namespace'] == 'ansible_test'
546 assert metadata['name'] == 'delete_me_skeleton'
547 assert metadata['authors'] == ['Ansible Cow <[email protected]>', 'Tu Cow <[email protected]>']
548 assert metadata['version'] == '0.1.0'
549 assert metadata['readme'] == 'README.md'
550 assert len(metadata) == 5
551
552 assert os.path.exists(os.path.join(collection_skeleton, 'README.md'))
553
554 # Test empty directories exist and are empty
555 for empty_dir in ['plugins/action', 'plugins/filter', 'plugins/inventory', 'plugins/lookup',
556 'plugins/module_utils', 'plugins/modules']:
557
558 assert os.listdir(os.path.join(collection_skeleton, empty_dir)) == []
559
560 # Test files that don't end with .j2 were not templated
561 doc_file = os.path.join(collection_skeleton, 'docs', 'My Collection.md')
562 with open(doc_file, 'r') as f:
563 doc_contents = f.read()
564 assert doc_contents.strip() == 'Welcome to my test collection doc for {{ namespace }}.'
565
566 # Test files that end with .j2 but are in the templates directory were not templated
567 for template_dir in ['playbooks/templates', 'playbooks/templates/subfolder',
568 'roles/common/templates', 'roles/common/templates/subfolder']:
569 test_conf_j2 = os.path.join(collection_skeleton, template_dir, 'test.conf.j2')
570 assert os.path.exists(test_conf_j2)
571
572 with open(test_conf_j2, 'r') as f:
573 contents = f.read()
574 expected_contents = '[defaults]\ntest_key = {{ test_variable }}'
575
576 assert expected_contents == contents.strip()
577
578
579 @pytest.fixture()
580 def collection_artifact(collection_skeleton, tmp_path_factory):
581 """ Creates a collection artifact tarball that is ready to be published and installed """
582 output_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Output'))
583
584 # Create a file with +x in the collection so we can test the permissions
585 execute_path = os.path.join(collection_skeleton, 'runme.sh')
586 with open(execute_path, mode='wb') as fd:
587 fd.write(b"echo hi")
588
589 # S_ISUID should not be present on extraction.
590 os.chmod(execute_path, os.stat(execute_path).st_mode | stat.S_ISUID | stat.S_IEXEC)
591
592 # Because we call GalaxyCLI in collection_skeleton we need to reset the singleton back to None so it uses the new
593 # args, we reset the original args once it is done.
594 orig_cli_args = co.GlobalCLIArgs._Singleton__instance
595 try:
596 co.GlobalCLIArgs._Singleton__instance = None
597 galaxy_args = ['ansible-galaxy', 'collection', 'build', collection_skeleton, '--output-path', output_dir]
598 gc = GalaxyCLI(args=galaxy_args)
599 gc.run()
600
601 yield output_dir
602 finally:
603 co.GlobalCLIArgs._Singleton__instance = orig_cli_args
604
605
606 def test_invalid_skeleton_path():
607 expected = "- the skeleton path '/fake/path' does not exist, cannot init collection"
608
609 gc = GalaxyCLI(args=['ansible-galaxy', 'collection', 'init', 'my.collection', '--collection-skeleton',
610 '/fake/path'])
611 with pytest.raises(AnsibleError, match=expected):
612 gc.run()
613
614
615 @pytest.mark.parametrize("name", [
616 "",
617 "invalid",
618 "hypen-ns.collection",
619 "ns.hyphen-collection",
620 "ns.collection.weird",
621 ])
622 def test_invalid_collection_name_init(name):
623 expected = "Invalid collection name '%s', name must be in the format <namespace>.<collection>" % name
624
625 gc = GalaxyCLI(args=['ansible-galaxy', 'collection', 'init', name])
626 with pytest.raises(AnsibleError, match=expected):
627 gc.run()
628
629
630 @pytest.mark.parametrize("name, expected", [
631 ("", ""),
632 ("invalid", "invalid"),
633 ("invalid:1.0.0", "invalid"),
634 ("hypen-ns.collection", "hypen-ns.collection"),
635 ("ns.hyphen-collection", "ns.hyphen-collection"),
636 ("ns.collection.weird", "ns.collection.weird"),
637 ])
638 def test_invalid_collection_name_install(name, expected, tmp_path_factory):
639 install_path = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))
640
641 # FIXME: we should add the collection name in the error message
642 # Used to be: expected = "Invalid collection name '%s', name must be in the format <namespace>.<collection>" % expected
643 expected = "Neither the collection requirement entry key 'name', nor 'source' point to a concrete resolvable collection artifact. "
644 expected += r"Also 'name' is not an FQCN\. A valid collection name must be in the format <namespace>\.<collection>\. "
645 expected += r"Please make sure that the namespace and the collection name contain characters from \[a\-zA\-Z0\-9_\] only\."
646
647 gc = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', name, '-p', os.path.join(install_path, 'install')])
648 with pytest.raises(AnsibleError, match=expected):
649 gc.run()
650
651
652 @pytest.mark.parametrize('collection_skeleton', [
653 ('ansible_test.build_collection', None),
654 ], indirect=True)
655 def test_collection_build(collection_artifact):
656 tar_path = os.path.join(collection_artifact, 'ansible_test-build_collection-1.0.0.tar.gz')
657 assert tarfile.is_tarfile(tar_path)
658
659 with tarfile.open(tar_path, mode='r') as tar:
660 tar_members = tar.getmembers()
661
662 valid_files = ['MANIFEST.json', 'FILES.json', 'roles', 'docs', 'plugins', 'plugins/README.md', 'README.md',
663 'runme.sh', 'meta', 'meta/runtime.yml']
664 assert len(tar_members) == len(valid_files)
665
666 # Verify the uid and gid is 0 and the correct perms are set
667 for member in tar_members:
668 assert member.name in valid_files
669
670 assert member.gid == 0
671 assert member.gname == ''
672 assert member.uid == 0
673 assert member.uname == ''
674 if member.isdir() or member.name == 'runme.sh':
675 assert member.mode == S_IRWXU_RXG_RXO
676 else:
677 assert member.mode == S_IRWU_RG_RO
678
679 manifest_file = tar.extractfile(tar_members[0])
680 try:
681 manifest = json.loads(to_text(manifest_file.read()))
682 finally:
683 manifest_file.close()
684
685 coll_info = manifest['collection_info']
686 file_manifest = manifest['file_manifest_file']
687 assert manifest['format'] == 1
688 assert len(manifest.keys()) == 3
689
690 assert coll_info['namespace'] == 'ansible_test'
691 assert coll_info['name'] == 'build_collection'
692 assert coll_info['version'] == '1.0.0'
693 assert coll_info['authors'] == ['your name <[email protected]>']
694 assert coll_info['readme'] == 'README.md'
695 assert coll_info['tags'] == []
696 assert coll_info['description'] == 'your collection description'
697 assert coll_info['license'] == ['GPL-2.0-or-later']
698 assert coll_info['license_file'] is None
699 assert coll_info['dependencies'] == {}
700 assert coll_info['repository'] == 'http://example.com/repository'
701 assert coll_info['documentation'] == 'http://docs.example.com'
702 assert coll_info['homepage'] == 'http://example.com'
703 assert coll_info['issues'] == 'http://example.com/issue/tracker'
704 assert len(coll_info.keys()) == 14
705
706 assert file_manifest['name'] == 'FILES.json'
707 assert file_manifest['ftype'] == 'file'
708 assert file_manifest['chksum_type'] == 'sha256'
709 assert file_manifest['chksum_sha256'] is not None # Order of keys makes it hard to verify the checksum
710 assert file_manifest['format'] == 1
711 assert len(file_manifest.keys()) == 5
712
713 files_file = tar.extractfile(tar_members[1])
714 try:
715 files = json.loads(to_text(files_file.read()))
716 finally:
717 files_file.close()
718
719 assert len(files['files']) == 9
720 assert files['format'] == 1
721 assert len(files.keys()) == 2
722
723 valid_files_entries = ['.', 'roles', 'docs', 'plugins', 'plugins/README.md', 'README.md', 'runme.sh', 'meta', 'meta/runtime.yml']
724 for file_entry in files['files']:
725 assert file_entry['name'] in valid_files_entries
726 assert file_entry['format'] == 1
727
728 if file_entry['name'] in ['plugins/README.md', 'runme.sh', 'meta/runtime.yml']:
729 assert file_entry['ftype'] == 'file'
730 assert file_entry['chksum_type'] == 'sha256'
731 # Can't test the actual checksum as the html link changes based on the version or the file contents
732 # don't matter
733 assert file_entry['chksum_sha256'] is not None
734 elif file_entry['name'] == 'README.md':
735 assert file_entry['ftype'] == 'file'
736 assert file_entry['chksum_type'] == 'sha256'
737 assert file_entry['chksum_sha256'] == '6d8b5f9b5d53d346a8cd7638a0ec26e75e8d9773d952162779a49d25da6ef4f5'
738 else:
739 assert file_entry['ftype'] == 'dir'
740 assert file_entry['chksum_type'] is None
741 assert file_entry['chksum_sha256'] is None
742
743 assert len(file_entry.keys()) == 5
744
745
746 @pytest.fixture()
747 def collection_install(reset_cli_args, tmp_path_factory, monkeypatch):
748 mock_install = MagicMock()
749 monkeypatch.setattr(ansible.cli.galaxy, 'install_collections', mock_install)
750
751 mock_warning = MagicMock()
752 monkeypatch.setattr(ansible.utils.display.Display, 'warning', mock_warning)
753
754 output_dir = to_text((tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Output')))
755 yield mock_install, mock_warning, output_dir
756
757
758 def test_collection_install_with_names(collection_install):
759 mock_install, mock_warning, output_dir = collection_install
760
761 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'namespace.collection', 'namespace2.collection:1.0.1',
762 '--collections-path', output_dir]
763 GalaxyCLI(args=galaxy_args).run()
764
765 collection_path = os.path.join(output_dir, 'ansible_collections')
766 assert os.path.isdir(collection_path)
767
768 assert mock_warning.call_count == 1
769 assert "The specified collections path '%s' is not part of the configured Ansible collections path" % output_dir \
770 in mock_warning.call_args[0][0]
771
772 assert mock_install.call_count == 1
773 requirements = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in mock_install.call_args[0][0]]
774 assert requirements == [('namespace.collection', '*', None, 'galaxy'),
775 ('namespace2.collection', '1.0.1', None, 'galaxy')]
776 assert mock_install.call_args[0][1] == collection_path
777 assert len(mock_install.call_args[0][2]) == 1
778 assert mock_install.call_args[0][2][0].api_server == 'https://galaxy.ansible.com'
779 assert mock_install.call_args[0][2][0].validate_certs is True
780 assert mock_install.call_args[0][3] is False # ignore_errors
781 assert mock_install.call_args[0][4] is False # no_deps
782 assert mock_install.call_args[0][5] is False # force
783 assert mock_install.call_args[0][6] is False # force_deps
784
785
786 def test_collection_install_with_invalid_requirements_format(collection_install):
787 output_dir = collection_install[2]
788
789 requirements_file = os.path.join(output_dir, 'requirements.yml')
790 with open(requirements_file, 'wb') as req_obj:
791 req_obj.write(b'"invalid"')
792
793 galaxy_args = ['ansible-galaxy', 'collection', 'install', '--requirements-file', requirements_file,
794 '--collections-path', output_dir]
795
796 with pytest.raises(AnsibleError, match="Expecting requirements yaml to be a list or dictionary but got str"):
797 GalaxyCLI(args=galaxy_args).run()
798
799
800 def test_collection_install_with_requirements_file(collection_install):
801 mock_install, mock_warning, output_dir = collection_install
802
803 requirements_file = os.path.join(output_dir, 'requirements.yml')
804 with open(requirements_file, 'wb') as req_obj:
805 req_obj.write(b"""---
806 collections:
807 - namespace.coll
808 - name: namespace2.coll
809 version: '>2.0.1'
810 """)
811
812 galaxy_args = ['ansible-galaxy', 'collection', 'install', '--requirements-file', requirements_file,
813 '--collections-path', output_dir]
814 GalaxyCLI(args=galaxy_args).run()
815
816 collection_path = os.path.join(output_dir, 'ansible_collections')
817 assert os.path.isdir(collection_path)
818
819 assert mock_warning.call_count == 1
820 assert "The specified collections path '%s' is not part of the configured Ansible collections path" % output_dir \
821 in mock_warning.call_args[0][0]
822
823 assert mock_install.call_count == 1
824 requirements = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in mock_install.call_args[0][0]]
825 assert requirements == [('namespace.coll', '*', None, 'galaxy'),
826 ('namespace2.coll', '>2.0.1', None, 'galaxy')]
827 assert mock_install.call_args[0][1] == collection_path
828 assert mock_install.call_args[0][2][0].api_server == 'https://galaxy.ansible.com'
829 assert mock_install.call_args[0][2][0].validate_certs is True
830 assert mock_install.call_args[0][3] is False # ignore_errors
831 assert mock_install.call_args[0][4] is False # no_deps
832 assert mock_install.call_args[0][5] is False # force
833 assert mock_install.call_args[0][6] is False # force_deps
834
835
836 def test_collection_install_with_relative_path(collection_install, monkeypatch):
837 mock_install = collection_install[0]
838
839 mock_req = MagicMock()
840 mock_req.return_value = {'collections': [('namespace.coll', '*', None, None)], 'roles': []}
841 monkeypatch.setattr(ansible.cli.galaxy.GalaxyCLI, '_parse_requirements_file', mock_req)
842
843 monkeypatch.setattr(os, 'makedirs', MagicMock())
844
845 requirements_file = './requirements.myl'
846 collections_path = './ansible_collections'
847 galaxy_args = ['ansible-galaxy', 'collection', 'install', '--requirements-file', requirements_file,
848 '--collections-path', collections_path]
849 GalaxyCLI(args=galaxy_args).run()
850
851 assert mock_install.call_count == 1
852 assert mock_install.call_args[0][0] == [('namespace.coll', '*', None, None)]
853 assert mock_install.call_args[0][1] == os.path.abspath(collections_path)
854 assert len(mock_install.call_args[0][2]) == 1
855 assert mock_install.call_args[0][2][0].api_server == 'https://galaxy.ansible.com'
856 assert mock_install.call_args[0][2][0].validate_certs is True
857 assert mock_install.call_args[0][3] is False # ignore_errors
858 assert mock_install.call_args[0][4] is False # no_deps
859 assert mock_install.call_args[0][5] is False # force
860 assert mock_install.call_args[0][6] is False # force_deps
861
862 assert mock_req.call_count == 1
863 assert mock_req.call_args[0][0] == os.path.abspath(requirements_file)
864
865
866 def test_collection_install_with_unexpanded_path(collection_install, monkeypatch):
867 mock_install = collection_install[0]
868
869 mock_req = MagicMock()
870 mock_req.return_value = {'collections': [('namespace.coll', '*', None, None)], 'roles': []}
871 monkeypatch.setattr(ansible.cli.galaxy.GalaxyCLI, '_parse_requirements_file', mock_req)
872
873 monkeypatch.setattr(os, 'makedirs', MagicMock())
874
875 requirements_file = '~/requirements.myl'
876 collections_path = '~/ansible_collections'
877 galaxy_args = ['ansible-galaxy', 'collection', 'install', '--requirements-file', requirements_file,
878 '--collections-path', collections_path]
879 GalaxyCLI(args=galaxy_args).run()
880
881 assert mock_install.call_count == 1
882 assert mock_install.call_args[0][0] == [('namespace.coll', '*', None, None)]
883 assert mock_install.call_args[0][1] == os.path.expanduser(os.path.expandvars(collections_path))
884 assert len(mock_install.call_args[0][2]) == 1
885 assert mock_install.call_args[0][2][0].api_server == 'https://galaxy.ansible.com'
886 assert mock_install.call_args[0][2][0].validate_certs is True
887 assert mock_install.call_args[0][3] is False # ignore_errors
888 assert mock_install.call_args[0][4] is False # no_deps
889 assert mock_install.call_args[0][5] is False # force
890 assert mock_install.call_args[0][6] is False # force_deps
891
892 assert mock_req.call_count == 1
893 assert mock_req.call_args[0][0] == os.path.expanduser(os.path.expandvars(requirements_file))
894
895
896 def test_collection_install_in_collection_dir(collection_install, monkeypatch):
897 mock_install, mock_warning, output_dir = collection_install
898
899 collections_path = C.COLLECTIONS_PATHS[0]
900
901 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'namespace.collection', 'namespace2.collection:1.0.1',
902 '--collections-path', collections_path]
903 GalaxyCLI(args=galaxy_args).run()
904
905 assert mock_warning.call_count == 0
906
907 assert mock_install.call_count == 1
908 requirements = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in mock_install.call_args[0][0]]
909 assert requirements == [('namespace.collection', '*', None, 'galaxy'),
910 ('namespace2.collection', '1.0.1', None, 'galaxy')]
911 assert mock_install.call_args[0][1] == os.path.join(collections_path, 'ansible_collections')
912 assert len(mock_install.call_args[0][2]) == 1
913 assert mock_install.call_args[0][2][0].api_server == 'https://galaxy.ansible.com'
914 assert mock_install.call_args[0][2][0].validate_certs is True
915 assert mock_install.call_args[0][3] is False # ignore_errors
916 assert mock_install.call_args[0][4] is False # no_deps
917 assert mock_install.call_args[0][5] is False # force
918 assert mock_install.call_args[0][6] is False # force_deps
919
920
921 def test_collection_install_with_url(
922 monkeypatch: pytest.MonkeyPatch,
923 collection_install: tuple[MagicMock, MagicMock, str]
924 ) -> None:
925 mock_install, dummy, output_dir = collection_install
926
927 class MockHTTPResponse:
928 def __init__(self) -> None:
929 self._stream = BytesIO()
930 self.length = 'UNKNOWN'
931
932 def read(self, size: int = -1) -> bytes:
933 return self._stream.read(size)
934
935 mock_open = MagicMock(return_value=MockHTTPResponse())
936 monkeypatch.setattr(collection.concrete_artifact_manager, 'open_url', mock_open)
937
938 mock_metadata = MagicMock(return_value={'namespace': 'foo', 'name': 'bar', 'version': 'v1.0.0'})
939 monkeypatch.setattr(collection.concrete_artifact_manager, '_get_meta_from_tar', mock_metadata)
940
941 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'https://foo/bar/foo-bar-v1.0.0.tar.gz',
942 '--collections-path', output_dir]
943 GalaxyCLI(args=galaxy_args).run()
944
945 collection_path = os.path.join(output_dir, 'ansible_collections')
946 assert os.path.isdir(collection_path)
947
948 assert mock_install.call_count == 1
949 requirements = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in mock_install.call_args[0][0]]
950 assert requirements == [('foo.bar', 'v1.0.0', 'https://foo/bar/foo-bar-v1.0.0.tar.gz', 'url')]
951 assert mock_install.call_args[0][1] == collection_path
952 assert len(mock_install.call_args[0][2]) == 1
953 assert mock_install.call_args[0][2][0].api_server == 'https://galaxy.ansible.com'
954 assert mock_install.call_args[0][2][0].validate_certs is True
955 assert mock_install.call_args[0][3] is False # ignore_errors
956 assert mock_install.call_args[0][4] is False # no_deps
957 assert mock_install.call_args[0][5] is False # force
958 assert mock_install.call_args[0][6] is False # force_deps
959
960
961 def test_collection_install_name_and_requirements_fail(collection_install):
962 test_path = collection_install[2]
963 expected = 'The positional collection_name arg and --requirements-file are mutually exclusive.'
964
965 with pytest.raises(AnsibleError, match=expected):
966 GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', 'namespace.collection', '--collections-path',
967 test_path, '--requirements-file', test_path]).run()
968
969
970 def test_collection_install_no_name_and_requirements_fail(collection_install):
971 test_path = collection_install[2]
972 expected = 'You must specify a collection name or a requirements file.'
973
974 with pytest.raises(AnsibleError, match=expected):
975 GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', '--collections-path', test_path]).run()
976
977
978 def test_collection_install_path_with_ansible_collections(collection_install):
979 mock_install, mock_warning, output_dir = collection_install
980
981 collection_path = os.path.join(output_dir, 'ansible_collections')
982
983 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'namespace.collection', 'namespace2.collection:1.0.1',
984 '--collections-path', collection_path]
985 GalaxyCLI(args=galaxy_args).run()
986
987 assert os.path.isdir(collection_path)
988
989 assert mock_warning.call_count == 1
990 assert "The specified collections path '%s' is not part of the configured Ansible collections path" \
991 % collection_path in mock_warning.call_args[0][0]
992
993 assert mock_install.call_count == 1
994 requirements = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in mock_install.call_args[0][0]]
995 assert requirements == [('namespace.collection', '*', None, 'galaxy'),
996 ('namespace2.collection', '1.0.1', None, 'galaxy')]
997 assert mock_install.call_args[0][1] == collection_path
998 assert len(mock_install.call_args[0][2]) == 1
999 assert mock_install.call_args[0][2][0].api_server == 'https://galaxy.ansible.com'
1000 assert mock_install.call_args[0][2][0].validate_certs is True
1001 assert mock_install.call_args[0][3] is False # ignore_errors
1002 assert mock_install.call_args[0][4] is False # no_deps
1003 assert mock_install.call_args[0][5] is False # force
1004 assert mock_install.call_args[0][6] is False # force_deps
1005
1006
1007 def test_collection_install_ignore_certs(collection_install):
1008 mock_install, mock_warning, output_dir = collection_install
1009
1010 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'namespace.collection', '--collections-path', output_dir,
1011 '--ignore-certs']
1012 GalaxyCLI(args=galaxy_args).run()
1013
1014 assert mock_install.call_args[0][3] is False
1015
1016
1017 def test_collection_install_force(collection_install):
1018 mock_install, mock_warning, output_dir = collection_install
1019
1020 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'namespace.collection', '--collections-path', output_dir,
1021 '--force']
1022 GalaxyCLI(args=galaxy_args).run()
1023
1024 # mock_install args: collections, output_path, apis, ignore_errors, no_deps, force, force_deps
1025 assert mock_install.call_args[0][5] is True
1026
1027
1028 def test_collection_install_force_deps(collection_install):
1029 mock_install, mock_warning, output_dir = collection_install
1030
1031 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'namespace.collection', '--collections-path', output_dir,
1032 '--force-with-deps']
1033 GalaxyCLI(args=galaxy_args).run()
1034
1035 # mock_install args: collections, output_path, apis, ignore_errors, no_deps, force, force_deps
1036 assert mock_install.call_args[0][6] is True
1037
1038
1039 def test_collection_install_no_deps(collection_install):
1040 mock_install, mock_warning, output_dir = collection_install
1041
1042 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'namespace.collection', '--collections-path', output_dir,
1043 '--no-deps']
1044 GalaxyCLI(args=galaxy_args).run()
1045
1046 # mock_install args: collections, output_path, apis, ignore_errors, no_deps, force, force_deps
1047 assert mock_install.call_args[0][4] is True
1048
1049
1050 def test_collection_install_ignore(collection_install):
1051 mock_install, mock_warning, output_dir = collection_install
1052
1053 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'namespace.collection', '--collections-path', output_dir,
1054 '--ignore-errors']
1055 GalaxyCLI(args=galaxy_args).run()
1056
1057 # mock_install args: collections, output_path, apis, ignore_errors, no_deps, force, force_deps
1058 assert mock_install.call_args[0][3] is True
1059
1060
1061 def test_collection_install_custom_server(collection_install):
1062 mock_install, mock_warning, output_dir = collection_install
1063
1064 galaxy_args = ['ansible-galaxy', 'collection', 'install', 'namespace.collection', '--collections-path', output_dir,
1065 '--server', 'https://galaxy-dev.ansible.com']
1066 GalaxyCLI(args=galaxy_args).run()
1067
1068 assert len(mock_install.call_args[0][2]) == 1
1069 assert mock_install.call_args[0][2][0].api_server == 'https://galaxy-dev.ansible.com'
1070 assert mock_install.call_args[0][2][0].validate_certs is True
1071
1072
1073 @pytest.fixture()
1074 def requirements_file(request, tmp_path_factory):
1075 content = request.param
1076
1077 test_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Requirements'))
1078 requirements_file = os.path.join(test_dir, 'requirements.yml')
1079
1080 if content:
1081 with open(requirements_file, 'wb') as req_obj:
1082 req_obj.write(to_bytes(content))
1083
1084 yield requirements_file
1085
1086
1087 @pytest.fixture()
1088 def requirements_cli(monkeypatch):
1089 monkeypatch.setattr(GalaxyCLI, 'execute_install', MagicMock())
1090 cli = GalaxyCLI(args=['ansible-galaxy', 'install'])
1091 cli.run()
1092 return cli
1093
1094
1095 @pytest.mark.parametrize('requirements_file', [None], indirect=True)
1096 def test_parse_requirements_file_that_doesnt_exist(requirements_cli, requirements_file):
1097 expected = "The requirements file '%s' does not exist." % to_native(requirements_file)
1098 with pytest.raises(AnsibleError, match=expected):
1099 requirements_cli._parse_requirements_file(requirements_file)
1100
1101
1102 @pytest.mark.parametrize('requirements_file', ['not a valid yml file: hi: world'], indirect=True)
1103 def test_parse_requirements_file_that_isnt_yaml(requirements_cli, requirements_file):
1104 expected = "Failed to parse the requirements yml at '%s' with the following error" % to_native(requirements_file)
1105 with pytest.raises(AnsibleError, match=expected):
1106 requirements_cli._parse_requirements_file(requirements_file)
1107
1108
1109 @pytest.mark.parametrize('requirements_file', [("""
1110 # Older role based requirements.yml
1111 - galaxy.role
1112 - anotherrole
1113 """)], indirect=True)
1114 def test_parse_requirements_in_older_format_illegal(requirements_cli, requirements_file):
1115 expected = "Expecting requirements file to be a dict with the key 'collections' that contains a list of " \
1116 "collections to install"
1117
1118 with pytest.raises(AnsibleError, match=expected):
1119 requirements_cli._parse_requirements_file(requirements_file, allow_old_format=False)
1120
1121
1122 @pytest.mark.parametrize('requirements_file', ["""
1123 collections:
1124 - version: 1.0.0
1125 """], indirect=True)
1126 def test_parse_requirements_without_mandatory_name_key(requirements_cli, requirements_file):
1127 # Used to be "Collections requirement entry should contain the key name."
1128 # Should we check that either source or name is provided before using the dep resolver?
1129
1130 expected = "Neither the collection requirement entry key 'name', nor 'source' point to a concrete resolvable collection artifact. "
1131 expected += r"Also 'name' is not an FQCN\. A valid collection name must be in the format <namespace>\.<collection>\. "
1132 expected += r"Please make sure that the namespace and the collection name contain characters from \[a\-zA\-Z0\-9_\] only\."
1133
1134 with pytest.raises(AnsibleError, match=expected):
1135 requirements_cli._parse_requirements_file(requirements_file)
1136
1137
1138 @pytest.mark.parametrize('requirements_file', [("""
1139 collections:
1140 - namespace.collection1
1141 - namespace.collection2
1142 """), ("""
1143 collections:
1144 - name: namespace.collection1
1145 - name: namespace.collection2
1146 """)], indirect=True)
1147 def test_parse_requirements(requirements_cli, requirements_file):
1148 expected = {
1149 'roles': [],
1150 'collections': [('namespace.collection1', '*', None, 'galaxy'), ('namespace.collection2', '*', None, 'galaxy')]
1151 }
1152 actual = requirements_cli._parse_requirements_file(requirements_file)
1153 actual['collections'] = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in actual.get('collections', [])]
1154
1155 assert actual == expected
1156
1157
1158 @pytest.mark.parametrize('requirements_file', ["""
1159 collections:
1160 - name: namespace.collection1
1161 version: ">=1.0.0,<=2.0.0"
1162 source: https://galaxy-dev.ansible.com
1163 - namespace.collection2"""], indirect=True)
1164 def test_parse_requirements_with_extra_info(requirements_cli, requirements_file):
1165 actual = requirements_cli._parse_requirements_file(requirements_file)
1166 actual['collections'] = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in actual.get('collections', [])]
1167
1168 assert len(actual['roles']) == 0
1169 assert len(actual['collections']) == 2
1170 assert actual['collections'][0][0] == 'namespace.collection1'
1171 assert actual['collections'][0][1] == '>=1.0.0,<=2.0.0'
1172 assert actual['collections'][0][2].api_server == 'https://galaxy-dev.ansible.com'
1173
1174 assert actual['collections'][1] == ('namespace.collection2', '*', None, 'galaxy')
1175
1176
1177 @pytest.mark.parametrize('requirements_file', ["""
1178 roles:
1179 - username.role_name
1180 - src: username2.role_name2
1181 - src: ssh://github.com/user/repo
1182 scm: git
1183
1184 collections:
1185 - namespace.collection2
1186 """], indirect=True)
1187 def test_parse_requirements_with_roles_and_collections(requirements_cli, requirements_file):
1188 actual = requirements_cli._parse_requirements_file(requirements_file)
1189 actual['collections'] = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in actual.get('collections', [])]
1190
1191 assert len(actual['roles']) == 3
1192 assert actual['roles'][0].name == 'username.role_name'
1193 assert actual['roles'][1].name == 'username2.role_name2'
1194 assert actual['roles'][2].name == 'repo'
1195 assert actual['roles'][2].src == 'ssh://github.com/user/repo'
1196
1197 assert len(actual['collections']) == 1
1198 assert actual['collections'][0] == ('namespace.collection2', '*', None, 'galaxy')
1199
1200
1201 @pytest.mark.parametrize('requirements_file', ["""
1202 collections:
1203 - name: namespace.collection
1204 - name: namespace2.collection2
1205 source: https://galaxy-dev.ansible.com/
1206 - name: namespace3.collection3
1207 source: server
1208 """], indirect=True)
1209 def test_parse_requirements_with_collection_source(requirements_cli, requirements_file):
1210 galaxy_api = GalaxyAPI(requirements_cli.api, 'server', 'https://config-server')
1211 requirements_cli.api_servers.append(galaxy_api)
1212
1213 actual = requirements_cli._parse_requirements_file(requirements_file)
1214 actual['collections'] = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in actual.get('collections', [])]
1215
1216 assert actual['roles'] == []
1217 assert len(actual['collections']) == 3
1218 assert actual['collections'][0] == ('namespace.collection', '*', None, 'galaxy')
1219
1220 assert actual['collections'][1][0] == 'namespace2.collection2'
1221 assert actual['collections'][1][1] == '*'
1222 assert actual['collections'][1][2].api_server == 'https://galaxy-dev.ansible.com/'
1223
1224 assert actual['collections'][2][0] == 'namespace3.collection3'
1225 assert actual['collections'][2][1] == '*'
1226 assert actual['collections'][2][2].api_server == 'https://config-server'
1227
1228
1229 @pytest.mark.parametrize('requirements_file', ["""
1230 - username.included_role
1231 - src: https://github.com/user/repo
1232 """], indirect=True)
1233 def test_parse_requirements_roles_with_include(requirements_cli, requirements_file):
1234 reqs = [
1235 'ansible.role',
1236 {'include': requirements_file},
1237 ]
1238 parent_requirements = os.path.join(os.path.dirname(requirements_file), 'parent.yaml')
1239 with open(to_bytes(parent_requirements), 'wb') as req_fd:
1240 req_fd.write(to_bytes(yaml.safe_dump(reqs)))
1241
1242 actual = requirements_cli._parse_requirements_file(parent_requirements)
1243
1244 assert len(actual['roles']) == 3
1245 assert actual['collections'] == []
1246 assert actual['roles'][0].name == 'ansible.role'
1247 assert actual['roles'][1].name == 'username.included_role'
1248 assert actual['roles'][2].name == 'repo'
1249 assert actual['roles'][2].src == 'https://github.com/user/repo'
1250
1251
1252 @pytest.mark.parametrize('requirements_file', ["""
1253 - username.role
1254 - include: missing.yml
1255 """], indirect=True)
1256 def test_parse_requirements_roles_with_include_missing(requirements_cli, requirements_file):
1257 expected = "Failed to find include requirements file 'missing.yml' in '%s'" % to_native(requirements_file)
1258
1259 with pytest.raises(AnsibleError, match=expected):
1260 requirements_cli._parse_requirements_file(requirements_file)
1261
1262
1263 @pytest.mark.parametrize('requirements_file', ["""
1264 collections:
1265 - namespace.name
1266 roles:
1267 - namespace.name
1268 """], indirect=True)
1269 def test_install_implicit_role_with_collections(requirements_file, monkeypatch):
1270 mock_collection_install = MagicMock()
1271 monkeypatch.setattr(GalaxyCLI, '_execute_install_collection', mock_collection_install)
1272 mock_role_install = MagicMock()
1273 monkeypatch.setattr(GalaxyCLI, '_execute_install_role', mock_role_install)
1274
1275 mock_display = MagicMock()
1276 monkeypatch.setattr(Display, 'display', mock_display)
1277
1278 cli = GalaxyCLI(args=['ansible-galaxy', 'install', '-r', requirements_file])
1279 cli.run()
1280
1281 assert mock_collection_install.call_count == 1
1282 requirements = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in mock_collection_install.call_args[0][0]]
1283 assert requirements == [('namespace.name', '*', None, 'galaxy')]
1284 assert mock_collection_install.call_args[0][1] == cli._get_default_collection_path()
1285
1286 assert mock_role_install.call_count == 1
1287 assert len(mock_role_install.call_args[0][0]) == 1
1288 assert str(mock_role_install.call_args[0][0][0]) == 'namespace.name'
1289
1290 assert not any(list('contains collections which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls))
1291
1292
1293 @pytest.mark.parametrize('requirements_file', ["""
1294 collections:
1295 - namespace.name
1296 roles:
1297 - namespace.name
1298 """], indirect=True)
1299 def test_install_explicit_role_with_collections(requirements_file, monkeypatch):
1300 mock_collection_install = MagicMock()
1301 monkeypatch.setattr(GalaxyCLI, '_execute_install_collection', mock_collection_install)
1302 mock_role_install = MagicMock()
1303 monkeypatch.setattr(GalaxyCLI, '_execute_install_role', mock_role_install)
1304
1305 mock_display = MagicMock()
1306 monkeypatch.setattr(Display, 'vvv', mock_display)
1307
1308 cli = GalaxyCLI(args=['ansible-galaxy', 'role', 'install', '-r', requirements_file])
1309 cli.run()
1310
1311 assert mock_collection_install.call_count == 0
1312
1313 assert mock_role_install.call_count == 1
1314 assert len(mock_role_install.call_args[0][0]) == 1
1315 assert str(mock_role_install.call_args[0][0][0]) == 'namespace.name'
1316
1317 assert any(list('contains collections which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls))
1318
1319
1320 @pytest.mark.parametrize('requirements_file', ["""
1321 collections:
1322 - namespace.name
1323 roles:
1324 - namespace.name
1325 """], indirect=True)
1326 def test_install_role_with_collections_and_path(requirements_file, monkeypatch):
1327 mock_collection_install = MagicMock()
1328 monkeypatch.setattr(GalaxyCLI, '_execute_install_collection', mock_collection_install)
1329 mock_role_install = MagicMock()
1330 monkeypatch.setattr(GalaxyCLI, '_execute_install_role', mock_role_install)
1331
1332 mock_display = MagicMock()
1333 monkeypatch.setattr(Display, 'warning', mock_display)
1334
1335 cli = GalaxyCLI(args=['ansible-galaxy', 'install', '-p', 'path', '-r', requirements_file])
1336 cli.run()
1337
1338 assert mock_collection_install.call_count == 0
1339
1340 assert mock_role_install.call_count == 1
1341 assert len(mock_role_install.call_args[0][0]) == 1
1342 assert str(mock_role_install.call_args[0][0][0]) == 'namespace.name'
1343
1344 assert any(list('contains collections which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls))
1345
1346
1347 @pytest.mark.parametrize('requirements_file', ["""
1348 collections:
1349 - namespace.name
1350 roles:
1351 - namespace.name
1352 """], indirect=True)
1353 def test_install_collection_with_roles(requirements_file, monkeypatch):
1354 mock_collection_install = MagicMock()
1355 monkeypatch.setattr(GalaxyCLI, '_execute_install_collection', mock_collection_install)
1356 mock_role_install = MagicMock()
1357 monkeypatch.setattr(GalaxyCLI, '_execute_install_role', mock_role_install)
1358
1359 mock_display = MagicMock()
1360 monkeypatch.setattr(Display, 'vvv', mock_display)
1361
1362 cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'install', '-r', requirements_file])
1363 cli.run()
1364
1365 assert mock_collection_install.call_count == 1
1366 requirements = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in mock_collection_install.call_args[0][0]]
1367 assert requirements == [('namespace.name', '*', None, 'galaxy')]
1368
1369 assert mock_role_install.call_count == 0
1370
1371 assert any(list('contains roles which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls))