diff --git a/test/sanity/ignore.txt b/test/sanity/ignore.txt index d4c908877b0..c50bd9dc5a7 100644 --- a/test/sanity/ignore.txt +++ b/test/sanity/ignore.txt @@ -228,7 +228,6 @@ test/units/module_utils/urls/test_Request.py replace-urlopen test/units/parsing/vault/test_vault.py pylint:disallowed-name test/units/playbook/role/test_role.py pylint:disallowed-name test/units/plugins/test_plugins.py pylint:disallowed-name -test/units/template/test_templar.py pylint:disallowed-name test/units/utils/collection_loader/fixtures/collections/ansible_collections/testns/testcoll/plugins/action/my_action.py pylint:relative-beyond-top-level test/units/utils/collection_loader/fixtures/collections/ansible_collections/testns/testcoll/plugins/modules/__init__.py empty-init # testing that collections don't need inits test/units/utils/collection_loader/fixtures/collections_masked/ansible_collections/ansible/__init__.py empty-init # testing that collections don't need inits diff --git a/test/units/cli/arguments/test_optparse_helpers.py b/test/units/cli/arguments/test_optparse_helpers.py index 082c9be4dc9..ae8e8d73ec9 100644 --- a/test/units/cli/arguments/test_optparse_helpers.py +++ b/test/units/cli/arguments/test_optparse_helpers.py @@ -14,10 +14,7 @@ from ansible.cli.arguments import option_helpers as opt_help from ansible import __path__ as ansible_path from ansible.release import __version__ as ansible_version -if C.DEFAULT_MODULE_PATH is None: - cpath = u'Default w/o overrides' -else: - cpath = C.DEFAULT_MODULE_PATH +cpath = C.DEFAULT_MODULE_PATH FAKE_PROG = u'ansible-cli-test' VERSION_OUTPUT = opt_help.version(prog=FAKE_PROG) diff --git a/test/units/cli/test_adhoc.py b/test/units/cli/test_adhoc.py index 4a975569be7..7bcca4714a1 100644 --- a/test/units/cli/test_adhoc.py +++ b/test/units/cli/test_adhoc.py @@ -98,11 +98,7 @@ def test_ansible_version(capsys): with pytest.raises(SystemExit): adhoc_cli.run() version = capsys.readouterr() - try: - version_lines = version.out.splitlines() - except AttributeError: - # Python 2.6 does return a named tuple, so get the first item - version_lines = version[0].splitlines() + version_lines = version.out.splitlines() assert len(version_lines) == 9, 'Incorrect number of lines in "ansible --version" output' assert re.match(r'ansible \[core [0-9.a-z]+\]', version_lines[0]), 'Incorrect ansible version line in "ansible --version" output' diff --git a/test/units/cli/test_galaxy.py b/test/units/cli/test_galaxy.py index 8ff564085ce..f0be9ebad87 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 @@ -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"]) @@ -88,29 +89,22 @@ class TestGalaxy(unittest.TestCase): 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 +131,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. ''' @@ -277,8 +270,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 @@ -298,8 +289,7 @@ class ValidRoleTests(object): @classmethod def tearDownClass(cls): - if os.path.isdir(cls.test_dir): - shutil.rmtree(cls.test_dir) + 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: diff --git a/test/units/executor/module_common/test_modify_module.py b/test/units/executor/module_common/test_modify_module.py index dceef76336d..a32d47c448f 100644 --- a/test/units/executor/module_common/test_modify_module.py +++ b/test/units/executor/module_common/test_modify_module.py @@ -8,7 +8,6 @@ __metaclass__ = type import pytest from ansible.executor.module_common import modify_module -from ansible.module_utils.six import PY2 from test_module_common import templar @@ -22,10 +21,7 @@ print('{"result": "%s"}' % sys.executable) @pytest.fixture def fake_old_module_open(mocker): m = mocker.mock_open(read_data=FAKE_OLD_MODULE) - if PY2: - mocker.patch('__builtin__.open', m) - else: - mocker.patch('builtins.open', m) + mocker.patch('builtins.open', m) # this test no longer makes sense, since a Python module will always either have interpreter discovery run or # an explicit interpreter passed (so we'll never default to the module shebang) diff --git a/test/units/executor/module_common/test_module_common.py b/test/units/executor/module_common/test_module_common.py index fa6add8cd61..c2c16125320 100644 --- a/test/units/executor/module_common/test_module_common.py +++ b/test/units/executor/module_common/test_module_common.py @@ -27,7 +27,6 @@ import ansible.errors from ansible.executor import module_common as amc from ansible.executor.interpreter_discovery import InterpreterDiscoveryRequiredError -from ansible.module_utils.six import PY2 class TestStripComments: @@ -80,19 +79,13 @@ class TestSlurp: def test_slurp_file(self, mocker): mocker.patch('os.path.exists', side_effect=lambda x: True) m = mocker.mock_open(read_data='This is a test') - if PY2: - mocker.patch('__builtin__.open', m) - else: - mocker.patch('builtins.open', m) + mocker.patch('builtins.open', m) assert amc._slurp('some_file') == 'This is a test' def test_slurp_file_with_newlines(self, mocker): mocker.patch('os.path.exists', side_effect=lambda x: True) m = mocker.mock_open(read_data='#!/usr/bin/python\ndef test(args):\nprint("hi")\n') - if PY2: - mocker.patch('__builtin__.open', m) - else: - mocker.patch('builtins.open', m) + mocker.patch('builtins.open', m) assert amc._slurp('some_file') == '#!/usr/bin/python\ndef test(args):\nprint("hi")\n' diff --git a/test/units/executor/test_play_iterator.py b/test/units/executor/test_play_iterator.py index 00c77fcf4b8..23301da0efb 100644 --- a/test/units/executor/test_play_iterator.py +++ b/test/units/executor/test_play_iterator.py @@ -433,8 +433,7 @@ class TestPlayIterator(unittest.TestCase): while (task and task.action != 'debug'): _, task = itr.get_next_task_for_host(hosts[0]) - if task is None: - raise Exception("iterated past end of play while looking for place to insert tasks") + self.assertIsNotNone(task, 'iterated past end of play while looking for place to insert tasks') # get the current host state and copy it so we can mutate it s = itr.get_host_state(hosts[0]) diff --git a/test/units/playbook/test_base.py b/test/units/playbook/test_base.py index d5810e73af9..f5559ad3606 100644 --- a/test/units/playbook/test_base.py +++ b/test/units/playbook/test_base.py @@ -26,8 +26,7 @@ from ansible.module_utils.six import string_types from ansible.playbook.attribute import FieldAttribute, NonInheritableFieldAttribute from ansible.template import Templar from ansible.playbook import base -from ansible.utils.unsafe_proxy import AnsibleUnsafeBytes, AnsibleUnsafeText -from ansible.utils.sentinel import Sentinel +from ansible.utils.unsafe_proxy import AnsibleUnsafeText from units.mock.loader import DictDataLoader @@ -331,12 +330,6 @@ class ExampleSubClass(base.Base): def __init__(self): super(ExampleSubClass, self).__init__() - def get_dep_chain(self): - if self._parent: - return self._parent.get_dep_chain() - else: - return None - class BaseSubClass(base.Base): name = FieldAttribute(isa='string', default='', always_post_validate=True) diff --git a/test/units/playbook/test_helpers.py b/test/units/playbook/test_helpers.py index e784312f9b3..15e229cae5e 100644 --- a/test/units/playbook/test_helpers.py +++ b/test/units/playbook/test_helpers.py @@ -52,10 +52,6 @@ class MixinForMocks(object): self.mock_inventory = MagicMock(name='MockInventory') self.mock_inventory._hosts_cache = dict() - def _get_host(host_name): - return None - - self.mock_inventory.get_host.side_effect = _get_host # TODO: can we use a real VariableManager? self.mock_variable_manager = MagicMock(name='MockVariableManager') self.mock_variable_manager.get_vars.return_value = dict() @@ -86,10 +82,6 @@ class TestLoadListOfTasks(unittest.TestCase, MixinForMocks): def setUp(self): self._setup() - def _assert_is_task_list(self, results): - for result in results: - self.assertIsInstance(result, Task) - def _assert_is_task_list_or_blocks(self, results): self.assertIsInstance(results, list) for result in results: diff --git a/test/units/template/test_templar.py b/test/units/template/test_templar.py index 146da0b40fc..53eba1d09ac 100644 --- a/test/units/template/test_templar.py +++ b/test/units/template/test_templar.py @@ -64,14 +64,6 @@ class BaseTemplar(object): return self._ansible_context._is_unsafe(obj) -# class used for testing arbitrary objects passed to template -class SomeClass(object): - foo = 'bar' - - def __init__(self): - self.blip = 'blip' - - class SomeUnsafeClass(AnsibleUnsafe): def __init__(self): super(SomeUnsafeClass, self).__init__() @@ -268,8 +260,6 @@ class TestTemplarMisc(BaseTemplar, unittest.TestCase): templar.available_variables = "foo=bam" except AssertionError: pass - except Exception as e: - self.fail(e) def test_templar_escape_backslashes(self): # Rule of thumb: If escape backslashes is True you should end up with