diff options
Diffstat (limited to 'test/units/cli/test_galaxy.py')
-rw-r--r-- | test/units/cli/test_galaxy.py | 110 |
1 files changed, 56 insertions, 54 deletions
diff --git a/test/units/cli/test_galaxy.py b/test/units/cli/test_galaxy.py index 8ff56408..80a2dfae 100644 --- a/test/units/cli/test_galaxy.py +++ b/test/units/cli/test_galaxy.py @@ -20,6 +20,8 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type +import contextlib + import ansible from io import BytesIO import json @@ -37,7 +39,7 @@ from ansible.cli.galaxy import GalaxyCLI from ansible.galaxy import collection from ansible.galaxy.api import GalaxyAPI from ansible.errors import AnsibleError -from ansible.module_utils._text import to_bytes, to_native, to_text +from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text from ansible.utils import context_objects as co from ansible.utils.display import Display from units.compat import unittest @@ -60,8 +62,7 @@ class TestGalaxy(unittest.TestCase): cls.temp_dir = tempfile.mkdtemp(prefix='ansible-test_galaxy-') os.chdir(cls.temp_dir) - if os.path.exists("./delete_me"): - shutil.rmtree("./delete_me") + shutil.rmtree("./delete_me", ignore_errors=True) # creating framework for a role gc = GalaxyCLI(args=["ansible-galaxy", "init", "--offline", "delete_me"]) @@ -71,8 +72,7 @@ class TestGalaxy(unittest.TestCase): # making a temp dir for role installation cls.role_path = os.path.join(tempfile.mkdtemp(), "roles") - if not os.path.isdir(cls.role_path): - os.makedirs(cls.role_path) + os.makedirs(cls.role_path) # creating a tar file name for class data cls.role_tar = './delete_me.tar.gz' @@ -80,37 +80,29 @@ class TestGalaxy(unittest.TestCase): # creating a temp file with installation requirements cls.role_req = './delete_me_requirements.yml' - fd = open(cls.role_req, "w") - fd.write("- 'src': '%s'\n 'name': '%s'\n 'path': '%s'" % (cls.role_tar, cls.role_name, cls.role_path)) - fd.close() + with open(cls.role_req, "w") as fd: + fd.write("- 'src': '%s'\n 'name': '%s'\n 'path': '%s'" % (cls.role_tar, cls.role_name, cls.role_path)) @classmethod def makeTar(cls, output_file, source_dir): ''' used for making a tarfile from a role directory ''' # adding directory into a tar file - try: - tar = tarfile.open(output_file, "w:gz") + with tarfile.open(output_file, "w:gz") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) - except AttributeError: # tarfile obj. has no attribute __exit__ prior to python 2. 7 - pass - finally: # ensuring closure of tarfile obj - tar.close() @classmethod def tearDownClass(cls): '''After tests are finished removes things created in setUpClass''' # deleting the temp role directory - if os.path.exists(cls.role_dir): - shutil.rmtree(cls.role_dir) - if os.path.exists(cls.role_req): + shutil.rmtree(cls.role_dir, ignore_errors=True) + with contextlib.suppress(FileNotFoundError): os.remove(cls.role_req) - if os.path.exists(cls.role_tar): + with contextlib.suppress(FileNotFoundError): os.remove(cls.role_tar) - if os.path.isdir(cls.role_path): - shutil.rmtree(cls.role_path) + shutil.rmtree(cls.role_path, ignore_errors=True) os.chdir('/') - shutil.rmtree(cls.temp_dir) + shutil.rmtree(cls.temp_dir, ignore_errors=True) def setUp(self): # Reset the stored command line args @@ -137,8 +129,7 @@ class TestGalaxy(unittest.TestCase): role_info = {'name': 'some_role_name', 'galaxy_info': galaxy_info} display_result = gc._display_role_info(role_info) - if display_result.find('\n\tgalaxy_info:') == -1: - self.fail('Expected galaxy_info to be indented once') + self.assertNotEqual(display_result.find('\n\tgalaxy_info:'), -1, 'Expected galaxy_info to be indented once') def test_run(self): ''' verifies that the GalaxyCLI object's api is created and that execute() is called. ''' @@ -176,7 +167,9 @@ class TestGalaxy(unittest.TestCase): with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display: # testing that error expected is raised self.assertRaises(AnsibleError, gc.run) - self.assertTrue(mocked_display.called_once_with("- downloading role 'fake_role_name', owned by ")) + assert mocked_display.call_count == 2 + assert mocked_display.mock_calls[0].args[0] == "Starting galaxy role install process" + assert "fake_role_name was NOT installed successfully" in mocked_display.mock_calls[1].args[0] def test_exit_without_ignore_with_flag(self): ''' tests that GalaxyCLI exits without the error specified if the --ignore-errors flag is used ''' @@ -184,7 +177,9 @@ class TestGalaxy(unittest.TestCase): gc = GalaxyCLI(args=["ansible-galaxy", "install", "--server=None", "fake_role_name", "--ignore-errors"]) with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display: gc.run() - self.assertTrue(mocked_display.called_once_with("- downloading role 'fake_role_name', owned by ")) + assert mocked_display.call_count == 2 + assert mocked_display.mock_calls[0].args[0] == "Starting galaxy role install process" + assert "fake_role_name was NOT installed successfully" in mocked_display.mock_calls[1].args[0] def test_parse_no_action(self): ''' testing the options parser when no action is given ''' @@ -277,8 +272,6 @@ class ValidRoleTests(object): # Make temp directory for testing cls.test_dir = tempfile.mkdtemp() - if not os.path.isdir(cls.test_dir): - os.makedirs(cls.test_dir) cls.role_dir = os.path.join(cls.test_dir, role_name) cls.role_name = role_name @@ -297,9 +290,8 @@ class ValidRoleTests(object): cls.role_skeleton_path = gc.galaxy.default_role_skeleton_path @classmethod - def tearDownClass(cls): - if os.path.isdir(cls.test_dir): - shutil.rmtree(cls.test_dir) + def tearDownRole(cls): + shutil.rmtree(cls.test_dir, ignore_errors=True) def test_metadata(self): with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf: @@ -349,6 +341,10 @@ class TestGalaxyInitDefault(unittest.TestCase, ValidRoleTests): def setUpClass(cls): cls.setUpRole(role_name='delete_me') + @classmethod + def tearDownClass(cls): + cls.tearDownRole() + def test_metadata_contents(self): with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf: metadata = yaml.safe_load(mf) @@ -361,6 +357,10 @@ class TestGalaxyInitAPB(unittest.TestCase, ValidRoleTests): def setUpClass(cls): cls.setUpRole('delete_me_apb', galaxy_args=['--type=apb']) + @classmethod + def tearDownClass(cls): + cls.tearDownRole() + def test_metadata_apb_tag(self): with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf: metadata = yaml.safe_load(mf) @@ -391,6 +391,10 @@ class TestGalaxyInitContainer(unittest.TestCase, ValidRoleTests): def setUpClass(cls): cls.setUpRole('delete_me_container', galaxy_args=['--type=container']) + @classmethod + def tearDownClass(cls): + cls.tearDownRole() + def test_metadata_container_tag(self): with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf: metadata = yaml.safe_load(mf) @@ -422,6 +426,10 @@ class TestGalaxyInitSkeleton(unittest.TestCase, ValidRoleTests): role_skeleton_path = os.path.join(os.path.split(__file__)[0], 'test_data', 'role_skeleton') cls.setUpRole('delete_me_skeleton', skeleton_path=role_skeleton_path, use_explicit_type=True) + @classmethod + def tearDownClass(cls): + cls.tearDownRole() + def test_empty_files_dir(self): files_dir = os.path.join(self.role_dir, 'files') self.assertTrue(os.path.isdir(files_dir)) @@ -763,6 +771,20 @@ def test_collection_install_with_names(collection_install): assert mock_install.call_args[0][6] is False # force_deps +def test_collection_install_with_invalid_requirements_format(collection_install): + output_dir = collection_install[2] + + requirements_file = os.path.join(output_dir, 'requirements.yml') + with open(requirements_file, 'wb') as req_obj: + req_obj.write(b'"invalid"') + + galaxy_args = ['ansible-galaxy', 'collection', 'install', '--requirements-file', requirements_file, + '--collections-path', output_dir] + + with pytest.raises(AnsibleError, match="Expecting requirements yaml to be a list or dictionary but got str"): + GalaxyCLI(args=galaxy_args).run() + + def test_collection_install_with_requirements_file(collection_install): mock_install, mock_warning, output_dir = collection_install @@ -1242,12 +1264,7 @@ def test_install_implicit_role_with_collections(requirements_file, monkeypatch): assert len(mock_role_install.call_args[0][0]) == 1 assert str(mock_role_install.call_args[0][0][0]) == 'namespace.name' - found = False - for mock_call in mock_display.mock_calls: - if 'contains collections which will be ignored' in mock_call[1][0]: - found = True - break - assert not found + assert not any(list('contains collections which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls)) @pytest.mark.parametrize('requirements_file', [''' @@ -1274,12 +1291,7 @@ def test_install_explicit_role_with_collections(requirements_file, monkeypatch): assert len(mock_role_install.call_args[0][0]) == 1 assert str(mock_role_install.call_args[0][0][0]) == 'namespace.name' - found = False - for mock_call in mock_display.mock_calls: - if 'contains collections which will be ignored' in mock_call[1][0]: - found = True - break - assert found + assert any(list('contains collections which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls)) @pytest.mark.parametrize('requirements_file', [''' @@ -1306,12 +1318,7 @@ def test_install_role_with_collections_and_path(requirements_file, monkeypatch): assert len(mock_role_install.call_args[0][0]) == 1 assert str(mock_role_install.call_args[0][0][0]) == 'namespace.name' - found = False - for mock_call in mock_display.mock_calls: - if 'contains collections which will be ignored' in mock_call[1][0]: - found = True - break - assert found + assert any(list('contains collections which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls)) @pytest.mark.parametrize('requirements_file', [''' @@ -1338,9 +1345,4 @@ def test_install_collection_with_roles(requirements_file, monkeypatch): assert mock_role_install.call_count == 0 - found = False - for mock_call in mock_display.mock_calls: - if 'contains roles which will be ignored' in mock_call[1][0]: - found = True - break - assert found + assert any(list('contains roles which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls)) |