Remove unused and unreachable unit test code (#79854)

pull/79857/head
Matt Clay 2 years ago committed by GitHub
parent 1dce45c42d
commit c33c8cf086
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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/parsing/vault/test_vault.py pylint:disallowed-name
test/units/playbook/role/test_role.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/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/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/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 test/units/utils/collection_loader/fixtures/collections_masked/ansible_collections/ansible/__init__.py empty-init # testing that collections don't need inits

@ -14,9 +14,6 @@ from ansible.cli.arguments import option_helpers as opt_help
from ansible import __path__ as ansible_path from ansible import __path__ as ansible_path
from ansible.release import __version__ as ansible_version 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' FAKE_PROG = u'ansible-cli-test'

@ -98,11 +98,7 @@ def test_ansible_version(capsys):
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
adhoc_cli.run() adhoc_cli.run()
version = capsys.readouterr() version = capsys.readouterr()
try:
version_lines = version.out.splitlines() 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()
assert len(version_lines) == 9, 'Incorrect number of lines in "ansible --version" output' 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' assert re.match(r'ansible \[core [0-9.a-z]+\]', version_lines[0]), 'Incorrect ansible version line in "ansible --version" output'

@ -20,6 +20,8 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
import contextlib
import ansible import ansible
from io import BytesIO from io import BytesIO
import json import json
@ -60,8 +62,7 @@ class TestGalaxy(unittest.TestCase):
cls.temp_dir = tempfile.mkdtemp(prefix='ansible-test_galaxy-') cls.temp_dir = tempfile.mkdtemp(prefix='ansible-test_galaxy-')
os.chdir(cls.temp_dir) os.chdir(cls.temp_dir)
if os.path.exists("./delete_me"): shutil.rmtree("./delete_me", ignore_errors=True)
shutil.rmtree("./delete_me")
# creating framework for a role # creating framework for a role
gc = GalaxyCLI(args=["ansible-galaxy", "init", "--offline", "delete_me"]) gc = GalaxyCLI(args=["ansible-galaxy", "init", "--offline", "delete_me"])
@ -88,29 +89,22 @@ class TestGalaxy(unittest.TestCase):
def makeTar(cls, output_file, source_dir): def makeTar(cls, output_file, source_dir):
''' used for making a tarfile from a role directory ''' ''' used for making a tarfile from a role directory '''
# adding directory into a tar file # adding directory into a tar file
try: with tarfile.open(output_file, "w:gz") as tar:
tar = tarfile.open(output_file, "w:gz")
tar.add(source_dir, arcname=os.path.basename(source_dir)) 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 @classmethod
def tearDownClass(cls): def tearDownClass(cls):
'''After tests are finished removes things created in setUpClass''' '''After tests are finished removes things created in setUpClass'''
# deleting the temp role directory # deleting the temp role directory
if os.path.exists(cls.role_dir): shutil.rmtree(cls.role_dir, ignore_errors=True)
shutil.rmtree(cls.role_dir) with contextlib.suppress(FileNotFoundError):
if os.path.exists(cls.role_req):
os.remove(cls.role_req) os.remove(cls.role_req)
if os.path.exists(cls.role_tar): with contextlib.suppress(FileNotFoundError):
os.remove(cls.role_tar) os.remove(cls.role_tar)
if os.path.isdir(cls.role_path): shutil.rmtree(cls.role_path, ignore_errors=True)
shutil.rmtree(cls.role_path)
os.chdir('/') os.chdir('/')
shutil.rmtree(cls.temp_dir) shutil.rmtree(cls.temp_dir, ignore_errors=True)
def setUp(self): def setUp(self):
# Reset the stored command line args # Reset the stored command line args
@ -137,8 +131,7 @@ class TestGalaxy(unittest.TestCase):
role_info = {'name': 'some_role_name', role_info = {'name': 'some_role_name',
'galaxy_info': galaxy_info} 'galaxy_info': galaxy_info}
display_result = gc._display_role_info(role_info) display_result = gc._display_role_info(role_info)
if display_result.find('\n\tgalaxy_info:') == -1: self.assertNotEqual(display_result.find('\n\tgalaxy_info:'), -1, 'Expected galaxy_info to be indented once')
self.fail('Expected galaxy_info to be indented once')
def test_run(self): def test_run(self):
''' verifies that the GalaxyCLI object's api is created and that execute() is called. ''' ''' 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 # Make temp directory for testing
cls.test_dir = tempfile.mkdtemp() 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_dir = os.path.join(cls.test_dir, role_name)
cls.role_name = role_name cls.role_name = role_name
@ -298,8 +289,7 @@ class ValidRoleTests(object):
@classmethod @classmethod
def tearDownClass(cls): def tearDownClass(cls):
if os.path.isdir(cls.test_dir): shutil.rmtree(cls.test_dir, ignore_errors=True)
shutil.rmtree(cls.test_dir)
def test_metadata(self): def test_metadata(self):
with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf: with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:

@ -8,7 +8,6 @@ __metaclass__ = type
import pytest import pytest
from ansible.executor.module_common import modify_module from ansible.executor.module_common import modify_module
from ansible.module_utils.six import PY2
from test_module_common import templar from test_module_common import templar
@ -22,9 +21,6 @@ print('{"result": "%s"}' % sys.executable)
@pytest.fixture @pytest.fixture
def fake_old_module_open(mocker): def fake_old_module_open(mocker):
m = mocker.mock_open(read_data=FAKE_OLD_MODULE) 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 # this test no longer makes sense, since a Python module will always either have interpreter discovery run or

@ -27,7 +27,6 @@ import ansible.errors
from ansible.executor import module_common as amc from ansible.executor import module_common as amc
from ansible.executor.interpreter_discovery import InterpreterDiscoveryRequiredError from ansible.executor.interpreter_discovery import InterpreterDiscoveryRequiredError
from ansible.module_utils.six import PY2
class TestStripComments: class TestStripComments:
@ -80,18 +79,12 @@ class TestSlurp:
def test_slurp_file(self, mocker): def test_slurp_file(self, mocker):
mocker.patch('os.path.exists', side_effect=lambda x: True) mocker.patch('os.path.exists', side_effect=lambda x: True)
m = mocker.mock_open(read_data='This is a test') 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' assert amc._slurp('some_file') == 'This is a test'
def test_slurp_file_with_newlines(self, mocker): def test_slurp_file_with_newlines(self, mocker):
mocker.patch('os.path.exists', side_effect=lambda x: True) 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') 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' assert amc._slurp('some_file') == '#!/usr/bin/python\ndef test(args):\nprint("hi")\n'

@ -433,8 +433,7 @@ class TestPlayIterator(unittest.TestCase):
while (task and task.action != 'debug'): while (task and task.action != 'debug'):
_, task = itr.get_next_task_for_host(hosts[0]) _, task = itr.get_next_task_for_host(hosts[0])
if task is None: self.assertIsNotNone(task, 'iterated past end of play while looking for place to insert tasks')
raise Exception("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 # get the current host state and copy it so we can mutate it
s = itr.get_host_state(hosts[0]) s = itr.get_host_state(hosts[0])

@ -26,8 +26,7 @@ from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttribute, NonInheritableFieldAttribute from ansible.playbook.attribute import FieldAttribute, NonInheritableFieldAttribute
from ansible.template import Templar from ansible.template import Templar
from ansible.playbook import base from ansible.playbook import base
from ansible.utils.unsafe_proxy import AnsibleUnsafeBytes, AnsibleUnsafeText from ansible.utils.unsafe_proxy import AnsibleUnsafeText
from ansible.utils.sentinel import Sentinel
from units.mock.loader import DictDataLoader from units.mock.loader import DictDataLoader
@ -331,12 +330,6 @@ class ExampleSubClass(base.Base):
def __init__(self): def __init__(self):
super(ExampleSubClass, self).__init__() 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): class BaseSubClass(base.Base):
name = FieldAttribute(isa='string', default='', always_post_validate=True) name = FieldAttribute(isa='string', default='', always_post_validate=True)

@ -52,10 +52,6 @@ class MixinForMocks(object):
self.mock_inventory = MagicMock(name='MockInventory') self.mock_inventory = MagicMock(name='MockInventory')
self.mock_inventory._hosts_cache = dict() 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? # TODO: can we use a real VariableManager?
self.mock_variable_manager = MagicMock(name='MockVariableManager') self.mock_variable_manager = MagicMock(name='MockVariableManager')
self.mock_variable_manager.get_vars.return_value = dict() self.mock_variable_manager.get_vars.return_value = dict()
@ -86,10 +82,6 @@ class TestLoadListOfTasks(unittest.TestCase, MixinForMocks):
def setUp(self): def setUp(self):
self._setup() 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): def _assert_is_task_list_or_blocks(self, results):
self.assertIsInstance(results, list) self.assertIsInstance(results, list)
for result in results: for result in results:

@ -64,14 +64,6 @@ class BaseTemplar(object):
return self._ansible_context._is_unsafe(obj) 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): class SomeUnsafeClass(AnsibleUnsafe):
def __init__(self): def __init__(self):
super(SomeUnsafeClass, self).__init__() super(SomeUnsafeClass, self).__init__()
@ -268,8 +260,6 @@ class TestTemplarMisc(BaseTemplar, unittest.TestCase):
templar.available_variables = "foo=bam" templar.available_variables = "foo=bam"
except AssertionError: except AssertionError:
pass pass
except Exception as e:
self.fail(e)
def test_templar_escape_backslashes(self): def test_templar_escape_backslashes(self):
# Rule of thumb: If escape backslashes is True you should end up with # Rule of thumb: If escape backslashes is True you should end up with

Loading…
Cancel
Save