diff options
Diffstat (limited to 'functest/tests/unit')
44 files changed, 1655 insertions, 6379 deletions
diff --git a/functest/tests/unit/ci/test_check_deployment.py b/functest/tests/unit/ci/test_check_deployment.py deleted file mode 100644 index fc6368e5a..000000000 --- a/functest/tests/unit/ci/test_check_deployment.py +++ /dev/null @@ -1,199 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2017 Ericsson and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -import logging -import mock -import unittest - -from functest.ci import check_deployment - -__author__ = "Jose Lausuch <jose.lausuch@ericsson.com>" - - -class CheckDeploymentTesting(unittest.TestCase): - """The super class which testing classes could inherit.""" - # pylint: disable=missing-docstring - - logging.disable(logging.CRITICAL) - - def setUp(self): - self.client_test = mock.Mock() - self.deployment = check_deployment.CheckDeployment() - self.service_test = 'compute' - self.rc_file = self.deployment.rc_file - self.endpoint_test = 'http://192.168.0.6:5000/v3' - creds_attr = {'auth_url': self.endpoint_test, - 'proxy_settings': ''} - proxy_attr = {'host': '192.168.0.1', 'port': '5000'} - proxy_settings = mock.Mock() - proxy_settings.configure_mock(**proxy_attr) - self.os_creds = mock.Mock() - self.os_creds.configure_mock(**creds_attr) - self.os_creds.proxy_settings = proxy_settings - self.deployment.os_creds = self.os_creds - - def test_check_rc(self): - with mock.patch('functest.ci.check_deployment.os.path.isfile', - returns=True) as m, \ - mock.patch('six.moves.builtins.open', - mock.mock_open(read_data='OS_AUTH_URL')): - self.deployment.check_rc() - self.assertTrue(m.called) - - def test_check_rc_missing_file(self): - with mock.patch('functest.ci.check_deployment.os.path.isfile', - return_value=False), \ - self.assertRaises(Exception) as context: - msg = 'RC file {} does not exist!'.format(self.rc_file) - self.deployment.check_rc(self.rc_file) - self.assertTrue(msg in context) - - def test_check_rc_missing_os_auth(self): - with mock.patch('six.moves.builtins.open', - mock.mock_open(read_data='test')), \ - self.assertRaises(Exception) as context: - msg = 'OS_AUTH_URL not defined in {}.'.format(self.rc_file) - self.assertTrue(msg in context) - - def test_check_auth_endpoint(self): - with mock.patch('functest.ci.check_deployment.verify_connectivity', - return_value=True) as m,\ - mock.patch('functest.ci.check_deployment.get_auth_token', - return_value='gAAAAABaOhXGS') as mock_token: - self.deployment.check_auth_endpoint() - self.assertTrue(m.called) - self.assertTrue(mock_token.called) - - def test_check_auth_endpoint_not_reachable(self): - with mock.patch('functest.ci.check_deployment.verify_connectivity', - return_value=False) as m, \ - self.assertRaises(Exception) as context: - endpoint = self.os_creds.auth_url - self.deployment.check_auth_endpoint() - msg = "OS_AUTH_URL {} is not reachable.".format(endpoint) - self.assertTrue(m.called) - self.assertTrue(msg in context) - - def test_check_public_endpoint(self): - with mock.patch('functest.ci.check_deployment.verify_connectivity', - return_value=True) as m, \ - mock.patch('functest.ci.check_deployment.keystone_utils.' - 'get_endpoint') as n: - self.deployment.check_public_endpoint() - self.assertTrue(m.called) - self.assertTrue(n.called) - - def test_check_public_endpoint_not_reachable(self): - with mock.patch('functest.ci.check_deployment.verify_connectivity', - return_value=False) as m, \ - mock.patch('functest.ci.check_deployment.keystone_utils.' - 'get_endpoint', - return_value=self.endpoint_test) as n, \ - self.assertRaises(Exception) as context: - self.deployment.check_public_endpoint() - msg = ("Public endpoint {} is not reachable." - .format(self.mock_endpoint)) - self.assertTrue(m.called) - self.assertTrue(n.called) - self.assertTrue(msg in context) - - def test_check_service_endpoint(self): - with mock.patch('functest.ci.check_deployment.verify_connectivity', - return_value=True) as m, \ - mock.patch('functest.ci.check_deployment.keystone_utils.' - 'get_endpoint') as n: - self.deployment.check_service_endpoint(self.service_test) - self.assertTrue(m.called) - self.assertTrue(n.called) - - def test_check_service_endpoint_not_reachable(self): - with mock.patch('functest.ci.check_deployment.verify_connectivity', - return_value=False) as m, \ - mock.patch('functest.ci.check_deployment.keystone_utils.' - 'get_endpoint', - return_value=self.endpoint_test) as n, \ - self.assertRaises(Exception) as context: - self.deployment.check_service_endpoint(self.service_test) - msg = "{} endpoint {} is not reachable.".format(self.service_test, - self.endpoint_test) - self.assertTrue(m.called) - self.assertTrue(n.called) - self.assertTrue(msg in context) - - def test_check_nova(self): - with mock.patch('functest.ci.check_deployment.nova_utils.nova_client', - return_value=self.client_test) as m: - self.deployment.check_nova() - self.assertTrue(m.called) - - def test_check_nova_fail(self): - with mock.patch('functest.ci.check_deployment.nova_utils.nova_client', - return_value=self.client_test) as m, \ - mock.patch.object(self.client_test, 'servers.list', - side_effect=Exception): - self.deployment.check_nova() - self.assertTrue(m.called) - self.assertRaises(Exception) - - def test_check_neutron(self): - with mock.patch('functest.ci.check_deployment.neutron_utils.' - 'neutron_client', return_value=self.client_test) as m: - self.deployment.check_neutron() - self.assertTrue(m.called) - - def test_check_neutron_fail(self): - with mock.patch('functest.ci.check_deployment.neutron_utils.' - 'neutron_client', - return_value=self.client_test) as m, \ - mock.patch.object(self.client_test, 'list_networks', - side_effect=Exception), \ - self.assertRaises(Exception): - self.deployment.check_neutron() - self.assertRaises(Exception) - self.assertTrue(m.called) - - def test_check_glance(self): - with mock.patch('functest.ci.check_deployment.glance_utils.' - 'glance_client', return_value=self.client_test) as m: - self.deployment.check_glance() - self.assertTrue(m.called) - - def test_check_glance_fail(self): - with mock.patch('functest.ci.check_deployment.glance_utils.' - 'glance_client', return_value=self.client_test) as m, \ - mock.patch.object(self.client_test, 'images.list', - side_effect=Exception): - self.deployment.check_glance() - self.assertRaises(Exception) - self.assertTrue(m.called) - - @mock.patch('functest.ci.check_deployment.LOGGER.info') - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_ext_net_name') - def test_check_extnet(self, mock_getext, mock_loginfo): - test_network = 'ext-net' - mock_getext.return_value = test_network - self.deployment.check_ext_net() - self.assertTrue(mock_getext.called) - mock_loginfo.assert_called_once_with( - "External network found: %s", test_network) - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_ext_net_name', return_value='') - def test_check_extnet_None(self, mock_getext): - with self.assertRaises(Exception) as context: - self.deployment.check_ext_net() - self.assertTrue(mock_getext.called) - msg = 'ERROR: No external networks in the deployment.' - self.assertTrue(msg in context) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/ci/test_run_tests.py b/functest/tests/unit/ci/test_run_tests.py deleted file mode 100644 index 93cbfccdf..000000000 --- a/functest/tests/unit/ci/test_run_tests.py +++ /dev/null @@ -1,250 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -import logging -import unittest - -import mock - -from functest.ci import run_tests -from functest.utils.constants import CONST -from functest.core.testcase import TestCase - - -class FakeModule(TestCase): - - def run(self): - return TestCase.EX_OK - - def push_to_db(self): - return TestCase.EX_OK - - def is_successful(self): - return TestCase.EX_OK - - -class RunTestsTesting(unittest.TestCase): - - def setUp(self): - self.runner = run_tests.Runner() - mock_test_case = mock.Mock() - mock_test_case.is_successful.return_value = TestCase.EX_OK - self.runner.executed_test_cases['test1'] = mock_test_case - self.runner.executed_test_cases['test2'] = mock_test_case - self.sep = 'test_sep' - self.creds = {'OS_AUTH_URL': 'http://test_ip:test_port/v2.0', - 'OS_USERNAME': 'test_os_username', - 'OS_TENANT_NAME': 'test_tenant', - 'OS_PASSWORD': 'test_password'} - self.test = {'test_name': 'test_name'} - self.tier = mock.Mock() - test1 = mock.Mock() - test1.get_name.return_value = 'test1' - test2 = mock.Mock() - test2.get_name.return_value = 'test2' - attrs = {'get_name.return_value': 'test_tier', - 'get_tests.return_value': [test1, test2], - 'get_ci_loop.return_value': 'test_ci_loop', - 'get_test_names.return_value': ['test1', 'test2']} - self.tier.configure_mock(**attrs) - - self.tiers = mock.Mock() - attrs = {'get_tiers.return_value': [self.tier]} - self.tiers.configure_mock(**attrs) - - self.run_tests_parser = run_tests.RunTestsParser() - - @mock.patch('functest.ci.run_tests.LOGGER.error') - def test_source_rc_file_missing_file(self, mock_logger_error): - with mock.patch('functest.ci.run_tests.os.path.isfile', - return_value=False), \ - self.assertRaises(Exception): - self.runner.source_rc_file() - - @mock.patch('functest.ci.run_tests.LOGGER.debug') - @mock.patch('functest.ci.run_tests.os.path.isfile', - return_value=True) - def test_source_rc_file_default(self, *args): - with mock.patch('functest.ci.run_tests.os_utils.source_credentials', - return_value=self.creds): - self.runner.source_rc_file() - - def test_get_run_dict_if_defined_default(self): - mock_obj = mock.Mock() - with mock.patch('functest.ci.run_tests.' - 'ft_utils.get_dict_by_test', - return_value={'run': mock_obj}): - self.assertEqual(self.runner.get_run_dict('test_name'), - mock_obj) - - @mock.patch('functest.ci.run_tests.LOGGER.error') - def test_get_run_dict_if_defined_missing_config_option(self, - mock_logger_error): - with mock.patch('functest.ci.run_tests.' - 'ft_utils.get_dict_by_test', - return_value=None): - testname = 'test_name' - self.assertEqual(self.runner.get_run_dict(testname), - None) - mock_logger_error.assert_called_once_with( - "Cannot get %s's config options", testname) - - with mock.patch('functest.ci.run_tests.' - 'ft_utils.get_dict_by_test', - return_value={}): - testname = 'test_name' - self.assertEqual(self.runner.get_run_dict(testname), - None) - - @mock.patch('functest.ci.run_tests.LOGGER.exception') - def test_get_run_dict_if_defined_exception(self, - mock_logger_except): - with mock.patch('functest.ci.run_tests.' - 'ft_utils.get_dict_by_test', - side_effect=Exception): - testname = 'test_name' - self.assertEqual(self.runner.get_run_dict(testname), - None) - mock_logger_except.assert_called_once_with( - "Cannot get %s's config options", testname) - - def test_run_tests_import_test_class_exception(self): - mock_test = mock.Mock() - args = {'get_name.return_value': 'test_name', - 'needs_clean.return_value': False} - mock_test.configure_mock(**args) - with mock.patch('functest.ci.run_tests.Runner.source_rc_file'), \ - mock.patch('functest.ci.run_tests.Runner.get_run_dict', - return_value=None), \ - self.assertRaises(Exception) as context: - self.runner(mock_test, 'tier_name') - msg = "Cannot import the class for the test case." - self.assertTrue(msg in context) - - @mock.patch('functest.ci.run_tests.Runner.source_rc_file') - @mock.patch('importlib.import_module', name="module", - return_value=mock.Mock(test_class=mock.Mock( - side_effect=FakeModule))) - @mock.patch('functest.utils.functest_utils.get_dict_by_test') - def test_run_tests_default(self, *args): - mock_test = mock.Mock() - kwargs = {'get_name.return_value': 'test_name', - 'needs_clean.return_value': True} - mock_test.configure_mock(**kwargs) - test_run_dict = {'module': 'test_module', - 'class': 'test_class'} - with mock.patch('functest.ci.run_tests.Runner.get_run_dict', - return_value=test_run_dict): - self.runner.clean_flag = True - self.runner.run_test(mock_test) - self.assertEqual(self.runner.overall_result, - run_tests.Result.EX_OK) - - @mock.patch('functest.ci.run_tests.Runner.run_test', - return_value=TestCase.EX_OK) - def test_run_tier_default(self, *mock_methods): - self.assertEqual(self.runner.run_tier(self.tier), - run_tests.Result.EX_OK) - mock_methods[0].assert_called_with(mock.ANY) - - @mock.patch('functest.ci.run_tests.LOGGER.info') - def test_run_tier_missing_test(self, mock_logger_info): - self.tier.get_tests.return_value = None - self.assertEqual(self.runner.run_tier(self.tier), - run_tests.Result.EX_ERROR) - self.assertTrue(mock_logger_info.called) - - @mock.patch('functest.ci.run_tests.LOGGER.info') - @mock.patch('functest.ci.run_tests.Runner.run_tier') - @mock.patch('functest.ci.run_tests.Runner.summary') - def test_run_all_default(self, *mock_methods): - CONST.__setattr__('CI_LOOP', 'test_ci_loop') - self.runner.run_all() - mock_methods[1].assert_not_called() - self.assertTrue(mock_methods[2].called) - - @mock.patch('functest.ci.run_tests.LOGGER.info') - @mock.patch('functest.ci.run_tests.Runner.summary') - def test_run_all_missing_tier(self, *mock_methods): - CONST.__setattr__('CI_LOOP', 'loop_re_not_available') - self.runner.run_all() - self.assertTrue(mock_methods[1].called) - - @mock.patch('functest.ci.run_tests.Runner.source_rc_file', - side_effect=Exception) - @mock.patch('functest.ci.run_tests.Runner.summary') - def test_main_failed(self, *mock_methods): - kwargs = {'test': 'test_name', 'noclean': True, 'report': True} - args = {'get_tier.return_value': False, - 'get_test.return_value': False} - self.runner._tiers = mock.Mock() - self.runner._tiers.configure_mock(**args) - self.assertEqual(self.runner.main(**kwargs), - run_tests.Result.EX_ERROR) - mock_methods[1].assert_called_once_with() - - @mock.patch('functest.ci.run_tests.Runner.source_rc_file') - @mock.patch('functest.ci.run_tests.Runner.run_test', - return_value=TestCase.EX_OK) - @mock.patch('functest.ci.run_tests.Runner.summary') - def test_main_tier(self, *mock_methods): - mock_tier = mock.Mock() - test_mock = mock.Mock() - test_mock.get_name.return_value = 'test1' - args = {'get_name.return_value': 'tier_name', - 'get_tests.return_value': [test_mock]} - mock_tier.configure_mock(**args) - kwargs = {'test': 'tier_name', 'noclean': True, 'report': True} - args = {'get_tier.return_value': mock_tier, - 'get_test.return_value': None} - self.runner._tiers = mock.Mock() - self.runner._tiers.configure_mock(**args) - self.assertEqual(self.runner.main(**kwargs), - run_tests.Result.EX_OK) - mock_methods[1].assert_called() - - @mock.patch('functest.ci.run_tests.Runner.source_rc_file') - @mock.patch('functest.ci.run_tests.Runner.run_test', - return_value=TestCase.EX_OK) - def test_main_test(self, *mock_methods): - kwargs = {'test': 'test_name', 'noclean': True, 'report': True} - args = {'get_tier.return_value': None, - 'get_test.return_value': 'test_name'} - self.runner._tiers = mock.Mock() - self.runner._tiers.configure_mock(**args) - self.assertEqual(self.runner.main(**kwargs), - run_tests.Result.EX_OK) - mock_methods[0].assert_called_once_with('test_name') - - @mock.patch('functest.ci.run_tests.Runner.source_rc_file') - @mock.patch('functest.ci.run_tests.Runner.run_all') - @mock.patch('functest.ci.run_tests.Runner.summary') - def test_main_all_tier(self, *mock_methods): - kwargs = {'test': 'all', 'noclean': True, 'report': True} - args = {'get_tier.return_value': None, - 'get_test.return_value': None} - self.runner._tiers = mock.Mock() - self.runner._tiers.configure_mock(**args) - self.assertEqual(self.runner.main(**kwargs), - run_tests.Result.EX_OK) - mock_methods[1].assert_called_once_with() - - @mock.patch('functest.ci.run_tests.Runner.source_rc_file') - @mock.patch('functest.ci.run_tests.Runner.summary') - def test_main_any_tier_test_ko(self, *mock_methods): - kwargs = {'test': 'any', 'noclean': True, 'report': True} - args = {'get_tier.return_value': None, - 'get_test.return_value': None} - self.runner._tiers = mock.Mock() - self.runner._tiers.configure_mock(**args) - self.assertEqual(self.runner.main(**kwargs), - run_tests.Result.EX_ERROR) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/ci/test_tier_builder.py b/functest/tests/unit/ci/test_tier_builder.py deleted file mode 100644 index d832ca3f0..000000000 --- a/functest/tests/unit/ci/test_tier_builder.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -# pylint: disable=missing-docstring - -import logging -import unittest - -import mock - -from functest.ci import tier_builder - - -class TierBuilderTesting(unittest.TestCase): - - def setUp(self): - self.dependency = {'installer': 'test_installer', - 'scenario': 'test_scenario'} - - self.testcase = {'dependencies': self.dependency, - 'enabled': 'true', - 'case_name': 'test_name', - 'criteria': 'test_criteria', - 'blocking': 'test_blocking', - 'description': 'test_desc', - 'project_name': 'project_name'} - - self.dic_tier = {'name': 'test_tier', - 'order': 'test_order', - 'ci_loop': 'test_ci_loop', - 'description': 'test_desc', - 'testcases': [self.testcase]} - - self.mock_yaml = mock.Mock() - attrs = {'get.return_value': [self.dic_tier]} - self.mock_yaml.configure_mock(**attrs) - - with mock.patch('functest.ci.tier_builder.yaml.safe_load', - return_value=self.mock_yaml), \ - mock.patch('six.moves.builtins.open', mock.mock_open()): - self.tierbuilder = tier_builder.TierBuilder('test_installer', - 'test_scenario', - 'testcases_file') - self.tier_obj = self.tierbuilder.tier_objects[0] - - def test_get_tiers(self): - self.assertEqual(self.tierbuilder.get_tiers(), - [self.tier_obj]) - - def test_get_tier_names(self): - self.assertEqual(self.tierbuilder.get_tier_names(), - ['test_tier']) - - def test_get_tier_present_tier(self): - self.assertEqual(self.tierbuilder.get_tier('test_tier'), - self.tier_obj) - - def test_get_tier_missing_tier(self): - self.assertEqual(self.tierbuilder.get_tier('test_tier2'), - None) - - def test_get_test_present_test(self): - self.assertEqual(self.tierbuilder.get_test('test_name'), - self.tier_obj.get_test('test_name')) - - def test_get_test_missing_test(self): - self.assertEqual(self.tierbuilder.get_test('test_name2'), - None) - - def test_get_tests_present_tier(self): - self.assertEqual(self.tierbuilder.get_tests('test_tier'), - self.tier_obj.tests_array) - - def test_get_tests_missing_tier(self): - self.assertEqual(self.tierbuilder.get_tests('test_tier2'), - None) - - def test_get_tier_name_ok(self): - self.assertEqual(self.tierbuilder.get_tier_name('test_name'), - 'test_tier') - - def test_get_tier_name_ko(self): - self.assertEqual(self.tierbuilder.get_tier_name('test_name2'), None) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/ci/test_tier_handler.py b/functest/tests/unit/ci/test_tier_handler.py deleted file mode 100644 index 871220db3..000000000 --- a/functest/tests/unit/ci/test_tier_handler.py +++ /dev/null @@ -1,142 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -# pylint: disable=missing-docstring - -import logging -import unittest - -import mock - -from functest.ci import tier_handler - - -class TierHandlerTesting(unittest.TestCase): - - def setUp(self): - self.test = mock.Mock() - attrs = {'get_name.return_value': 'test_name'} - self.test.configure_mock(**attrs) - - self.mock_depend = mock.Mock() - attrs = {'get_scenario.return_value': 'test_scenario', - 'get_installer.return_value': 'test_installer'} - self.mock_depend.configure_mock(**attrs) - - self.tier = tier_handler.Tier('test_tier', - 'test_order', - 'test_ci_loop', - description='test_desc') - self.testcase = tier_handler.TestCase('test_name', - 'true', - self.mock_depend, - 'test_criteria', - 'test_blocking', - description='test_desc') - - self.dependency = tier_handler.Dependency('test_installer', - 'test_scenario') - - self.testcase.str = self.testcase.__str__() - self.dependency.str = self.dependency.__str__() - self.tier.str = self.tier.__str__() - - def test_split_text(self): - test_str = 'this is for testing' - self.assertEqual(tier_handler.split_text(test_str, 10), - ['this is ', 'for ', 'testing ']) - - def test_add_test(self): - self.tier.add_test(self.test) - self.assertEqual(self.tier.tests_array, - [self.test]) - - def test_get_tests(self): - self.tier.tests_array = [self.test] - self.assertEqual(self.tier.get_tests(), - [self.test]) - - def test_get_test_names(self): - self.tier.tests_array = [self.test] - self.assertEqual(self.tier.get_test_names(), - ['test_name']) - - def test_get_test(self): - self.tier.tests_array = [self.test] - with mock.patch.object(self.tier, 'is_test', - return_value=True): - self.assertEqual(self.tier.get_test('test_name'), - self.test) - - def test_get_test_missing_test(self): - self.tier.tests_array = [self.test] - with mock.patch.object(self.tier, 'is_test', - return_value=False): - self.assertEqual(self.tier.get_test('test_name'), - None) - - def test_get_name(self): - self.assertEqual(self.tier.get_name(), - 'test_tier') - - def test_get_order(self): - self.assertEqual(self.tier.get_order(), - 'test_order') - - def test_get_ci_loop(self): - self.assertEqual(self.tier.get_ci_loop(), - 'test_ci_loop') - - def test_testcase_is_none_in_item(self): - self.assertEqual(tier_handler.TestCase.is_none("item"), - False) - - def test_testcase_is_none_no_item(self): - self.assertEqual(tier_handler.TestCase.is_none(None), - True) - - def test_testcase_is_compatible(self): - self.assertEqual(self.testcase.is_compatible('test_installer', - 'test_scenario'), - True) - - def test_testcase_is_compatible_2(self): - self.assertEqual(self.testcase.is_compatible('missing_installer', - 'test_scenario'), - False) - self.assertEqual(self.testcase.is_compatible('test_installer', - 'missing_scenario'), - False) - - def test_testcase_get_name(self): - self.assertEqual(self.tier.get_name(), - 'test_tier') - - def test_testcase_is_enabled(self): - self.assertEqual(self.testcase.is_enabled(), - 'true') - - def test_testcase_get_criteria(self): - self.assertEqual(self.tier.get_order(), - 'test_order') - - def test_testcase_is_blocking(self): - self.assertEqual(self.tier.get_ci_loop(), - 'test_ci_loop') - - def test_dependency_get_installer(self): - self.assertEqual(self.dependency.get_installer(), - 'test_installer') - - def test_dependency_get_scenario(self): - self.assertEqual(self.dependency.get_scenario(), - 'test_scenario') - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/cli/commands/test_cli_env.py b/functest/tests/unit/cli/commands/test_cli_env.py deleted file mode 100644 index d865d3803..000000000 --- a/functest/tests/unit/cli/commands/test_cli_env.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -import logging -import unittest - -import mock - -from functest.cli.commands import cli_env -from functest.utils.constants import CONST -from functest.tests.unit import test_utils - - -class CliEnvTesting(unittest.TestCase): - - def setUp(self): - self.cli_environ = cli_env.CliEnv() - - def _test_show_missing_env_var(self, var, *args): - if var == 'INSTALLER_TYPE': - CONST.__setattr__('INSTALLER_TYPE', None) - reg_string = "| INSTALLER: Unknown, \S+\s*|" - elif var == 'INSTALLER_IP': - CONST.__setattr__('INSTALLER_IP', None) - reg_string = "| INSTALLER: \S+, Unknown\s*|" - elif var == 'SCENARIO': - CONST.__setattr__('DEPLOY_SCENARIO', None) - reg_string = "| SCENARIO: Unknown\s*|" - elif var == 'NODE': - CONST.__setattr__('NODE_NAME', None) - reg_string = "| POD: Unknown\s*|" - elif var == 'BUILD_TAG': - CONST.__setattr__('BUILD_TAG', None) - reg_string = "| BUILD TAG: None|" - elif var == 'DEBUG': - CONST.__setattr__('CI_DEBUG', None) - reg_string = "| DEBUG FLAG: false\s*|" - - with mock.patch('functest.cli.commands.cli_env.click.echo') \ - as mock_click_echo: - self.cli_environ.show() - mock_click_echo.assert_called_with(test_utils. - RegexMatch(reg_string)) - - def test_show_missing_ci_installer_type(self, *args): - self._test_show_missing_env_var('INSTALLER_TYPE', *args) - - def test_show_missing_ci_installer_ip(self, *args): - self._test_show_missing_env_var('INSTALLER_IP', *args) - - def test_show_missing_ci_scenario(self, *args): - self._test_show_missing_env_var('SCENARIO', *args) - - def test_show_missing_ci_node(self, *args): - self._test_show_missing_env_var('NODE', *args) - - def test_show_missing_ci_build_tag(self, *args): - self._test_show_missing_env_var('BUILD_TAG', *args) - - def test_show_missing_ci_debug(self, *args): - self._test_show_missing_env_var('DEBUG', *args) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/cli/commands/test_cli_os.py b/functest/tests/unit/cli/commands/test_cli_os.py deleted file mode 100644 index b827e87ca..000000000 --- a/functest/tests/unit/cli/commands/test_cli_os.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python -# -# jose.lausuch@ericsson.com -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 -# - -import logging -import unittest -import os - -import mock - -from functest.cli.commands import cli_os - - -class CliOpenStackTesting(unittest.TestCase): - - def setUp(self): - self.endpoint_ip = 'test_ip' - self.os_auth_url = 'http://test_ip:test_port/v2.0' - self.installer_type = 'test_installer_type' - self.installer_ip = 'test_installer_ip' - self.openstack_creds = 'test_openstack_creds' - self.snapshot_file = 'test_snapshot_file' - self.cli_os = cli_os.CliOpenStack() - - def test_ping_endpoint_default(self): - self.cli_os.os_auth_url = self.os_auth_url - self.cli_os.endpoint_ip = self.endpoint_ip - with mock.patch('functest.cli.commands.cli_os.os.system', - return_value=0): - self.assertEqual(self.cli_os.ping_endpoint(), 0) - - @mock.patch('functest.cli.commands.cli_os.exit', side_effect=Exception) - @mock.patch('functest.cli.commands.cli_os.click.echo') - def test_ping_endpoint_missing_auth_url(self, mock_click_echo, - mock_exit): - with self.assertRaises(Exception): - self.cli_os.os_auth_url = None - self.cli_os.ping_endpoint() - mock_click_echo.assert_called_once_with("Source the OpenStack " - "credentials first '. " - "$creds'") - - @mock.patch('functest.cli.commands.cli_os.exit') - @mock.patch('functest.cli.commands.cli_os.click.echo') - def test_ping_endpoint_os_system_fails(self, mock_click_echo, - mock_exit): - self.cli_os.os_auth_url = self.os_auth_url - self.cli_os.endpoint_ip = self.endpoint_ip - with mock.patch('functest.cli.commands.cli_os.os.system', - return_value=1): - self.cli_os.ping_endpoint() - mock_click_echo.assert_called_once_with("Cannot talk to the " - "endpoint %s\n" % - self.endpoint_ip) - mock_exit.assert_called_once_with(0) - - def test_check(self): - with mock.patch.object(self.cli_os, 'ping_endpoint'), \ - mock.patch('functest.cli.commands.cli_os.check_deployment.' - 'CheckDeployment') as mock_check_deployment: - self.cli_os.check() - self.assertTrue(mock_check_deployment.called) - - @mock.patch('functest.cli.commands.cli_os.click.echo') - def test_show_credentials(self, mock_click_echo): - key = 'OS_KEY' - value = 'OS_VALUE' - with mock.patch.dict(os.environ, {key: value}): - self.cli_os.show_credentials() - mock_click_echo.assert_any_call("{}={}".format(key, value)) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/cli/commands/test_cli_testcase.py b/functest/tests/unit/cli/commands/test_cli_testcase.py deleted file mode 100644 index f3648eb05..000000000 --- a/functest/tests/unit/cli/commands/test_cli_testcase.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - - -import logging -import unittest - -import mock - -from functest.cli.commands import cli_testcase - - -class CliTestCasesTesting(unittest.TestCase): - - def setUp(self): - self.testname = 'testname' - with mock.patch('functest.cli.commands.cli_testcase.tb'): - self.cli_tests = cli_testcase.CliTestcase() - - @mock.patch('functest.cli.commands.cli_testcase.vacation.main') - def test_run_vacation(self, mock_method): - self.cli_tests.run('vacation') - self.assertTrue(mock_method.called) - - @mock.patch('functest.cli.commands.cli_testcase.ft_utils.execute_command') - def test_run_default(self, mock_ft_utils): - cmd = "run_tests -n -r -t {}".format(self.testname) - self.cli_tests.run(self.testname, noclean=True, report=True) - mock_ft_utils.assert_called_with(cmd) - - @mock.patch('functest.cli.commands.cli_testcase.ft_utils.execute_command') - def test_run_noclean_missing_report(self, mock_ft_utils): - cmd = "run_tests -n -t {}".format(self.testname) - self.cli_tests.run(self.testname, noclean=True, report=False) - mock_ft_utils.assert_called_with(cmd) - - @mock.patch('functest.cli.commands.cli_testcase.ft_utils.execute_command') - def test_run_report_missing_noclean(self, mock_ft_utils): - cmd = "run_tests -r -t {}".format(self.testname) - self.cli_tests.run(self.testname, noclean=False, report=True) - mock_ft_utils.assert_called_with(cmd) - - @mock.patch('functest.cli.commands.cli_testcase.ft_utils.execute_command') - def test_run_missing_noclean_report(self, mock_ft_utils): - cmd = "run_tests -t {}".format(self.testname) - self.cli_tests.run(self.testname, noclean=False, report=False) - mock_ft_utils.assert_called_with(cmd) - - @mock.patch('functest.cli.commands.cli_testcase.click.echo') - def test_list(self, mock_click_echo): - with mock.patch.object(self.cli_tests.tiers, 'get_tiers', - return_value=[]): - self.cli_tests.list() - mock_click_echo.assert_called_with("") - - @mock.patch('functest.cli.commands.cli_testcase.click.echo') - def test_show_default_desc_none(self, mock_click_echo): - with mock.patch.object(self.cli_tests.tiers, 'get_test', - return_value=None): - self.cli_tests.show(self.testname) - mock_click_echo.assert_any_call("The test case '%s' " - "does not exist or is" - " not supported." - % self.testname) - - @mock.patch('functest.cli.commands.cli_testcase.click.echo') - def test_show_default(self, mock_click_echo): - mock_obj = mock.Mock() - with mock.patch.object(self.cli_tests.tiers, 'get_test', - return_value=mock_obj): - self.cli_tests.show(self.testname) - mock_click_echo.assert_called_with(mock_obj) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/cli/commands/test_cli_tier.py b/functest/tests/unit/cli/commands/test_cli_tier.py deleted file mode 100644 index a76d12049..000000000 --- a/functest/tests/unit/cli/commands/test_cli_tier.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - - -import logging -import unittest - -import mock - -from functest.cli.commands import cli_tier - - -class CliTierTesting(unittest.TestCase): - - def setUp(self): - self.tiername = 'tiername' - self.testnames = 'testnames' - with mock.patch('functest.cli.commands.cli_tier.tb'): - self.cli_tier = cli_tier.CliTier() - - @mock.patch('functest.cli.commands.cli_tier.click.echo') - def test_list(self, mock_click_echo): - with mock.patch.object(self.cli_tier.tiers, 'get_tiers', - return_value=[]): - self.cli_tier.list() - mock_click_echo.assert_called_with("") - - @mock.patch('functest.cli.commands.cli_tier.click.echo') - def test_show_default(self, mock_click_echo): - with mock.patch.object(self.cli_tier.tiers, 'get_tier', - return_value=self.tiername): - self.cli_tier.show(self.tiername) - mock_click_echo.assert_called_with(self.tiername) - - @mock.patch('functest.cli.commands.cli_tier.click.echo') - def test_show_missing_tier(self, mock_click_echo): - with mock.patch.object(self.cli_tier.tiers, 'get_tier', - return_value=None), \ - mock.patch.object(self.cli_tier.tiers, 'get_tier_names', - return_value='tiernames'): - self.cli_tier.show(self.tiername) - mock_click_echo.assert_called_with("The tier with name '%s' does " - "not exist. Available tiers are" - ":\n %s\n" % (self.tiername, - 'tiernames')) - - @mock.patch('functest.cli.commands.cli_tier.click.echo') - def test_gettests_default(self, mock_click_echo): - mock_obj = mock.Mock() - attrs = {'get_test_names.return_value': self.testnames} - mock_obj.configure_mock(**attrs) - - with mock.patch.object(self.cli_tier.tiers, 'get_tier', - return_value=mock_obj): - self.cli_tier.gettests(self.tiername) - mock_click_echo.assert_called_with("Test cases in tier " - "'%s':\n %s\n" % (self.tiername, - self.testnames - )) - - @mock.patch('functest.cli.commands.cli_tier.click.echo') - def test_gettests_missing_tier(self, mock_click_echo): - with mock.patch.object(self.cli_tier.tiers, 'get_tier', - return_value=None), \ - mock.patch.object(self.cli_tier.tiers, 'get_tier_names', - return_value='tiernames'): - self.cli_tier.gettests(self.tiername) - mock_click_echo.assert_called_with("The tier with name '%s' does " - "not exist. Available tiers are" - ":\n %s\n" % (self.tiername, - 'tiernames')) - - @mock.patch('functest.cli.commands.cli_tier.ft_utils.execute_command') - def test_run_default(self, mock_ft_utils): - cmd = "run_tests -n -r -t {}".format(self.tiername) - self.cli_tier.run(self.tiername, noclean=True, report=True) - mock_ft_utils.assert_called_with(cmd) - - @mock.patch('functest.cli.commands.cli_tier.ft_utils.execute_command') - def test_run_report_missing_noclean(self, mock_ft_utils): - cmd = "run_tests -r -t {}".format(self.tiername) - self.cli_tier.run(self.tiername, noclean=False, report=True) - mock_ft_utils.assert_called_with(cmd) - - @mock.patch('functest.cli.commands.cli_tier.ft_utils.execute_command') - def test_run_noclean_missing_report(self, mock_ft_utils): - cmd = "run_tests -n -t {}".format(self.tiername) - self.cli_tier.run(self.tiername, noclean=True, report=False) - mock_ft_utils.assert_called_with(cmd) - - @mock.patch('functest.cli.commands.cli_tier.ft_utils.execute_command') - def test_run_missing_noclean_report(self, mock_ft_utils): - cmd = "run_tests -t {}".format(self.tiername) - self.cli_tier.run(self.tiername, noclean=False, report=False) - mock_ft_utils.assert_called_with(cmd) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/cli/test_cli_base.py b/functest/tests/unit/cli/test_cli_base.py deleted file mode 100644 index bc2ca903e..000000000 --- a/functest/tests/unit/cli/test_cli_base.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2016 Orange and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -import logging -import unittest - -import mock -from click.testing import CliRunner - -with mock.patch('functest.cli.commands.cli_testcase.CliTestcase.__init__', - mock.Mock(return_value=None)), \ - mock.patch('functest.cli.commands.cli_tier.CliTier.__init__', - mock.Mock(return_value=None)): - from functest.cli import cli_base - - -class CliBaseTesting(unittest.TestCase): - - def setUp(self): - self.runner = CliRunner() - self._openstack = cli_base._openstack - self._env = cli_base._env - self._testcase = cli_base._testcase - self._tier = cli_base._tier - - def test_os_check(self): - with mock.patch.object(self._openstack, 'check') as mock_method: - result = self.runner.invoke(cli_base.os_check) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - def test_os_show_credentials(self): - with mock.patch.object(self._openstack, 'show_credentials') \ - as mock_method: - result = self.runner.invoke(cli_base.os_show_credentials) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - def test_env_show(self): - with mock.patch.object(self._env, 'show') as mock_method: - result = self.runner.invoke(cli_base.env_show) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - def test_testcase_list(self): - with mock.patch.object(self._testcase, 'list') as mock_method: - result = self.runner.invoke(cli_base.testcase_list) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - def test_testcase_show(self): - with mock.patch.object(self._testcase, 'show') as mock_method: - result = self.runner.invoke(cli_base.testcase_show, ['testname']) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - def test_testcase_run(self): - with mock.patch.object(self._testcase, 'run') as mock_method: - result = self.runner.invoke(cli_base.testcase_run, - ['testname', '--noclean']) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - def test_tier_list(self): - with mock.patch.object(self._tier, 'list') as mock_method: - result = self.runner.invoke(cli_base.tier_list) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - def test_tier_show(self): - with mock.patch.object(self._tier, 'show') as mock_method: - result = self.runner.invoke(cli_base.tier_show, ['tiername']) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - def test_tier_gettests(self): - with mock.patch.object(self._tier, 'gettests') as mock_method: - result = self.runner.invoke(cli_base.tier_gettests, ['tiername']) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - def test_tier_run(self): - with mock.patch.object(self._tier, 'run') as mock_method: - result = self.runner.invoke(cli_base.tier_run, - ['tiername', '--noclean']) - self.assertEqual(result.exit_code, 0) - self.assertTrue(mock_method.called) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/core/test_feature.py b/functest/tests/unit/core/test_feature.py deleted file mode 100644 index 8c73bb5d5..000000000 --- a/functest/tests/unit/core/test_feature.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2017 Orange and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -# pylint: disable=missing-docstring - -import logging -import unittest - -import mock - -from functest.core import feature -from functest.core import testcase - - -class FeatureTestingBase(unittest.TestCase): - - _case_name = "foo" - _project_name = "bar" - _repo = "dir_repo_bar" - _cmd = "run_bar_tests.py" - _output_file = '/home/opnfv/functest/results/foo.log' - feature = None - - @mock.patch('time.time', side_effect=[1, 2]) - def _test_run(self, status, mock_method=None): - self.assertEqual(self.feature.run(cmd=self._cmd), status) - if status == testcase.TestCase.EX_OK: - self.assertEqual(self.feature.result, 100) - else: - self.assertEqual(self.feature.result, 0) - mock_method.assert_has_calls([mock.call(), mock.call()]) - self.assertEqual(self.feature.start_time, 1) - self.assertEqual(self.feature.stop_time, 2) - - def test_logger_module_ko(self): - with mock.patch('six.moves.builtins.open'): - self.feature = feature.Feature( - project_name=self._project_name, case_name=self._case_name) - self.assertEqual(self.feature.logger.name, self._case_name) - - def test_logger_module(self): - with mock.patch('six.moves.builtins.open'): - self.feature = feature.Feature( - project_name=self._project_name, case_name=self._case_name, - run={'module': 'bar'}) - self.assertEqual(self.feature.logger.name, 'bar') - - -class FeatureTesting(FeatureTestingBase): - - def setUp(self): - with mock.patch('six.moves.builtins.open'): - self.feature = feature.Feature( - project_name=self._project_name, case_name=self._case_name) - - def test_run_exc(self): - # pylint: disable=bad-continuation - with mock.patch.object( - self.feature, 'execute', - side_effect=Exception) as mock_method: - self._test_run(testcase.TestCase.EX_RUN_ERROR) - mock_method.assert_called_once_with(cmd=self._cmd) - - def test_run(self): - self._test_run(testcase.TestCase.EX_RUN_ERROR) - - -class BashFeatureTesting(FeatureTestingBase): - - def setUp(self): - with mock.patch('six.moves.builtins.open'): - self.feature = feature.BashFeature( - project_name=self._project_name, case_name=self._case_name) - - @mock.patch('subprocess.Popen') - def test_run_no_cmd(self, mock_subproc): - self.assertEqual( - self.feature.run(), testcase.TestCase.EX_RUN_ERROR) - mock_subproc.assert_not_called() - - @mock.patch('subprocess.Popen') - def test_run_ko(self, mock_subproc): - with mock.patch('six.moves.builtins.open', mock.mock_open()) as mopen: - mock_obj = mock.Mock() - attrs = {'wait.return_value': 1} - mock_obj.configure_mock(**attrs) - - mock_subproc.return_value = mock_obj - self._test_run(testcase.TestCase.EX_RUN_ERROR) - mopen.assert_called_once_with(self._output_file, "w+") - - @mock.patch('subprocess.Popen') - def test_run(self, mock_subproc): - with mock.patch('six.moves.builtins.open', mock.mock_open()) as mopen: - mock_obj = mock.Mock() - attrs = {'wait.return_value': 0} - mock_obj.configure_mock(**attrs) - - mock_subproc.return_value = mock_obj - self._test_run(testcase.TestCase.EX_OK) - mopen.assert_called_once_with(self._output_file, "w+") - - -if __name__ == "__main__": - # logging must be disabled else it calls time.time() - # what will break these unit tests. - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/core/test_robotframework.py b/functest/tests/unit/core/test_robotframework.py deleted file mode 100644 index 38e9039b2..000000000 --- a/functest/tests/unit/core/test_robotframework.py +++ /dev/null @@ -1,191 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2017 Orange and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -"""Define the classes required to fully cover robot.""" - -import errno -import logging -import os -import unittest - -import mock -from robot.errors import DataError, RobotError -from robot.result import model -from robot.utils.robottime import timestamp_to_secs - -from functest.core import robotframework - -__author__ = "Cedric Ollivier <cedric.ollivier@orange.com>" - - -class ResultVisitorTesting(unittest.TestCase): - - """The class testing ResultVisitor.""" - # pylint: disable=missing-docstring - - def setUp(self): - self.visitor = robotframework.ResultVisitor() - - def test_empty(self): - self.assertFalse(self.visitor.get_data()) - - def test_ok(self): - data = {'name': 'foo', - 'parent': 'bar', - 'status': 'PASS', - 'starttime': "20161216 16:00:00.000", - 'endtime': "20161216 16:00:01.000", - 'elapsedtime': 1000, - 'text': 'Hello, World!', - 'critical': True} - test = model.TestCase( - name=data['name'], status=data['status'], message=data['text'], - starttime=data['starttime'], endtime=data['endtime']) - test.parent = mock.Mock() - config = {'name': data['parent'], - 'criticality.test_is_critical.return_value': data[ - 'critical']} - test.parent.configure_mock(**config) - self.visitor.visit_test(test) - self.assertEqual(self.visitor.get_data(), [data]) - - -class ParseResultTesting(unittest.TestCase): - - """The class testing RobotFramework.parse_results().""" - # pylint: disable=missing-docstring - - _config = {'name': 'dummy', 'starttime': '20161216 16:00:00.000', - 'endtime': '20161216 16:00:01.000'} - - def setUp(self): - self.test = robotframework.RobotFramework( - case_name='robot', project_name='functest') - - @mock.patch('robot.api.ExecutionResult', side_effect=DataError) - def test_raises_exc(self, mock_method): - with self.assertRaises(DataError): - self.test.parse_results() - mock_method.assert_called_once_with( - os.path.join(self.test.res_dir, 'output.xml')) - - def _test_result(self, config, result): - suite = mock.Mock() - suite.configure_mock(**config) - with mock.patch('robot.api.ExecutionResult', - return_value=mock.Mock(suite=suite)): - self.test.parse_results() - self.assertEqual(self.test.result, result) - self.assertEqual(self.test.start_time, - timestamp_to_secs(config['starttime'])) - self.assertEqual(self.test.stop_time, - timestamp_to_secs(config['endtime'])) - self.assertEqual(self.test.details, - {'description': config['name'], 'tests': []}) - - def test_null_passed(self): - self._config.update({'statistics.critical.passed': 0, - 'statistics.critical.total': 20}) - self._test_result(self._config, 0) - - def test_no_test(self): - self._config.update({'statistics.critical.passed': 20, - 'statistics.critical.total': 0}) - self._test_result(self._config, 0) - - def test_half_success(self): - self._config.update({'statistics.critical.passed': 10, - 'statistics.critical.total': 20}) - self._test_result(self._config, 50) - - def test_success(self): - self._config.update({'statistics.critical.passed': 20, - 'statistics.critical.total': 20}) - self._test_result(self._config, 100) - - -class RunTesting(unittest.TestCase): - - """The class testing RobotFramework.run().""" - # pylint: disable=missing-docstring - - suites = ["foo"] - variable = [] - - def setUp(self): - self.test = robotframework.RobotFramework( - case_name='robot', project_name='functest') - - def test_exc_key_error(self): - self.assertEqual(self.test.run(), self.test.EX_RUN_ERROR) - - @mock.patch('robot.run') - def _test_makedirs_exc(self, *args): - with mock.patch.object(self.test, 'parse_results') as mock_method: - self.assertEqual( - self.test.run(suites=self.suites, variable=self.variable), - self.test.EX_RUN_ERROR) - args[0].assert_not_called() - mock_method.asser_not_called() - - @mock.patch('os.makedirs', side_effect=Exception) - def test_makedirs_exc(self, *args): - self._test_makedirs_exc() - args[0].assert_called_once_with(self.test.res_dir) - - @mock.patch('os.makedirs', side_effect=OSError) - def test_makedirs_oserror(self, *args): - self._test_makedirs_exc() - args[0].assert_called_once_with(self.test.res_dir) - - @mock.patch('robot.run') - def _test_makedirs(self, *args): - with mock.patch.object(self.test, 'parse_results') as mock_method: - self.assertEqual( - self.test.run(suites=self.suites, variable=self.variable), - self.test.EX_OK) - args[0].assert_called_once_with( - *self.suites, log='NONE', output=self.test.xml_file, - report='NONE', stdout=mock.ANY, variable=self.variable) - mock_method.assert_called_once_with() - - @mock.patch('os.makedirs', side_effect=OSError(errno.EEXIST, '')) - def test_makedirs_oserror17(self, *args): - self._test_makedirs() - args[0].assert_called_once_with(self.test.res_dir) - - @mock.patch('os.makedirs') - def test_makedirs(self, *args): - self._test_makedirs() - args[0].assert_called_once_with(self.test.res_dir) - - @mock.patch('robot.run') - def _test_parse_results(self, status, *args): - self.assertEqual( - self.test.run(suites=self.suites, variable=self.variable), status) - args[0].assert_called_once_with( - *self.suites, log='NONE', output=self.test.xml_file, - report='NONE', stdout=mock.ANY, variable=self.variable) - - def test_parse_results_exc(self): - with mock.patch.object(self.test, 'parse_results', - side_effect=Exception) as mock_method: - self._test_parse_results(self.test.EX_RUN_ERROR) - mock_method.assert_called_once_with() - - def test_parse_results_robot_error(self): - with mock.patch.object(self.test, 'parse_results', - side_effect=RobotError('foo')) as mock_method: - self._test_parse_results(self.test.EX_RUN_ERROR) - mock_method.assert_called_once_with() - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/core/test_testcase.py b/functest/tests/unit/core/test_testcase.py deleted file mode 100644 index 73ed3470a..000000000 --- a/functest/tests/unit/core/test_testcase.py +++ /dev/null @@ -1,232 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2016 Orange and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -"""Define the class required to fully cover testcase.""" - -import logging -import unittest - -from functest.core import testcase - -import mock - - -__author__ = "Cedric Ollivier <cedric.ollivier@orange.com>" - - -class TestCaseTesting(unittest.TestCase): - """The class testing TestCase.""" - - # pylint: disable=missing-docstring,too-many-public-methods - - _case_name = "base" - _project_name = "functest" - _published_result = "PASS" - - def setUp(self): - self.test = testcase.TestCase(case_name=self._case_name, - project_name=self._project_name) - self.test.start_time = "1" - self.test.stop_time = "2" - self.test.result = 100 - self.test.details = {"Hello": "World"} - - def test_run_unimplemented(self): - self.assertEqual(self.test.run(), - testcase.TestCase.EX_RUN_ERROR) - - @mock.patch('functest.utils.functest_utils.push_results_to_db', - return_value=False) - def _test_missing_attribute(self, mock_function=None): - self.assertEqual(self.test.push_to_db(), - testcase.TestCase.EX_PUSH_TO_DB_ERROR) - mock_function.assert_not_called() - - def test_missing_project_name(self): - self.test.project_name = None - self._test_missing_attribute() - - def test_missing_case_name(self): - self.test.case_name = None - self._test_missing_attribute() - - def test_missing_start_time(self): - self.test.start_time = None - self._test_missing_attribute() - - def test_missing_stop_time(self): - self.test.stop_time = None - self._test_missing_attribute() - - @mock.patch('functest.utils.functest_utils.push_results_to_db', - return_value=True) - def test_missing_details(self, mock_function=None): - self.test.details = None - self.assertEqual(self.test.push_to_db(), - testcase.TestCase.EX_OK) - mock_function.assert_called_once_with( - self._project_name, self._case_name, self.test.start_time, - self.test.stop_time, self._published_result, self.test.details) - - @mock.patch('functest.utils.functest_utils.push_results_to_db', - return_value=False) - def test_push_to_db_failed(self, mock_function=None): - self.assertEqual(self.test.push_to_db(), - testcase.TestCase.EX_PUSH_TO_DB_ERROR) - mock_function.assert_called_once_with( - self._project_name, self._case_name, self.test.start_time, - self.test.stop_time, self._published_result, self.test.details) - - @mock.patch('functest.utils.functest_utils.push_results_to_db', - return_value=True) - def test_push_to_db(self, mock_function=None): - self.assertEqual(self.test.push_to_db(), - testcase.TestCase.EX_OK) - mock_function.assert_called_once_with( - self._project_name, self._case_name, self.test.start_time, - self.test.stop_time, self._published_result, self.test.details) - - @mock.patch('functest.utils.functest_utils.push_results_to_db', - return_value=True) - def test_push_to_db_res_ko(self, mock_function=None): - self.test.result = 0 - self.assertEqual(self.test.push_to_db(), - testcase.TestCase.EX_OK) - mock_function.assert_called_once_with( - self._project_name, self._case_name, self.test.start_time, - self.test.stop_time, 'FAIL', self.test.details) - - @mock.patch('functest.utils.functest_utils.push_results_to_db', - return_value=True) - def test_push_to_db_both_ko(self, mock_function=None): - self.test.result = 0 - self.test.criteria = 0 - self.assertEqual(self.test.push_to_db(), - testcase.TestCase.EX_OK) - mock_function.assert_called_once_with( - self._project_name, self._case_name, self.test.start_time, - self.test.stop_time, 'FAIL', self.test.details) - - def test_check_criteria_missing(self): - self.test.criteria = None - self.assertEqual(self.test.is_successful(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_check_result_missing(self): - self.test.result = None - self.assertEqual(self.test.is_successful(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_check_result_failed(self): - # Backward compatibility - # It must be removed as soon as TestCase subclasses - # stop setting result = 'PASS' or 'FAIL'. - self.test.result = 'FAIL' - self.assertEqual(self.test.is_successful(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_check_result_pass(self): - # Backward compatibility - # It must be removed as soon as TestCase subclasses - # stop setting result = 'PASS' or 'FAIL'. - self.test.result = 'PASS' - self.assertEqual(self.test.is_successful(), - testcase.TestCase.EX_OK) - - def test_check_result_lt(self): - self.test.result = 50 - self.assertEqual(self.test.is_successful(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_check_result_eq(self): - self.test.result = 100 - self.assertEqual(self.test.is_successful(), - testcase.TestCase.EX_OK) - - def test_check_result_gt(self): - self.test.criteria = 50 - self.test.result = 100 - self.assertEqual(self.test.is_successful(), - testcase.TestCase.EX_OK) - - def test_check_result_zero(self): - self.test.criteria = 0 - self.test.result = 0 - self.assertEqual(self.test.is_successful(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_get_duration_start_ko(self): - self.test.start_time = None - self.assertEqual(self.test.get_duration(), "XX:XX") - self.test.start_time = 0 - self.assertEqual(self.test.get_duration(), "XX:XX") - - def test_get_duration_end_ko(self): - self.test.stop_time = None - self.assertEqual(self.test.get_duration(), "XX:XX") - self.test.stop_time = 0 - self.assertEqual(self.test.get_duration(), "XX:XX") - - def test_get_invalid_duration(self): - self.test.start_time = 2 - self.test.stop_time = 1 - self.assertEqual(self.test.get_duration(), "XX:XX") - - def test_get_zero_duration(self): - self.test.start_time = 2 - self.test.stop_time = 2 - self.assertEqual(self.test.get_duration(), "00:00") - - def test_get_duration(self): - self.test.start_time = 1 - self.test.stop_time = 180 - self.assertEqual(self.test.get_duration(), "02:59") - - def test_str_project_name_ko(self): - self.test.project_name = None - self.assertIn("<functest.core.testcase.TestCase object at", - str(self.test)) - - def test_str_case_name_ko(self): - self.test.case_name = None - self.assertIn("<functest.core.testcase.TestCase object at", - str(self.test)) - - def test_str_pass(self): - duration = '01:01' - with mock.patch.object(self.test, 'get_duration', - return_value=duration), \ - mock.patch.object(self.test, 'is_successful', - return_value=testcase.TestCase.EX_OK): - message = str(self.test) - self.assertIn(self._project_name, message) - self.assertIn(self._case_name, message) - self.assertIn(duration, message) - self.assertIn('PASS', message) - - def test_str_fail(self): - duration = '00:59' - with mock.patch.object(self.test, 'get_duration', - return_value=duration), \ - mock.patch.object( - self.test, 'is_successful', - return_value=testcase.TestCase.EX_TESTCASE_FAILED): - message = str(self.test) - self.assertIn(self._project_name, message) - self.assertIn(self._case_name, message) - self.assertIn(duration, message) - self.assertIn('FAIL', message) - - def test_clean(self): - self.assertEqual(self.test.clean(), None) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/core/test_unit.py b/functest/tests/unit/core/test_unit.py deleted file mode 100644 index ca73de672..000000000 --- a/functest/tests/unit/core/test_unit.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -# pylint: disable=missing-docstring - -import logging -import unittest - -import mock - -from functest.core import unit -from functest.core import testcase - - -class PyTestSuiteRunnerTesting(unittest.TestCase): - - def setUp(self): - self.psrunner = unit.Suite() - self.psrunner.suite = "foo" - - @mock.patch('unittest.TestLoader') - def _test_run(self, mock_class=None, result=mock.Mock(), - status=testcase.TestCase.EX_OK): - with mock.patch('functest.core.unit.unittest.TextTestRunner.run', - return_value=result): - self.assertEqual(self.psrunner.run(), status) - mock_class.assert_not_called() - - def test_check_suite_null(self): - self.assertEqual(unit.Suite().suite, None) - self.psrunner.suite = None - self._test_run(result=mock.Mock(), - status=testcase.TestCase.EX_RUN_ERROR) - - def test_run_no_ut(self): - mock_result = mock.Mock(testsRun=0, errors=[], failures=[]) - self._test_run(result=mock_result, - status=testcase.TestCase.EX_RUN_ERROR) - self.assertEqual(self.psrunner.result, 0) - self.assertEqual(self.psrunner.details, - {'errors': 0, 'failures': 0, 'stream': '', - 'testsRun': 0}) - self.assertEqual(self.psrunner.is_successful(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_run_result_ko(self): - self.psrunner.criteria = 100 - mock_result = mock.Mock(testsRun=50, errors=[('test1', 'error_msg1')], - failures=[('test2', 'failure_msg1')]) - self._test_run(result=mock_result) - self.assertEqual(self.psrunner.result, 96) - self.assertEqual(self.psrunner.details, - {'errors': 1, 'failures': 1, 'stream': '', - 'testsRun': 50}) - self.assertEqual(self.psrunner.is_successful(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_run_result_ok(self): - mock_result = mock.Mock(testsRun=50, errors=[], - failures=[]) - self._test_run(result=mock_result) - self.assertEqual(self.psrunner.result, 100) - self.assertEqual(self.psrunner.details, - {'errors': 0, 'failures': 0, 'stream': '', - 'testsRun': 50}) - self.assertEqual(self.psrunner.is_successful(), - testcase.TestCase.EX_OK) - - @mock.patch('unittest.TestLoader') - def test_run_name_exc(self, mock_class=None): - mock_obj = mock.Mock(side_effect=ImportError) - mock_class.side_effect = mock_obj - self.assertEqual(self.psrunner.run(name='foo'), - testcase.TestCase.EX_RUN_ERROR) - mock_class.assert_called_once_with() - mock_obj.assert_called_once_with() - - @mock.patch('unittest.TestLoader') - def test_run_name(self, mock_class=None): - mock_result = mock.Mock(testsRun=50, errors=[], - failures=[]) - mock_obj = mock.Mock() - mock_class.side_effect = mock_obj - with mock.patch('functest.core.unit.unittest.TextTestRunner.run', - return_value=mock_result): - self.assertEqual(self.psrunner.run(name='foo'), - testcase.TestCase.EX_OK) - mock_class.assert_called_once_with() - mock_obj.assert_called_once_with() - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/core/test_vnf.py b/functest/tests/unit/core/test_vnf.py deleted file mode 100644 index e0eee1a19..000000000 --- a/functest/tests/unit/core/test_vnf.py +++ /dev/null @@ -1,194 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2016 Orange and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -# pylint: disable=missing-docstring - -import logging -import unittest - -import mock - -from functest.core import vnf -from functest.core import testcase -from functest.utils import constants - -from snaps.openstack.os_credentials import OSCreds - - -class VnfBaseTesting(unittest.TestCase): - """The class testing VNF.""" - # pylint: disable=missing-docstring,too-many-public-methods - - tenant_name = 'test_tenant_name' - tenant_description = 'description' - - def setUp(self): - constants.CONST.__setattr__("vnf_foo_tenant_name", self.tenant_name) - constants.CONST.__setattr__( - "vnf_foo_tenant_description", self.tenant_description) - self.test = vnf.VnfOnBoarding(project='functest', case_name='foo') - - def test_run_deploy_orch_exc(self): - with mock.patch.object(self.test, 'prepare'), \ - mock.patch.object(self.test, 'deploy_orchestrator', - side_effect=Exception) as mock_method, \ - mock.patch.object(self.test, 'deploy_vnf', - return_value=True), \ - mock.patch.object(self.test, 'test_vnf', - return_value=True): - self.assertEqual(self.test.run(), - testcase.TestCase.EX_TESTCASE_FAILED) - mock_method.assert_called_with() - - def test_run_deploy_vnf_exc(self): - with mock.patch.object(self.test, 'prepare'),\ - mock.patch.object(self.test, 'deploy_orchestrator', - return_value=True), \ - mock.patch.object(self.test, 'deploy_vnf', - side_effect=Exception) as mock_method: - self.assertEqual(self.test.run(), - testcase.TestCase.EX_TESTCASE_FAILED) - mock_method.assert_called_with() - - def test_run_test_vnf_exc(self): - with mock.patch.object(self.test, 'prepare'),\ - mock.patch.object(self.test, 'deploy_orchestrator', - return_value=True), \ - mock.patch.object(self.test, 'deploy_vnf', return_value=True), \ - mock.patch.object(self.test, 'test_vnf', - side_effect=Exception) as mock_method: - self.assertEqual(self.test.run(), - testcase.TestCase.EX_TESTCASE_FAILED) - mock_method.assert_called_with() - - def test_run_deploy_orch_ko(self): - with mock.patch.object(self.test, 'prepare'),\ - mock.patch.object(self.test, 'deploy_orchestrator', - return_value=False), \ - mock.patch.object(self.test, 'deploy_vnf', - return_value=True), \ - mock.patch.object(self.test, 'test_vnf', - return_value=True): - self.assertEqual(self.test.run(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_run_vnf_deploy_ko(self): - with mock.patch.object(self.test, 'prepare'),\ - mock.patch.object(self.test, 'deploy_orchestrator', - return_value=True), \ - mock.patch.object(self.test, 'deploy_vnf', - return_value=False), \ - mock.patch.object(self.test, 'test_vnf', - return_value=True): - self.assertEqual(self.test.run(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_run_vnf_test_ko(self): - with mock.patch.object(self.test, 'prepare'),\ - mock.patch.object(self.test, 'deploy_orchestrator', - return_value=True), \ - mock.patch.object(self.test, 'deploy_vnf', - return_value=True), \ - mock.patch.object(self.test, 'test_vnf', - return_value=False): - self.assertEqual(self.test.run(), - testcase.TestCase.EX_TESTCASE_FAILED) - - def test_run_default(self): - with mock.patch.object(self.test, 'prepare'),\ - mock.patch.object(self.test, 'deploy_orchestrator', - return_value=True), \ - mock.patch.object(self.test, 'deploy_vnf', - return_value=True), \ - mock.patch.object(self.test, 'test_vnf', - return_value=True): - self.assertEqual(self.test.run(), testcase.TestCase.EX_OK) - - @mock.patch('functest.core.vnf.OpenStackUser') - @mock.patch('functest.core.vnf.OpenStackProject') - @mock.patch('snaps.openstack.tests.openstack_tests.get_credentials', - side_effect=Exception) - def test_prepare_exc1(self, *args): - with self.assertRaises(Exception): - self.test.prepare() - args[0].assert_called_with( - os_env_file=constants.CONST.__getattribute__('openstack_creds')) - args[1].assert_not_called() - args[2].assert_not_called() - - @mock.patch('functest.core.vnf.OpenStackUser') - @mock.patch('functest.core.vnf.OpenStackProject', side_effect=Exception) - @mock.patch('snaps.openstack.tests.openstack_tests.get_credentials') - def test_prepare_exc2(self, *args): - with self.assertRaises(Exception): - self.test.prepare() - args[0].assert_called_with( - os_env_file=constants.CONST.__getattribute__('openstack_creds')) - args[1].assert_called_with(mock.ANY, mock.ANY) - args[2].assert_not_called() - - @mock.patch('functest.core.vnf.OpenStackUser', side_effect=Exception) - @mock.patch('functest.core.vnf.OpenStackProject') - @mock.patch('snaps.openstack.tests.openstack_tests.get_credentials') - def test_prepare_exc3(self, *args): - with self.assertRaises(Exception): - self.test.prepare() - args[0].assert_called_with( - os_env_file=constants.CONST.__getattribute__('openstack_creds')) - args[1].assert_called_with(mock.ANY, mock.ANY) - args[2].assert_called_with(mock.ANY, mock.ANY) - - @mock.patch('functest.core.vnf.OpenStackUser') - @mock.patch('functest.core.vnf.OpenStackProject') - @mock.patch('snaps.openstack.tests.openstack_tests.get_credentials') - def test_prepare_default(self, *args): - self.assertEqual(self.test.prepare(), testcase.TestCase.EX_OK) - args[0].assert_called_with( - os_env_file=constants.CONST.__getattribute__('openstack_creds')) - args[1].assert_called_with(mock.ANY, mock.ANY) - args[2].assert_called_with(mock.ANY, mock.ANY) - - def test_deploy_vnf_unimplemented(self): - with self.assertRaises(vnf.VnfDeploymentException): - self.test.deploy_vnf() - - def test_test_vnf_unimplemented(self): - with self.assertRaises(vnf.VnfTestException): - self.test.test_vnf() - - def test_deploy_orch_unimplemented(self): - self.assertTrue(self.test.deploy_orchestrator()) - - @mock.patch('snaps.openstack.tests.openstack_tests.get_credentials', - return_value=OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar'), - side_effect=Exception) - def test_prepare_keystone_client_ko(self, *args): - with self.assertRaises(vnf.VnfPreparationException): - self.test.prepare() - args[0].assert_called_once() - - def test_vnf_clean_exc(self): - obj = mock.Mock() - obj.clean.side_effect = Exception - self.test.created_object = [obj] - self.test.clean() - obj.clean.assert_called_with() - - def test_vnf_clean(self): - obj = mock.Mock() - self.test.created_object = [obj] - self.test.clean() - obj.clean.assert_called_with() - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/energy/__init__.py b/functest/tests/unit/energy/__init__.py deleted file mode 100644 index e69de29bb..000000000 --- a/functest/tests/unit/energy/__init__.py +++ /dev/null diff --git a/functest/tests/unit/energy/test_functest_energy.py b/functest/tests/unit/energy/test_functest_energy.py deleted file mode 100644 index f0711ca0c..000000000 --- a/functest/tests/unit/energy/test_functest_energy.py +++ /dev/null @@ -1,385 +0,0 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- - -# Copyright (c) 2017 Orange and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -"""Unitary test for energy module.""" -# pylint: disable=unused-argument -import logging -import requests -import unittest - -import mock - -from functest.energy.energy import EnergyRecorder -import functest.energy.energy as energy -from functest.utils.constants import CONST - -CASE_NAME = "UNIT_TEST_CASE" -STEP_NAME = "UNIT_TEST_STEP" - -PREVIOUS_SCENARIO = "previous_scenario" -PREVIOUS_STEP = "previous_step" - - -class MockHttpResponse(object): # pylint: disable=too-few-public-methods - """Mock response for Energy recorder API.""" - - def __init__(self, text, status_code): - """Create an instance of MockHttpResponse.""" - self.text = text - self.status_code = status_code - - -API_OK = MockHttpResponse( - '{"status": "OK"}', - 200 -) -API_KO = MockHttpResponse( - '{"message": "API-KO"}', - 500 -) - -RECORDER_OK = MockHttpResponse( - '{"environment": "UNIT_TEST",' - ' "step": "string",' - ' "scenario": "' + CASE_NAME + '"}', - 200 -) -RECORDER_KO = MockHttpResponse( - '{"message": "An unhandled API exception occurred (MOCK)"}', - 500 -) -RECORDER_NOT_FOUND = MockHttpResponse( - '{"message": "Recorder not found (MOCK)"}', - 404 -) - - -def config_loader_mock(config_key): - """Return mocked config values.""" - if config_key == "energy_recorder.api_url": - return "http://pod-uri:8888" - elif config_key == "energy_recorder.api_user": - return "user" - elif config_key == "energy_recorder.api_password": - return "password" - - -def config_loader_mock_no_creds(config_key): - """Return mocked config values.""" - if config_key == "energy_recorder.api_url": - return "http://pod-uri:8888" - elif config_key == "energy_recorder.api_user": - return "" - elif config_key == "energy_recorder.api_password": - return "" - - -# pylint: disable=too-many-public-methods -class EnergyRecorderTest(unittest.TestCase): - """Energy module unitary test suite.""" - - case_name = CASE_NAME - request_headers = {'content-type': 'application/json'} - returned_value_to_preserve = "value" - exception_message_to_preserve = "exception_message" - - @mock.patch('functest.energy.energy.requests.post', - return_value=RECORDER_OK) - def test_start(self, post_mock=None, get_mock=None): - """EnergyRecorder.start method (regular case).""" - self.test_load_config() - self.assertTrue(EnergyRecorder.start(self.case_name)) - post_mock.assert_called_once_with( - EnergyRecorder.energy_recorder_api["uri"], - auth=EnergyRecorder.energy_recorder_api["auth"], - data=mock.ANY, - headers=self.request_headers, - timeout=EnergyRecorder.CONNECTION_TIMEOUT - ) - - @mock.patch('functest.energy.energy.requests.post', - side_effect=Exception("Internal execution error (MOCK)")) - def test_start_error(self, post_mock=None): - """EnergyRecorder.start method (error in method).""" - self.test_load_config() - self.assertFalse(EnergyRecorder.start(self.case_name)) - post_mock.assert_called_once_with( - EnergyRecorder.energy_recorder_api["uri"], - auth=EnergyRecorder.energy_recorder_api["auth"], - data=mock.ANY, - headers=self.request_headers, - timeout=EnergyRecorder.CONNECTION_TIMEOUT - ) - - @mock.patch('functest.energy.energy.EnergyRecorder.load_config', - side_effect=Exception("Internal execution error (MOCK)")) - def test_start_exception(self, conf_loader_mock=None): - """EnergyRecorder.start test with exception during execution.""" - start_status = EnergyRecorder.start(CASE_NAME) - self.assertFalse(start_status) - - @mock.patch('functest.energy.energy.requests.post', - return_value=RECORDER_KO) - def test_start_api_error(self, post_mock=None): - """EnergyRecorder.start method (API error).""" - self.test_load_config() - self.assertFalse(EnergyRecorder.start(self.case_name)) - post_mock.assert_called_once_with( - EnergyRecorder.energy_recorder_api["uri"], - auth=EnergyRecorder.energy_recorder_api["auth"], - data=mock.ANY, - headers=self.request_headers, - timeout=EnergyRecorder.CONNECTION_TIMEOUT - ) - - @mock.patch('functest.energy.energy.requests.post', - return_value=RECORDER_OK) - def test_set_step(self, post_mock=None): - """EnergyRecorder.set_step method (regular case).""" - self.test_load_config() - self.assertTrue(EnergyRecorder.set_step(STEP_NAME)) - post_mock.assert_called_once_with( - EnergyRecorder.energy_recorder_api["uri"] + "/step", - auth=EnergyRecorder.energy_recorder_api["auth"], - data=mock.ANY, - headers=self.request_headers, - timeout=EnergyRecorder.CONNECTION_TIMEOUT - ) - - @mock.patch('functest.energy.energy.requests.post', - return_value=RECORDER_KO) - def test_set_step_api_error(self, post_mock=None): - """EnergyRecorder.set_step method (API error).""" - self.test_load_config() - self.assertFalse(EnergyRecorder.set_step(STEP_NAME)) - post_mock.assert_called_once_with( - EnergyRecorder.energy_recorder_api["uri"] + "/step", - auth=EnergyRecorder.energy_recorder_api["auth"], - data=mock.ANY, - headers=self.request_headers, - timeout=EnergyRecorder.CONNECTION_TIMEOUT - ) - - @mock.patch('functest.energy.energy.requests.post', - side_effect=Exception("Internal execution error (MOCK)")) - def test_set_step_error(self, post_mock=None): - """EnergyRecorder.set_step method (method error).""" - self.test_load_config() - self.assertFalse(EnergyRecorder.set_step(STEP_NAME)) - post_mock.assert_called_once_with( - EnergyRecorder.energy_recorder_api["uri"] + "/step", - auth=EnergyRecorder.energy_recorder_api["auth"], - data=mock.ANY, - headers=self.request_headers, - timeout=EnergyRecorder.CONNECTION_TIMEOUT - ) - - @mock.patch('functest.energy.energy.EnergyRecorder.load_config', - side_effect=requests.exceptions.ConnectionError()) - def test_set_step_connection_error(self, conf_loader_mock=None): - """EnergyRecorder.start test with exception during execution.""" - step_status = EnergyRecorder.set_step(STEP_NAME) - self.assertFalse(step_status) - - @mock.patch('functest.energy.energy.requests.delete', - return_value=RECORDER_OK) - def test_stop(self, delete_mock=None): - """EnergyRecorder.stop method (regular case).""" - self.test_load_config() - self.assertTrue(EnergyRecorder.stop()) - delete_mock.assert_called_once_with( - EnergyRecorder.energy_recorder_api["uri"], - auth=EnergyRecorder.energy_recorder_api["auth"], - headers=self.request_headers, - timeout=EnergyRecorder.CONNECTION_TIMEOUT - ) - - @mock.patch('functest.energy.energy.requests.delete', - return_value=RECORDER_KO) - def test_stop_api_error(self, delete_mock=None): - """EnergyRecorder.stop method (API Error).""" - self.test_load_config() - self.assertFalse(EnergyRecorder.stop()) - delete_mock.assert_called_once_with( - EnergyRecorder.energy_recorder_api["uri"], - auth=EnergyRecorder.energy_recorder_api["auth"], - headers=self.request_headers, - timeout=EnergyRecorder.CONNECTION_TIMEOUT - ) - - @mock.patch('functest.energy.energy.requests.delete', - side_effect=Exception("Internal execution error (MOCK)")) - def test_stop_error(self, delete_mock=None): - """EnergyRecorder.stop method (method error).""" - self.test_load_config() - self.assertFalse(EnergyRecorder.stop()) - delete_mock.assert_called_once_with( - EnergyRecorder.energy_recorder_api["uri"], - auth=EnergyRecorder.energy_recorder_api["auth"], - headers=self.request_headers, - timeout=EnergyRecorder.CONNECTION_TIMEOUT - ) - - @energy.enable_recording - def __decorated_method(self): - """Call with to energy recorder decorators.""" - return self.returned_value_to_preserve - - @energy.enable_recording - def __decorated_method_with_ex(self): - """Call with to energy recorder decorators.""" - raise Exception(self.exception_message_to_preserve) - - @mock.patch("functest.energy.energy.EnergyRecorder.get_current_scenario", - return_value=None) - @mock.patch("functest.energy.energy.EnergyRecorder") - def test_decorators(self, - recorder_mock=None, - cur_scenario_mock=None): - """Test energy module decorators.""" - self.__decorated_method() - calls = [mock.call.start(self.case_name), - mock.call.stop()] - recorder_mock.assert_has_calls(calls) - - @mock.patch("functest.energy.energy.EnergyRecorder.get_current_scenario", - return_value={"scenario": PREVIOUS_SCENARIO, - "step": PREVIOUS_STEP}) - @mock.patch("functest.energy.energy.EnergyRecorder") - @mock.patch("functest.utils.functest_utils.get_functest_config", - side_effect=config_loader_mock) - def test_decorators_with_previous(self, - loader_mock=None, - recorder_mock=None, - cur_scenario_mock=None): - """Test energy module decorators.""" - CONST.__setattr__('NODE_NAME', 'MOCK_POD') - self.__decorated_method() - calls = [mock.call.start(self.case_name), - mock.call.submit_scenario(PREVIOUS_SCENARIO, - PREVIOUS_STEP)] - recorder_mock.assert_has_calls(calls, True) - - def test_decorator_preserve_return(self): - """Test that decorator preserve method returned value.""" - self.test_load_config() - self.assertTrue( - self.__decorated_method() == self.returned_value_to_preserve - ) - - @mock.patch( - "functest.energy.energy.finish_session") - def test_decorator_preserve_ex(self, finish_mock=None): - """Test that decorator preserve method exceptions.""" - self.test_load_config() - with self.assertRaises(Exception) as context: - self.__decorated_method_with_ex() - self.assertTrue( - self.exception_message_to_preserve in str(context.exception) - ) - self.assertTrue(finish_mock.called) - - @mock.patch("functest.utils.functest_utils.get_functest_config", - side_effect=config_loader_mock) - @mock.patch("functest.energy.energy.requests.get", - return_value=API_OK) - def test_load_config(self, loader_mock=None, get_mock=None): - """Test load config.""" - CONST.__setattr__('NODE_NAME', 'MOCK_POD') - EnergyRecorder.energy_recorder_api = None - EnergyRecorder.load_config() - - self.assertEquals( - EnergyRecorder.energy_recorder_api["auth"], - ("user", "password") - ) - self.assertEquals( - EnergyRecorder.energy_recorder_api["uri"], - "http://pod-uri:8888/recorders/environment/MOCK_POD" - ) - - @mock.patch("functest.utils.functest_utils.get_functest_config", - side_effect=config_loader_mock_no_creds) - @mock.patch("functest.energy.energy.requests.get", - return_value=API_OK) - def test_load_config_no_creds(self, loader_mock=None, get_mock=None): - """Test load config without creds.""" - CONST.__setattr__('NODE_NAME', 'MOCK_POD') - EnergyRecorder.energy_recorder_api = None - EnergyRecorder.load_config() - self.assertEquals(EnergyRecorder.energy_recorder_api["auth"], None) - self.assertEquals( - EnergyRecorder.energy_recorder_api["uri"], - "http://pod-uri:8888/recorders/environment/MOCK_POD" - ) - - @mock.patch("functest.utils.functest_utils.get_functest_config", - return_value=None) - @mock.patch("functest.energy.energy.requests.get", - return_value=API_OK) - def test_load_config_ex(self, loader_mock=None, get_mock=None): - """Test load config with exception.""" - CONST.__setattr__('NODE_NAME', 'MOCK_POD') - with self.assertRaises(AssertionError): - EnergyRecorder.energy_recorder_api = None - EnergyRecorder.load_config() - self.assertEquals(EnergyRecorder.energy_recorder_api, None) - - @mock.patch("functest.utils.functest_utils.get_functest_config", - side_effect=config_loader_mock) - @mock.patch("functest.energy.energy.requests.get", - return_value=API_KO) - def test_load_config_api_ko(self, loader_mock=None, get_mock=None): - """Test load config with API unavailable.""" - CONST.__setattr__('NODE_NAME', 'MOCK_POD') - EnergyRecorder.energy_recorder_api = None - EnergyRecorder.load_config() - self.assertEquals(EnergyRecorder.energy_recorder_api["available"], - False) - - @mock.patch("functest.utils.functest_utils.get_functest_config", - return_value=None) - @mock.patch('functest.energy.energy.requests.get', - return_value=RECORDER_OK) - def test_get_current_scenario(self, loader_mock=None, get_mock=None): - """Test get_current_scenario.""" - CONST.__setattr__('NODE_NAME', 'MOCK_POD') - self.test_load_config() - scenario = EnergyRecorder.get_current_scenario() - self.assertTrue(scenario is not None) - - @mock.patch('functest.energy.energy.requests.get', - return_value=RECORDER_NOT_FOUND) - def test_current_scenario_not_found(self, get_mock=None): - """Test get current scenario not existing.""" - CONST.__setattr__('NODE_NAME', 'MOCK_POD') - self.test_load_config() - scenario = EnergyRecorder.get_current_scenario() - self.assertTrue(scenario is None) - - @mock.patch('functest.energy.energy.requests.get', - return_value=RECORDER_KO) - def test_current_scenario_api_error(self, get_mock=None): - """Test get current scenario with API error.""" - CONST.__setattr__('NODE_NAME', 'MOCK_POD') - self.test_load_config() - scenario = EnergyRecorder.get_current_scenario() - self.assertTrue(scenario is None) - - @mock.patch('functest.energy.energy.EnergyRecorder.load_config', - side_effect=Exception("Internal execution error (MOCK)")) - def test_current_scenario_exception(self, get_mock=None): - """Test get current scenario with exception.""" - scenario = EnergyRecorder.get_current_scenario() - self.assertTrue(scenario is None) - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/odl/test_odl.py b/functest/tests/unit/odl/test_odl.py index 1a3f79503..c675c2988 100644 --- a/functest/tests/unit/odl/test_odl.py +++ b/functest/tests/unit/odl/test_odl.py @@ -13,13 +13,13 @@ import logging import os import unittest -from keystoneauth1.exceptions import auth_plugins import mock +import munch from robot.errors import RobotError import six from six.moves import urllib +from xtesting.core import testcase -from functest.core import testcase from functest.opnfv_tests.sdn.odl import odl __author__ = "Cedric Ollivier <cedric.ollivier@orange.com>" @@ -33,9 +33,10 @@ class ODLTesting(unittest.TestCase): logging.disable(logging.CRITICAL) _keystone_ip = "127.0.0.1" - _neutron_url = "http://127.0.0.2:9696" + _neutron_url = "https://127.0.0.1:9696" + _neutron_id = "dummy" _sdn_controller_ip = "127.0.0.3" - _os_auth_url = "http://{}:5000/v3".format(_keystone_ip) + _os_auth_url = f"http://{_keystone_ip}:5000/v3" _os_projectname = "admin" _os_username = "admin" _os_password = "admin" @@ -45,9 +46,10 @@ class ODLTesting(unittest.TestCase): _odl_password = "admin" _os_userdomainname = 'Default' _os_projectdomainname = 'Default' + _os_interface = "public" def setUp(self): - for var in ("INSTALLER_TYPE", "SDN_CONTROLLER", "SDN_CONTROLLER_IP"): + for var in ("SDN_CONTROLLER", "SDN_CONTROLLER_IP"): if var in os.environ: del os.environ[var] os.environ["OS_AUTH_URL"] = self._os_auth_url @@ -57,11 +59,11 @@ class ODLTesting(unittest.TestCase): os.environ["OS_PROJECT_NAME"] = self._os_projectname os.environ["OS_PROJECT_DOMAIN_NAME"] = self._os_projectdomainname os.environ["OS_PASSWORD"] = self._os_password + os.environ["OS_INTERFACE"] = self._os_interface self.test = odl.ODLTests(case_name='odl', project_name='functest') self.defaultargs = {'odlusername': self._odl_username, 'odlpassword': self._odl_password, - 'neutronurl': "http://{}:9696".format( - self._keystone_ip), + 'neutronurl': f"http://{self._keystone_ip}:9696", 'osauthurl': self._os_auth_url, 'osusername': self._os_username, 'osuserdomainname': self._os_userdomainname, @@ -102,7 +104,7 @@ class ODLRobotTesting(ODLTesting): mock_method.assert_called_once_with( os.path.join(odl.ODLTests.odl_test_repo, 'csit/variables/Variables.robot'), inplace=True) - self.assertEqual(args[0].getvalue(), "{}\n".format(msg2)) + self.assertEqual(args[0].getvalue(), f"{msg2}\n") def test_set_vars_auth_default(self): self._test_set_vars( @@ -153,31 +155,30 @@ class ODLMainTesting(ODLTesting): def _test_run_suites(self, status, *args): kwargs = self._get_run_suites_kwargs() self.assertEqual(self.test.run_suites(**kwargs), status) - if len(args) > 0: + if args: args[0].assert_called_once_with(self.test.odl_variables_file) if len(args) > 1: variable = [ - 'KEYSTONEURL:{}://{}'.format( - urllib.parse.urlparse(self._os_auth_url).scheme, - urllib.parse.urlparse(self._os_auth_url).netloc), - 'NEUTRONURL:{}'.format(self._neutron_url), - 'OS_AUTH_URL:"{}"'.format(self._os_auth_url), - 'OSUSERNAME:"{}"'.format(self._os_username), - 'OSUSERDOMAINNAME:"{}"'.format(self._os_userdomainname), - 'OSTENANTNAME:"{}"'.format(self._os_projectname), - 'OSPROJECTDOMAINNAME:"{}"'.format(self._os_projectdomainname), - 'OSPASSWORD:"{}"'.format(self._os_password), - 'ODL_SYSTEM_IP:{}'.format(self._sdn_controller_ip), - 'PORT:{}'.format(self._odl_webport), - 'RESTCONFPORT:{}'.format(self._odl_restconfport)] + ('KEYSTONEURL:' + f'{urllib.parse.urlparse(self._os_auth_url).scheme}://' + f'{urllib.parse.urlparse(self._os_auth_url).netloc}'), + f'NEUTRONURL:{self._neutron_url}', + f'OS_AUTH_URL:"{self._os_auth_url}"', + f'OSUSERNAME:"{self._os_username}"', + f'OSUSERDOMAINNAME:"{self._os_userdomainname}"', + f'OSTENANTNAME:"{self._os_projectname}"', + f'OSPROJECTDOMAINNAME:"{self._os_projectdomainname}"', + f'OSPASSWORD:"{self._os_password}"', + f'ODL_SYSTEM_IP:{self._sdn_controller_ip}', + f'PORT:{self._odl_webport}', + f'RESTCONFPORT:{self._odl_restconfport}'] args[1].assert_called_once_with( - odl.ODLTests.basic_suite_dir, - odl.ODLTests.neutron_suite_dir, + odl.ODLTests.basic_suite_dir, odl.ODLTests.neutron_suite_dir, + include=[], log='NONE', output=os.path.join(self.test.res_dir, 'output.xml'), - report='NONE', - stdout=mock.ANY, - variable=variable) + report='NONE', stdout=mock.ANY, variable=variable, + variablefile=[]) def _test_no_keyword(self, key): kwargs = self._get_run_suites_kwargs(key) @@ -223,6 +224,7 @@ class ODLMainTesting(ODLTesting): self._odl_username, self._odl_password) args[0].assert_called_once_with(self.test.odl_variables_file) + @mock.patch('os.makedirs') @mock.patch('robot.run', side_effect=RobotError) @mock.patch('os.path.isfile', return_value=True) def test_run_ko(self, *args): @@ -231,6 +233,7 @@ class ODLMainTesting(ODLTesting): self.assertRaises(RobotError): self._test_run_suites(testcase.TestCase.EX_RUN_ERROR, *args) + @mock.patch('os.makedirs') @mock.patch('robot.run') @mock.patch('os.path.isfile', return_value=True) def test_parse_results_ko(self, *args): @@ -240,97 +243,214 @@ class ODLMainTesting(ODLTesting): side_effect=RobotError): self._test_run_suites(testcase.TestCase.EX_RUN_ERROR, *args) + @mock.patch('os.makedirs') + @mock.patch('robot.run') + @mock.patch('os.path.isfile', return_value=True) + def test_generate_report_ko(self, *args): + with mock.patch.object(self.test, 'set_robotframework_vars', + return_value=True), \ + mock.patch.object(self.test, 'parse_results'), \ + mock.patch.object(self.test, 'generate_report', + return_value=1): + self._test_run_suites(testcase.TestCase.EX_OK, *args) + + @mock.patch('os.makedirs') + @mock.patch('robot.run') + @mock.patch('os.path.isfile', return_value=True) + def test_generate_report_exc(self, *args): + with mock.patch.object(self.test, 'set_robotframework_vars', + return_value=True), \ + mock.patch.object(self.test, 'parse_results'), \ + mock.patch.object(self.test, 'generate_report', + side_effect=Exception): + self._test_run_suites(testcase.TestCase.EX_RUN_ERROR, *args) + + @mock.patch('os.makedirs') @mock.patch('robot.run') @mock.patch('os.path.isfile', return_value=True) def test_ok(self, *args): with mock.patch.object(self.test, 'set_robotframework_vars', return_value=True), \ - mock.patch.object(self.test, 'parse_results'): + mock.patch.object(self.test, 'parse_results'), \ + mock.patch.object(self.test, 'generate_report', + return_value=0): self._test_run_suites(testcase.TestCase.EX_OK, *args) + @mock.patch('os.makedirs') @mock.patch('robot.run') @mock.patch('os.path.isfile', return_value=False) def test_ok_no_creds(self, *args): with mock.patch.object(self.test, 'set_robotframework_vars', return_value=True) as mock_method, \ - mock.patch.object(self.test, 'parse_results'): + mock.patch.object(self.test, 'parse_results'), \ + mock.patch.object(self.test, 'generate_report', + return_value=0): self._test_run_suites(testcase.TestCase.EX_OK, *args) mock_method.assert_not_called() + @mock.patch('os.makedirs') @mock.patch('robot.run', return_value=1) @mock.patch('os.path.isfile', return_value=True) def test_testcases_in_failure(self, *args): with mock.patch.object(self.test, 'set_robotframework_vars', return_value=True), \ - mock.patch.object(self.test, 'parse_results'): + mock.patch.object(self.test, 'parse_results'), \ + mock.patch.object(self.test, 'generate_report', + return_value=0): self._test_run_suites(testcase.TestCase.EX_OK, *args) class ODLRunTesting(ODLTesting): - """The class testing ODLTests.run().""" - # pylint: disable=missing-docstring - - def _test_no_env_var(self, var): - with mock.patch('functest.utils.openstack_utils.get_endpoint', - return_value=ODLTesting._neutron_url): - del os.environ[var] - self.assertEqual(self.test.run(), - testcase.TestCase.EX_RUN_ERROR) - + # pylint: disable=too-many-public-methods,missing-docstring + + @mock.patch('os_client_config.make_shade', side_effect=Exception) + def test_no_cloud(self, *args): + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].assert_called_once_with() + + @mock.patch('os_client_config.make_shade') + def test_no_service1(self, *args): + args[0].return_value.search_services.return_value = None + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].return_value.search_services.assert_called_once_with('neutron') + args[0].return_value.search_endpoints.assert_not_called() + + @mock.patch('os_client_config.make_shade') + def test_no_service2(self, *args): + args[0].return_value.search_services.return_value = [] + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].return_value.search_services.assert_called_once_with('neutron') + args[0].return_value.search_endpoints.assert_not_called() + + @mock.patch('os_client_config.make_shade') + def test_no_service3(self, *args): + args[0].return_value.search_services.return_value = [ + munch.Munch()] + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].return_value.search_services.assert_called_once_with('neutron') + args[0].return_value.search_endpoints.assert_not_called() + + @mock.patch('os_client_config.make_shade') + def test_no_endpoint1(self, *args): + args[0].return_value.search_services.return_value = [ + munch.Munch(id=self._neutron_id)] + args[0].return_value.search_endpoints.return_value = None + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].return_value.search_services.assert_called_once_with('neutron') + args[0].return_value.search_endpoints.assert_called_once_with( + filters={'interface': self._os_interface, + 'service_id': self._neutron_id}) + + @mock.patch('os_client_config.make_shade') + def test_no_endpoint2(self, *args): + args[0].return_value.search_services.return_value = [ + munch.Munch(id=self._neutron_id)] + args[0].return_value.search_endpoints.return_value = [] + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].return_value.search_services.assert_called_once_with('neutron') + args[0].return_value.search_endpoints.assert_called_once_with( + filters={'interface': self._os_interface, + 'service_id': self._neutron_id}) + + @mock.patch('os_client_config.make_shade') + def test_no_endpoint3(self, *args): + args[0].return_value.search_services.return_value = [ + munch.Munch(id=self._neutron_id)] + args[0].return_value.search_endpoints.return_value = [munch.Munch()] + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].return_value.search_services.assert_called_once_with('neutron') + args[0].return_value.search_endpoints.assert_called_once_with( + filters={'interface': self._os_interface, + 'service_id': self._neutron_id}) + + @mock.patch('os_client_config.make_shade') + def test_endpoint_interface(self, *args): + args[0].return_value.search_services.return_value = [ + munch.Munch(id=self._neutron_id)] + args[0].return_value.search_endpoints.return_value = [munch.Munch()] + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].return_value.search_services.assert_called_once_with('neutron') + args[0].return_value.search_endpoints.assert_called_once_with( + filters={'interface': self._os_interface, + 'service_id': self._neutron_id}) + + @mock.patch('os_client_config.make_shade') + def _test_no_env_var(self, var, *args): + del os.environ[var] + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].assert_called_once_with() + + @mock.patch('os_client_config.make_shade') + def _test_missing_value(self, *args): + self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) + args[0].assert_called_once_with() + + @mock.patch('os_client_config.make_shade') def _test_run(self, status=testcase.TestCase.EX_OK, - exception=None, **kwargs): + exception=None, *args, **kwargs): + # pylint: disable=keyword-arg-before-vararg + args[0].return_value.search_services.return_value = [ + munch.Munch(id=self._neutron_id)] + args[0].return_value.search_endpoints.return_value = [ + munch.Munch(url=self._neutron_url)] odlip = kwargs['odlip'] if 'odlip' in kwargs else '127.0.0.3' odlwebport = kwargs['odlwebport'] if 'odlwebport' in kwargs else '8080' odlrestconfport = (kwargs['odlrestconfport'] if 'odlrestconfport' in kwargs else '8181') - - with mock.patch('functest.utils.openstack_utils.get_endpoint', - return_value=ODLTesting._neutron_url): - if exception: - self.test.run_suites = mock.Mock(side_effect=exception) - else: - self.test.run_suites = mock.Mock(return_value=status) - self.assertEqual(self.test.run(), status) - self.test.run_suites.assert_called_once_with( - odl.ODLTests.default_suites, - neutronurl=self._neutron_url, - odlip=odlip, odlpassword=self._odl_password, - odlrestconfport=odlrestconfport, - odlusername=self._odl_username, odlwebport=odlwebport, - osauthurl=self._os_auth_url, - ospassword=self._os_password, - osprojectname=self._os_projectname, - osusername=self._os_username, - osprojectdomainname=self._os_projectdomainname, - osuserdomainname=self._os_userdomainname) - + if exception: + self.test.run_suites = mock.Mock(side_effect=exception) + else: + self.test.run_suites = mock.Mock(return_value=status) + self.assertEqual(self.test.run(), status) + self.test.run_suites.assert_called_once_with( + odl.ODLTests.default_suites, neutronurl=self._neutron_url, + odlip=odlip, odlpassword=self._odl_password, + odlrestconfport=odlrestconfport, odlusername=self._odl_username, + odlwebport=odlwebport, osauthurl=self._os_auth_url, + ospassword=self._os_password, osprojectname=self._os_projectname, + osusername=self._os_username, + osprojectdomainname=self._os_projectdomainname, + osuserdomainname=self._os_userdomainname) + args[0].assert_called_once_with() + args[0].return_value.search_services.assert_called_once_with('neutron') + args[0].return_value.search_endpoints.assert_called_once_with( + filters={ + 'interface': os.environ.get( + "OS_INTERFACE", "public").replace('URL', ''), + 'service_id': self._neutron_id}) + + @mock.patch('os_client_config.make_shade') def _test_multiple_suites(self, suites, - status=testcase.TestCase.EX_OK, **kwargs): + status=testcase.TestCase.EX_OK, *args, **kwargs): + # pylint: disable=keyword-arg-before-vararg + args[0].return_value.search_endpoints.return_value = [ + munch.Munch(url=self._neutron_url)] + args[0].return_value.search_services.return_value = [ + munch.Munch(id=self._neutron_id)] odlip = kwargs['odlip'] if 'odlip' in kwargs else '127.0.0.3' odlwebport = kwargs['odlwebport'] if 'odlwebport' in kwargs else '8080' odlrestconfport = (kwargs['odlrestconfport'] if 'odlrestconfport' in kwargs else '8181') - with mock.patch('functest.utils.openstack_utils.get_endpoint', - return_value=ODLTesting._neutron_url): - self.test.run_suites = mock.Mock(return_value=status) - self.assertEqual(self.test.run(suites=suites), status) - self.test.run_suites.assert_called_once_with( - suites, - neutronurl=self._neutron_url, - odlip=odlip, odlpassword=self._odl_password, - odlrestconfport=odlrestconfport, - odlusername=self._odl_username, odlwebport=odlwebport, - osauthurl=self._os_auth_url, - ospassword=self._os_password, - osprojectname=self._os_projectname, - osusername=self._os_username, - osprojectdomainname=self._os_projectdomainname, - osuserdomainname=self._os_userdomainname) + self.test.run_suites = mock.Mock(return_value=status) + self.assertEqual(self.test.run(suites=suites), status) + self.test.run_suites.assert_called_once_with( + suites, neutronurl=self._neutron_url, odlip=odlip, + odlpassword=self._odl_password, odlrestconfport=odlrestconfport, + odlusername=self._odl_username, odlwebport=odlwebport, + osauthurl=self._os_auth_url, ospassword=self._os_password, + osprojectname=self._os_projectname, osusername=self._os_username, + osprojectdomainname=self._os_projectdomainname, + osuserdomainname=self._os_userdomainname) + args[0].assert_called_once_with() + args[0].return_value.search_services.assert_called_once_with('neutron') + args[0].return_value.search_endpoints.assert_called_once_with( + filters={'interface': os.environ.get("OS_INTERFACE", "public"), + 'service_id': self._neutron_id}) def test_exc(self): - with mock.patch('functest.utils.openstack_utils.get_endpoint', - side_effect=auth_plugins.MissingAuthPlugin()): + with mock.patch('os_client_config.make_shade', + side_effect=Exception()): self.assertEqual(self.test.run(), testcase.TestCase.EX_RUN_ERROR) @@ -348,105 +468,69 @@ class ODLRunTesting(ODLTesting): def test_run_suites_false(self): os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip - self._test_run(testcase.TestCase.EX_RUN_ERROR, + self._test_run(testcase.TestCase.EX_RUN_ERROR, None, odlip=self._sdn_controller_ip, odlwebport=self._odl_webport) def test_run_suites_exc(self): with self.assertRaises(Exception): os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip - self._test_run(status=testcase.TestCase.EX_RUN_ERROR, - exception=Exception(), + self._test_run(testcase.TestCase.EX_RUN_ERROR, + Exception(), odlip=self._sdn_controller_ip, odlwebport=self._odl_webport) def test_no_sdn_controller_ip(self): - with mock.patch('functest.utils.openstack_utils.get_endpoint', - return_value=ODLTesting._neutron_url): - self.assertEqual(self.test.run(), - testcase.TestCase.EX_RUN_ERROR) + self._test_missing_value() def test_without_installer_type(self): os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip - self._test_run(testcase.TestCase.EX_OK, + self._test_run(testcase.TestCase.EX_OK, None, odlip=self._sdn_controller_ip, odlwebport=self._odl_webport) - def test_suites(self): + def test_without_os_interface(self): + del os.environ["OS_INTERFACE"] os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip - self._test_multiple_suites( - [odl.ODLTests.basic_suite_dir], - testcase.TestCase.EX_OK, - odlip=self._sdn_controller_ip, - odlwebport=self._odl_webport) + self._test_run(testcase.TestCase.EX_OK, None, + odlip=self._sdn_controller_ip, + odlwebport=self._odl_webport) - def test_fuel(self): - os.environ["INSTALLER_TYPE"] = "fuel" - self._test_run(testcase.TestCase.EX_OK, - odlip=urllib.parse.urlparse(self._neutron_url).hostname, - odlwebport='8181', - odlrestconfport='8282') - - def test_apex_no_controller_ip(self): - with mock.patch('functest.utils.openstack_utils.get_endpoint', - return_value=ODLTesting._neutron_url): - os.environ["INSTALLER_TYPE"] = "apex" - self.assertEqual(self.test.run(), - testcase.TestCase.EX_RUN_ERROR) + def test_os_interface_public(self): + os.environ["OS_INTERFACE"] = "public" + os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip + self._test_run(testcase.TestCase.EX_OK, None, + odlip=self._sdn_controller_ip, + odlwebport=self._odl_webport) - def test_apex(self): + def test_os_interface_publicurl(self): + os.environ["OS_INTERFACE"] = "publicURL" os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip - os.environ["INSTALLER_TYPE"] = "apex" - self._test_run(testcase.TestCase.EX_OK, - odlip=self._sdn_controller_ip, odlwebport='8081', - odlrestconfport='8081') - - def test_netvirt_no_controller_ip(self): - with mock.patch('functest.utils.openstack_utils.get_endpoint', - return_value=ODLTesting._neutron_url): - os.environ["INSTALLER_TYPE"] = "netvirt" - self.assertEqual(self.test.run(), - testcase.TestCase.EX_RUN_ERROR) + self._test_run(testcase.TestCase.EX_OK, None, + odlip=self._sdn_controller_ip, + odlwebport=self._odl_webport) - def test_netvirt(self): + def test_os_interface_internal(self): + os.environ["OS_INTERFACE"] = "internal" os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip - os.environ["INSTALLER_TYPE"] = "netvirt" - self._test_run(testcase.TestCase.EX_OK, - odlip=self._sdn_controller_ip, odlwebport='8081', - odlrestconfport='8081') - - def test_joid_no_controller_ip(self): - with mock.patch('functest.utils.openstack_utils.get_endpoint', - return_value=ODLTesting._neutron_url): - os.environ["INSTALLER_TYPE"] = "joid" - self.assertEqual(self.test.run(), - testcase.TestCase.EX_RUN_ERROR) + self._test_run(testcase.TestCase.EX_OK, None, + odlip=self._sdn_controller_ip, + odlwebport=self._odl_webport) - def test_joid(self): - os.environ["SDN_CONTROLLER"] = self._sdn_controller_ip - os.environ["INSTALLER_TYPE"] = "joid" - self._test_run(testcase.TestCase.EX_OK, - odlip=self._sdn_controller_ip, odlwebport='8080') - - def test_compass(self): - os.environ["INSTALLER_TYPE"] = "compass" - self._test_run(testcase.TestCase.EX_OK, - odlip=urllib.parse.urlparse(self._neutron_url).hostname, - odlrestconfport='8080') - - def test_daisy_no_controller_ip(self): - with mock.patch('functest.utils.openstack_utils.get_endpoint', - return_value=ODLTesting._neutron_url): - os.environ["INSTALLER_TYPE"] = "daisy" - self.assertEqual(self.test.run(), - testcase.TestCase.EX_RUN_ERROR) + def test_os_interface_admin(self): + os.environ["OS_INTERFACE"] = "admin" + os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip + self._test_run(testcase.TestCase.EX_OK, None, + odlip=self._sdn_controller_ip, + odlwebport=self._odl_webport) - def test_daisy(self): + def test_suites(self): os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip - os.environ["INSTALLER_TYPE"] = "daisy" - self._test_run(testcase.TestCase.EX_OK, - odlip=self._sdn_controller_ip, odlwebport='8181', - odlrestconfport='8087') + self._test_multiple_suites( + [odl.ODLTests.basic_suite_dir], + testcase.TestCase.EX_OK, + odlip=self._sdn_controller_ip, + odlwebport=self._odl_webport) class ODLArgParserTesting(ODLTesting): @@ -456,7 +540,7 @@ class ODLArgParserTesting(ODLTesting): def setUp(self): self.parser = odl.ODLParser() - super(ODLArgParserTesting, self).setUp() + super().setUp() def test_default(self): self.assertEqual(self.parser.parse_args(), self.defaultargs) @@ -466,8 +550,8 @@ class ODLArgParserTesting(ODLTesting): self.defaultargs['odlip'] = self._sdn_controller_ip self.assertEqual( self.parser.parse_args( - ["--neutronurl={}".format(self._neutron_url), - "--odlip={}".format(self._sdn_controller_ip)]), + [f"--neutronurl={self._neutron_url}", + f"--odlip={self._sdn_controller_ip}"]), self.defaultargs) @mock.patch('sys.stderr', new_callable=six.StringIO) @@ -480,7 +564,7 @@ class ODLArgParserTesting(ODLTesting): def _test_arg(self, arg, value): self.defaultargs[arg] = value self.assertEqual( - self.parser.parse_args(["--{}={}".format(arg, value)]), + self.parser.parse_args([f"--{arg}={value}"]), self.defaultargs) def test_odlusername(self): @@ -521,7 +605,7 @@ class ODLArgParserTesting(ODLTesting): def test_pushtodb(self): self.defaultargs['pushtodb'] = True - self.assertEqual(self.parser.parse_args(["--{}".format('pushtodb')]), + self.assertEqual(self.parser.parse_args(["--pushtodb"]), self.defaultargs) def test_multiple_args(self): @@ -529,8 +613,8 @@ class ODLArgParserTesting(ODLTesting): self.defaultargs['odlip'] = self._sdn_controller_ip self.assertEqual( self.parser.parse_args( - ["--neutronurl={}".format(self._neutron_url), - "--odlip={}".format(self._sdn_controller_ip)]), + [f"--neutronurl={self._neutron_url}", + f"--odlip={self._sdn_controller_ip}"]), self.defaultargs) diff --git a/functest/tests/unit/ci/__init__.py b/functest/tests/unit/openstack/cinder/__init__.py index e69de29bb..e69de29bb 100644 --- a/functest/tests/unit/ci/__init__.py +++ b/functest/tests/unit/openstack/cinder/__init__.py diff --git a/functest/tests/unit/openstack/cinder/test_cinder.py b/functest/tests/unit/openstack/cinder/test_cinder.py new file mode 100644 index 000000000..d3c9cabb6 --- /dev/null +++ b/functest/tests/unit/openstack/cinder/test_cinder.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python + +# Copyright (c) 2018 Enea AB and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 + +# pylint: disable=missing-docstring + + +import logging +import unittest + +import pkg_resources +import mock +import munch +import shade + +from functest.opnfv_tests.openstack.cinder import cinder_test +from functest.utils import config +from functest.utils import env + + +class CinderTesting(unittest.TestCase): + + def setUp(self): + with mock.patch('functest.core.singlevm.SingleVm2.__init__'): + self.cinder = cinder_test.CinderCheck() + self.cinder.cloud = mock.Mock() + self.cinder.case_name = 'cinder' + self.cinder.guid = '1' + + @mock.patch('functest.opnfv_tests.openstack.cinder.cinder_test.' + 'CinderCheck.connect') + @mock.patch('functest.core.singlevm.SingleVm2.prepare', + side_effect=Exception) + def test_prepare_exc1(self, *args): + self.cinder.cloud.boot_vm = mock.Mock() + with self.assertRaises(Exception): + self.cinder.prepare() + args[0].assert_called_once_with() + args[1].assert_not_called() + self.cinder.cloud.boot_vm.assert_not_called() + self.cinder.cloud.create_volume.assert_not_called() + + @mock.patch('functest.opnfv_tests.openstack.cinder.cinder_test.' + 'CinderCheck.connect') + @mock.patch('functest.opnfv_tests.openstack.cinder.cinder_test.' + 'CinderCheck.boot_vm', + side_effect=Exception) + @mock.patch('functest.core.singlevm.SingleVm2.prepare') + def test_prepare_exc2(self, *args): + self.cinder.sec = munch.Munch(id='foo') + self.cinder.keypair = munch.Munch(id='foo') + self.cinder.volume_timeout = munch.Munch(id='foo') + with self.assertRaises(Exception): + self.cinder.prepare() + args[0].assert_called_with() + args[1].assert_called_once_with( + f'{self.cinder.case_name}-vm2_{self.cinder.guid}', + security_groups=[self.cinder.sec.id], + key_name=self.cinder.keypair.id) + self.cinder.cloud.create_volume.assert_not_called() + args[2].assert_not_called() + + @mock.patch('functest.opnfv_tests.openstack.cinder.cinder_test.' + 'CinderCheck.boot_vm', return_value=munch.Munch(id='vm2')) + @mock.patch('functest.core.singlevm.SingleVm2.prepare') + def test_prepare(self, *args): + self.cinder.sec = munch.Munch(id='foo') + self.cinder.keypair = munch.Munch(id='foo') + self.cinder.ext_net = mock.Mock(id='foo') + self.cinder.ssh2 = mock.Mock() + self.cinder.fip2 = munch.Munch(id='fip2') + self.cinder.connect = mock.Mock( + return_value=(self.cinder.fip2, self.cinder.ssh2)) + self.cinder.cloud.create_volume = mock.Mock( + return_value=munch.Munch()) + self.cinder.prepare() + args[0].assert_called_once_with() + args[1].assert_called_once_with( + f'{self.cinder.case_name}-vm2_{self.cinder.guid}', + security_groups=[self.cinder.sec.id], + key_name=self.cinder.keypair.id) + self.cinder.connect.assert_called_once_with(args[1].return_value) + self.cinder.cloud.create_volume.assert_called_once_with( + name=f'{self.cinder.case_name}-volume_{self.cinder.guid}', + size='2', timeout=self.cinder.volume_timeout, wait=True) + + @mock.patch('scp.SCPClient.put') + def test_write(self, *args): + # pylint: disable=protected-access + self.cinder.ssh = mock.Mock() + self.cinder.sshvm = mock.Mock(id='foo') + self.cinder.volume = mock.Mock(id='volume') + stdout = mock.Mock() + stdout.channel.recv_exit_status.return_value = 0 + self.cinder.ssh.exec_command.return_value = (None, stdout, mock.Mock()) + self.assertEqual(self.cinder._write_data(), 0) + self.cinder.ssh.exec_command.assert_called_once_with( + f"sh ~/write_data.sh {env.get('VOLUME_DEVICE_NAME')}") + self.cinder.cloud.attach_volume.assert_called_once_with( + self.cinder.sshvm, self.cinder.volume, + timeout=self.cinder.volume_timeout) + self.cinder.cloud.detach_volume.assert_called_once_with( + self.cinder.sshvm, self.cinder.volume, + timeout=self.cinder.volume_timeout) + args[0].assert_called_once_with( + pkg_resources.resource_filename( + 'functest.opnfv_tests.openstack.cinder', 'write_data.sh'), + remote_path="~/") + + @mock.patch('scp.SCPClient.put', side_effect=Exception) + def test_write_exc1(self, *args): + # pylint: disable=protected-access + self.cinder.ssh = mock.Mock() + self.cinder.sshvm = mock.Mock(id='foo') + self.cinder.cloud.attach_volume = mock.Mock() + self.assertEqual( + self.cinder._write_data(), self.cinder.EX_RUN_ERROR) + args[0].assert_called_once_with( + pkg_resources.resource_filename( + 'functest.opnfv_tests.openstack.cinder', 'write_data.sh'), + remote_path="~/") + + @mock.patch('scp.SCPClient.put') + def test_read(self, *args): + # pylint: disable=protected-access + self.cinder.ssh2 = mock.Mock() + self.cinder.vm2 = mock.Mock(id='foo') + self.cinder.volume = mock.Mock(id='volume') + stdout = mock.Mock() + self.cinder.ssh2.exec_command.return_value = ( + None, stdout, mock.Mock()) + stdout.channel.recv_exit_status.return_value = 0 + self.assertEqual(self.cinder._read_data(), 0) + self.cinder.ssh2.exec_command.assert_called_once_with( + f"sh ~/read_data.sh {env.get('VOLUME_DEVICE_NAME')}") + self.cinder.cloud.attach_volume.assert_called_once_with( + self.cinder.vm2, self.cinder.volume, + timeout=self.cinder.volume_timeout) + self.cinder.cloud.detach_volume.assert_called_once_with( + self.cinder.vm2, self.cinder.volume, + timeout=self.cinder.volume_timeout) + args[0].assert_called_once_with( + pkg_resources.resource_filename( + 'functest.opnfv_tests.openstack.cinder', 'read_data.sh'), + remote_path="~/") + + @mock.patch('scp.SCPClient.put', side_effect=Exception) + def test_read_exc1(self, *args): + # pylint: disable=protected-access + self.cinder.ssh = mock.Mock() + self.cinder.ssh2 = mock.Mock() + self.cinder.sshvm = mock.Mock(id='foo') + self.cinder.cloud.attach_volume = mock.Mock() + self.assertEqual( + self.cinder._read_data(), self.cinder.EX_RUN_ERROR) + args[0].assert_called_once_with( + pkg_resources.resource_filename( + 'functest.opnfv_tests.openstack.cinder', 'read_data.sh'), + remote_path="~/") + + def test_execute_exc1(self): + # pylint: disable=protected-access + self.cinder._write_data = mock.Mock(side_effect=Exception) + self.cinder._read_data = mock.Mock() + with self.assertRaises(Exception): + self.cinder.execute() + self.cinder._write_data.assert_called_once_with() + self.cinder._read_data.assert_not_called() + + def test_execute_exc2(self): + # pylint: disable=protected-access + self.cinder._write_data = mock.Mock(return_value=0) + self.cinder._read_data = mock.Mock(side_effect=Exception) + with self.assertRaises(Exception): + self.cinder.execute() + self.cinder._write_data.assert_called_once_with() + self.cinder._read_data.assert_called_once_with() + + def test_execute_res1(self): + # pylint: disable=protected-access + self.cinder._write_data = mock.Mock(return_value=1) + self.cinder._read_data = mock.Mock() + self.assertEqual(self.cinder.execute(), 1) + self.cinder._write_data.assert_called_once_with() + self.cinder._read_data.assert_not_called() + + def test_execute_res2(self): + # pylint: disable=protected-access + self.cinder._write_data = mock.Mock(return_value=0) + self.cinder._read_data = mock.Mock(return_value=1) + self.assertEqual(self.cinder.execute(), 1) + self.cinder._write_data.assert_called_once_with() + self.cinder._read_data.assert_called_once_with() + + def test_execute_res3(self): + # pylint: disable=protected-access + self.cinder._write_data = mock.Mock(return_value=0) + self.cinder._read_data = mock.Mock(return_value=0) + self.assertEqual(self.cinder.execute(), 0) + self.cinder._write_data.assert_called_once_with() + self.cinder._read_data.assert_called_once_with() + + def test_clean_exc1(self): + self.cinder.cloud = None + with self.assertRaises(AssertionError): + self.cinder.clean() + + @mock.patch('functest.core.singlevm.SingleVm2.clean') + def test_clean_exc2(self, *args): + self.cinder.vm2 = munch.Munch(id='vm2') + self.cinder.cloud.delete_server = mock.Mock( + side_effect=shade.OpenStackCloudException("Foo")) + with self.assertRaises(shade.OpenStackCloudException): + self.cinder.clean() + self.cinder.cloud.delete_server.assert_called_once_with( + self.cinder.vm2, wait=True, + timeout=getattr(config.CONF, 'vping_vm_delete_timeout')) + self.cinder.cloud.delete_floating_ip.assert_not_called() + self.cinder.cloud.delete_volume.assert_not_called() + args[0].assert_not_called() + + @mock.patch('functest.core.singlevm.SingleVm2.clean', + side_effect=Exception) + def test_clean_exc3(self, mock_clean): + self.cinder.vm2 = munch.Munch(id='vm2') + self.cinder.volume = munch.Munch(id='volume') + self.cinder.fip2 = munch.Munch(id='fip2') + with self.assertRaises(Exception): + self.cinder.clean() + self.cinder.cloud.delete_server.assert_called_once_with( + self.cinder.vm2, wait=True, + timeout=getattr(config.CONF, 'vping_vm_delete_timeout')) + self.cinder.cloud.delete_floating_ip.assert_called_once_with( + self.cinder.fip2.id) + self.cinder.cloud.delete_volume.assert_called_once_with( + self.cinder.volume.id) + mock_clean.prepare() + + @mock.patch('functest.core.singlevm.SingleVm2.clean') + def test_clean(self, *args): + self.cinder.vm2 = munch.Munch(id='vm2') + self.cinder.volume = munch.Munch(id='volume') + self.cinder.fip2 = munch.Munch(id='fip2') + self.cinder.clean() + self.cinder.cloud.delete_server.assert_called_once_with( + self.cinder.vm2, wait=True, + timeout=getattr(config.CONF, 'vping_vm_delete_timeout')) + self.cinder.cloud.delete_floating_ip.assert_called_once_with( + self.cinder.fip2.id) + self.cinder.cloud.delete_volume.assert_called_once_with( + self.cinder.volume.id) + args[0].assert_called_once_with() + + @mock.patch('functest.core.singlevm.SingleVm2.clean') + def test_clean2(self, *args): + self.cinder.clean() + self.cinder.cloud.delete_server.assert_not_called() + self.cinder.cloud.delete_floating_ip.assert_not_called() + self.cinder.cloud.delete_volume.assert_not_called() + args[0].assert_called_once_with() + + +if __name__ == '__main__': + logging.disable(logging.CRITICAL) + unittest.main(verbosity=2) diff --git a/functest/tests/unit/openstack/rally/test_rally.py b/functest/tests/unit/openstack/rally/test_rally.py index 450eb85bc..f3c2e7cf6 100644 --- a/functest/tests/unit/openstack/rally/test_rally.py +++ b/functest/tests/unit/openstack/rally/test_rally.py @@ -5,46 +5,52 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 +# pylint: disable=missing-docstring,protected-access,invalid-name + import json import logging import os +import subprocess import unittest import mock +import munch +from xtesting.core import testcase -from functest.core import testcase from functest.opnfv_tests.openstack.rally import rally -from functest.utils.constants import CONST - -from snaps.openstack.os_credentials import OSCreds +from functest.utils import config class OSRallyTesting(unittest.TestCase): + # pylint: disable=too-many-public-methods def setUp(self): - os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - with mock.patch('snaps.openstack.tests.openstack_tests.' - 'get_credentials', return_value=os_creds) as m: + with mock.patch('os_client_config.get_config') as mock_get_config, \ + mock.patch('shade.OpenStackCloud') as mock_shade, \ + mock.patch('functest.core.tenantnetwork.NewProject') \ + as mock_new_project: self.rally_base = rally.RallyBase() - self.polling_iter = 2 - self.assertTrue(m.called) + self.rally_base.image = munch.Munch(name='foo') + self.rally_base.flavor = munch.Munch(name='foo') + self.rally_base.flavor_alt = munch.Munch(name='bar') + self.assertTrue(mock_get_config.called) + self.assertTrue(mock_shade.called) + self.assertTrue(mock_new_project.called) def test_build_task_args_missing_floating_network(self): - CONST.__setattr__('OS_AUTH_URL', None) - self.rally_base.ext_net_name = '' - task_args = self.rally_base._build_task_args('test_file_name') + os.environ['OS_AUTH_URL'] = '' + self.rally_base.ext_net = None + task_args = self.rally_base.build_task_args('test_name') self.assertEqual(task_args['floating_network'], '') def test_build_task_args_missing_net_id(self): - CONST.__setattr__('OS_AUTH_URL', None) - self.rally_base.priv_net_id = '' - task_args = self.rally_base._build_task_args('test_file_name') + os.environ['OS_AUTH_URL'] = '' + self.rally_base.network = None + task_args = self.rally_base.build_task_args('test_name') self.assertEqual(task_args['netid'], '') @staticmethod def check_scenario_file(value): - yaml_file = 'opnfv-{}.yaml'.format('test_file_name') + yaml_file = 'opnfv-test_file_name.yaml' if yaml_file in value: return False return True @@ -58,126 +64,128 @@ class OSRallyTesting(unittest.TestCase): @staticmethod def check_temp_dir(value): - yaml_file = 'opnfv-{}.yaml'.format('test_file_name') + yaml_file = 'opnfv-test_file_name.yaml' if yaml_file in value: return True return False + @mock.patch('functest.opnfv_tests.openstack.rally.rally.' + 'RallyBase.get_verifier_deployment_id', return_value='foo') + @mock.patch('subprocess.check_output') + def test_create_rally_deployment(self, mock_exec, mock_get_id): + # pylint: disable=unused-argument + self.assertEqual(rally.RallyBase.create_rally_deployment(), 'foo') + calls = [ + mock.call(['rally', 'deployment', 'destroy', '--deployment', + str(getattr(config.CONF, 'rally_deployment_name'))]), + mock.call().decode("utf-8"), + mock.call(['rally', 'deployment', 'create', '--fromenv', '--name', + str(getattr(config.CONF, 'rally_deployment_name'))], + env=None), + mock.call().decode("utf-8"), + mock.call(['rally', 'deployment', 'check']), + mock.call().decode("utf-8")] + mock_exec.assert_has_calls(calls) + @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists') @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_apply_blacklist') + 'apply_blacklist') def test_prepare_test_list_missing_temp_dir( self, mock_method, mock_os_makedirs, mock_path_exists): mock_path_exists.side_effect = self.check_temp_dir - yaml_file = 'opnfv-{}.yaml'.format('test_file_name') - ret_val = os.path.join(self.rally_base.TEMP_DIR, yaml_file) + yaml_file = 'opnfv-test_file_name.yaml' + ret_val = os.path.join(self.rally_base.temp_dir, yaml_file) self.assertEqual(self.rally_base._prepare_test_list('test_file_name'), ret_val) mock_path_exists.assert_called() mock_method.assert_called() mock_os_makedirs.assert_called() - def test_get_task_id_default(self): - cmd_raw = 'Task 1: started' - self.assertEqual(self.rally_base.get_task_id(cmd_raw), - '1') + @mock.patch('subprocess.check_output', return_value=b'1\n') + def test_get_task_id_default(self, *args): + tag = 'nova' + self.assertEqual(self.rally_base.get_task_id(tag), '1') + args[0].assert_called_with( + ['rally', 'task', 'list', '--tag', tag, '--uuids-only']) - def test_get_task_id_missing_id(self): - cmd_raw = '' - self.assertEqual(self.rally_base.get_task_id(cmd_raw), - None) + @mock.patch('subprocess.check_output', return_value=b'\n') + def test_get_task_id_missing_id(self, *args): + tag = 'nova' + self.assertEqual(self.rally_base.get_task_id(tag), '') + args[0].assert_called_with( + ['rally', 'task', 'list', '--tag', tag, '--uuids-only']) def test_task_succeed_fail(self): - json_raw = json.dumps([None]) + json_raw = json.dumps({}) self.assertEqual(self.rally_base.task_succeed(json_raw), False) - json_raw = json.dumps([{'result': [{'error': ['test_error']}]}]) + json_raw = json.dumps({'tasks': [{'status': 'crashed'}]}) self.assertEqual(self.rally_base.task_succeed(json_raw), False) def test_task_succeed_success(self): - json_raw = json.dumps('') + json_raw = json.dumps({'tasks': [{'status': 'finished', + 'pass_sla': True}]}) self.assertEqual(self.rally_base.task_succeed(json_raw), True) - def polling(self): - if self.polling_iter == 0: - return "something" - self.polling_iter -= 1 - return None - - def test_get_cmd_output(self): - proc = mock.Mock() - attrs = {'poll.side_effect': self.polling, - 'stdout.readline.return_value': 'line'} - proc.configure_mock(**attrs) - self.assertEqual(self.rally_base.get_cmd_output(proc), - 'lineline') - - @mock.patch('__builtin__.open', mock.mock_open()) + @mock.patch('six.moves.builtins.open', mock.mock_open()) @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load', return_value={'scenario': [ {'scenarios': ['test_scenario'], - 'installers': ['test_installer'], 'tests': ['test']}, {'scenarios': ['other_scenario'], - 'installers': ['test_installer'], 'tests': ['other_test']}]}) def test_excl_scenario_default(self, mock_func): - CONST.__setattr__('INSTALLER_TYPE', 'test_installer') - CONST.__setattr__('DEPLOY_SCENARIO', 'test_scenario') + os.environ['INSTALLER_TYPE'] = 'test_installer' + os.environ['DEPLOY_SCENARIO'] = 'test_scenario' self.assertEqual(self.rally_base.excl_scenario(), ['test']) mock_func.assert_called() - @mock.patch('__builtin__.open', mock.mock_open()) + @mock.patch('six.moves.builtins.open', mock.mock_open()) @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load', return_value={'scenario': [ {'scenarios': ['^os-[^-]+-featT-modeT$'], - 'installers': ['test_installer'], 'tests': ['test1']}, {'scenarios': ['^os-ctrlT-[^-]+-modeT$'], - 'installers': ['test_installer'], 'tests': ['test2']}, {'scenarios': ['^os-ctrlT-featT-[^-]+$'], - 'installers': ['test_installer'], 'tests': ['test3']}, {'scenarios': ['^os-'], - 'installers': ['test_installer'], 'tests': ['test4']}, {'scenarios': ['other_scenario'], - 'installers': ['test_installer'], 'tests': ['test0a']}, {'scenarios': [''], # empty scenario - 'installers': ['test_installer'], 'tests': ['test0b']}]}) def test_excl_scenario_regex(self, mock_func): - CONST.__setattr__('INSTALLER_TYPE', 'test_installer') - CONST.__setattr__('DEPLOY_SCENARIO', 'os-ctrlT-featT-modeT') + os.environ['DEPLOY_SCENARIO'] = 'os-ctrlT-featT-modeT' self.assertEqual(self.rally_base.excl_scenario(), ['test1', 'test2', 'test3', 'test4']) mock_func.assert_called() - @mock.patch('__builtin__.open', side_effect=Exception) + @mock.patch('six.moves.builtins.open', side_effect=Exception) def test_excl_scenario_exception(self, mock_open): self.assertEqual(self.rally_base.excl_scenario(), []) mock_open.assert_called() - @mock.patch('__builtin__.open', mock.mock_open()) + @mock.patch('six.moves.builtins.open', mock.mock_open()) @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load', return_value={'functionality': [ {'functions': ['no_migration'], 'tests': ['test']}]}) @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' '_migration_supported', return_value=False) - def test_excl_func_default(self, mock_func, mock_yaml_load): - CONST.__setattr__('INSTALLER_TYPE', 'test_installer') - CONST.__setattr__('DEPLOY_SCENARIO', 'test_scenario') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + '_network_trunk_supported', return_value=False) + def test_excl_func_default(self, mock_trunk, mock_func, mock_yaml_load): + os.environ['DEPLOY_SCENARIO'] = 'test_scenario' self.assertEqual(self.rally_base.excl_func(), ['test']) mock_func.assert_called() + mock_trunk.assert_called() mock_yaml_load.assert_called() - @mock.patch('__builtin__.open', side_effect=Exception) + @mock.patch('six.moves.builtins.open', side_effect=Exception) def test_excl_func_exception(self, mock_open): self.assertEqual(self.rally_base.excl_func(), []) mock_open.assert_called() @@ -200,61 +208,51 @@ class OSRallyTesting(unittest.TestCase): return_value=False) def test_run_task_missing_task_file(self, mock_path_exists): with self.assertRaises(Exception): - self.rally_base._run_task('test_name') + self.rally_base.prepare_run() mock_path_exists.assert_called() - @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists', - return_value=True) @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' '_prepare_test_list', return_value='test_file_name') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'file_is_empty', return_value=True) @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info') - def test_run_task_no_tests_for_scenario(self, mock_logger_info, - mock_file_empty, mock_prep_list, - mock_path_exists): - self.rally_base._run_task('test_name') + def test_prepare_task_no_tests_for_scenario( + self, mock_logger_info, mock_file_empty, mock_prep_list): + self.rally_base.prepare_task('test_name') mock_logger_info.assert_any_call('No tests for scenario \"%s\"', 'test_name') mock_file_empty.assert_called() mock_prep_list.assert_called() - mock_path_exists.assert_called() @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' '_prepare_test_list', return_value='test_file_name') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'file_is_empty', return_value=False) @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_build_task_args', return_value={}) - @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_get_output') + 'build_task_args', return_value={}) @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'get_task_id', return_value=None) - @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - 'get_cmd_output', return_value='') @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists', return_value=True) @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen') @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error') def test_run_task_taskid_missing(self, mock_logger_error, *args): - self.rally_base._run_task('test_name') - text = 'Failed to retrieve task_id, validating task...' + # pylint: disable=unused-argument + with self.assertRaises(Exception): + self.rally_base.run_task('test_name') + text = 'Failed to retrieve task_id' mock_logger_error.assert_any_call(text) - @mock.patch('__builtin__.open', mock.mock_open()) + @mock.patch('six.moves.builtins.open', mock.mock_open()) @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' '_prepare_test_list', return_value='test_file_name') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'file_is_empty', return_value=False) @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_build_task_args', return_value={}) - @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_get_output') + 'build_task_args', return_value={}) @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'get_task_id', return_value='1') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - 'get_cmd_output', return_value='') - @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'task_succeed', return_value=True) @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists', return_value=True) @@ -262,174 +260,207 @@ class OSRallyTesting(unittest.TestCase): @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs') @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info') @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error') - def test_run_task_default(self, mock_logger_error, mock_logger_info, - *args): - self.rally_base._run_task('test_name') - text = 'Test scenario: "test_name" OK.\n' - mock_logger_info.assert_any_call(text) - mock_logger_error.assert_not_called() - - def test_prepare_env_testname_invalid(self): - self.rally_base.TESTS = ['test1', 'test2'] - self.rally_base.test_name = 'test' - with self.assertRaises(Exception): - self.rally_base._prepare_env() - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_active_compute_cnt') - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_ext_net_name', return_value='test_net_name') - @mock.patch('snaps.openstack.utils.deploy_utils.create_image', - return_value=None) - def test_prepare_env_image_missing( - self, mock_get_img, mock_get_net, mock_get_comp_cnt): - self.rally_base.TESTS = ['test1', 'test2'] - self.rally_base.test_name = 'test1' - with self.assertRaises(Exception): - self.rally_base._prepare_env() - mock_get_img.assert_called() - mock_get_net.assert_called() - mock_get_comp_cnt.assert_called() - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_active_compute_cnt') - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_ext_net_name', return_value='test_net_name') - @mock.patch('snaps.openstack.utils.deploy_utils.create_image') - @mock.patch('snaps.openstack.utils.deploy_utils.create_network', - return_value=None) - def test_prepare_env_network_creation_failed( - self, mock_create_net, mock_get_img, mock_get_net, - mock_get_comp_cnt): - self.rally_base.TESTS = ['test1', 'test2'] - self.rally_base.test_name = 'test1' - with self.assertRaises(Exception): - self.rally_base._prepare_env() - mock_create_net.assert_called() - mock_get_img.assert_called() - mock_get_net.assert_called() - mock_get_comp_cnt.assert_called() - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_active_compute_cnt') - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_ext_net_name', return_value='test_net_name') - @mock.patch('snaps.openstack.utils.deploy_utils.create_image') - @mock.patch('snaps.openstack.utils.deploy_utils.create_network') - @mock.patch('snaps.openstack.utils.deploy_utils.create_router', - return_value=None) - def test_prepare_env_router_creation_failed( - self, mock_create_router, mock_create_net, mock_get_img, - mock_get_net, mock_get_comp_cnt): - self.rally_base.TESTS = ['test1', 'test2'] - self.rally_base.test_name = 'test1' - with self.assertRaises(Exception): - self.rally_base._prepare_env() - mock_create_net.assert_called() - mock_get_img.assert_called() - mock_get_net.assert_called() - mock_create_router.assert_called() - mock_get_comp_cnt.assert_called() - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_active_compute_cnt') - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_ext_net_name', return_value='test_net_name') - @mock.patch('snaps.openstack.utils.deploy_utils.create_image') - @mock.patch('snaps.openstack.utils.deploy_utils.create_network') - @mock.patch('snaps.openstack.utils.deploy_utils.create_router') - @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create', - return_value=None) - def test_prepare_env_flavor_creation_failed( - self, mock_create_flavor, mock_create_router, mock_create_net, - mock_get_img, mock_get_net, mock_get_comp_cnt): - self.rally_base.TESTS = ['test1', 'test2'] - self.rally_base.test_name = 'test1' - with self.assertRaises(Exception): - self.rally_base._prepare_env() - mock_create_net.assert_called() - mock_get_img.assert_called() - mock_get_net.assert_called() - mock_create_router.assert_called() - mock_get_comp_cnt.assert_called() - mock_create_flavor.assert_called_once() - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_active_compute_cnt') - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_ext_net_name', return_value='test_net_name') - @mock.patch('snaps.openstack.utils.deploy_utils.create_image') - @mock.patch('snaps.openstack.utils.deploy_utils.create_network') - @mock.patch('snaps.openstack.utils.deploy_utils.create_router') - @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create', - side_effect=[mock.Mock, None]) - def test_prepare_env_flavor_alt_creation_failed( - self, mock_create_flavor, mock_create_router, mock_create_net, - mock_get_img, mock_get_net, mock_get_comp_cnt): - self.rally_base.TESTS = ['test1', 'test2'] - self.rally_base.test_name = 'test1' + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + '_save_results') + def test_run_task_default(self, mock_save_res, *args): + # pylint: disable=unused-argument + self.rally_base.run_task('test_name') + mock_save_res.assert_called() + + @mock.patch('six.moves.builtins.open', mock.mock_open()) + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + 'task_succeed', return_value=True) + @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists', + return_value=True) + @mock.patch('subprocess.check_output') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.debug') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + '_append_summary') + def test_save_results(self, mock_summary, *args): + # pylint: disable=unused-argument + self.rally_base._save_results('test_name', '1234') + mock_summary.assert_called() + + def test_prepare_run_testname_invalid(self): + self.rally_base.stests = ['test1', 'test2'] with self.assertRaises(Exception): - self.rally_base._prepare_env() - mock_create_net.assert_called() - mock_get_img.assert_called() - mock_get_net.assert_called() - mock_create_router.assert_called() - mock_get_comp_cnt.assert_called() - self.assertEqual(mock_create_flavor.call_count, 2) - - @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_run_task') - def test_run_tests_all(self, mock_run_task): - self.rally_base.TESTS = ['test1', 'test2'] - self.rally_base.test_name = 'all' - self.rally_base._run_tests() + self.rally_base.prepare_run(tests=['test']) + + @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.shutil.copyfile') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.shutil.copytree') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.shutil.rmtree') + def test_prepare_run_flavor_alt_creation_failed(self, *args): + # pylint: disable=unused-argument + self.rally_base.stests = ['test1', 'test2'] + with mock.patch.object(self.rally_base, 'count_hypervisors') \ + as mock_list_hyperv, \ + mock.patch.object(self.rally_base, 'create_flavor_alt', + side_effect=Exception) \ + as mock_create_flavor: + with self.assertRaises(Exception): + self.rally_base.prepare_run(tests=['test1']) + mock_list_hyperv.assert_called_once() + mock_create_flavor.assert_called_once() + + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + 'prepare_task', return_value=True) + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + 'run_task') + def test_run_tests_all(self, mock_run_task, mock_prepare_task): + self.rally_base.tests = ['test1', 'test2'] + self.rally_base.run_tests() + mock_prepare_task.assert_any_call('test1') + mock_prepare_task.assert_any_call('test2') mock_run_task.assert_any_call('test1') mock_run_task.assert_any_call('test2') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_run_task') - def test_run_tests_default(self, mock_run_task): - self.rally_base.TESTS = ['test1', 'test2'] - self.rally_base.test_name = 'test1' - self.rally_base._run_tests() + 'prepare_task', return_value=True) + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + 'run_task') + def test_run_tests_default(self, mock_run_task, mock_prepare_task): + self.rally_base.tests = ['test1', 'test2'] + self.rally_base.run_tests() + mock_prepare_task.assert_any_call('test1') + mock_prepare_task.assert_any_call('test2') mock_run_task.assert_any_call('test1') + mock_run_task.assert_any_call('test2') - def test_clean_up_default(self): - creator1 = mock.Mock() - creator2 = mock.Mock() - self.rally_base.creators = [creator1, creator2] - self.rally_base._clean_up() - self.assertTrue(creator1.clean.called) - self.assertTrue(creator2.clean.called) + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + 'clean_rally_logs') + def test_clean_up_default(self, *args): + with mock.patch.object(self.rally_base.orig_cloud, + 'delete_flavor') as mock_delete_flavor: + self.rally_base.flavor_alt = mock.Mock() + self.rally_base.clean() + self.assertEqual(mock_delete_flavor.call_count, 1) + args[0].assert_called_once_with() - @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.' + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + 'update_rally_logs') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'create_rally_deployment') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_prepare_env') + 'prepare_run') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_run_tests') + 'run_tests') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' '_generate_report') @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_clean_up') + 'export_task') def test_run_default(self, *args): self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_OK) - map(lambda m: m.assert_called(), args) + for func in args: + func.assert_called() - @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.' + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + 'update_rally_logs') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'create_rally_deployment', side_effect=Exception) - def test_run_exception_create_rally_dep(self, mock_create_rally_dep): + def test_run_exception_create_rally_dep(self, *args): self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR) - mock_create_rally_dep.assert_called() + args[0].assert_called() + args[1].assert_called_once_with(self.rally_base.res_dir) @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' - '_prepare_env', side_effect=Exception) - @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.' + 'update_rally_logs') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'create_rally_deployment', return_value=mock.Mock()) - def test_run_exception_prepare_env(self, mock_create_rally_dep, - mock_prep_env): + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' + 'prepare_run', side_effect=Exception) + def test_run_exception_prepare_run(self, mock_prep_env, *args): + # pylint: disable=unused-argument self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR) mock_prep_env.assert_called() + args[1].assert_called_once_with(self.rally_base.res_dir) + + def test_append_summary(self): + json_dict = { + 'tasks': [{ + 'subtasks': [{ + 'title': 'sub_task', + 'workloads': [{ + 'full_duration': 1.23, + 'data': [{ + 'error': [] + }] + }, { + 'full_duration': 2.78, + 'data': [{ + 'error': ['err'] + }] + }] + }] + }] + } + self.rally_base._append_summary(json.dumps(json_dict), "foo_test") + self.assertEqual(self.rally_base.summary[0]['test_name'], "foo_test") + self.assertEqual(self.rally_base.summary[0]['overall_duration'], 4.01) + self.assertEqual(self.rally_base.summary[0]['nb_tests'], 2) + self.assertEqual(self.rally_base.summary[0]['nb_success'], 1) + self.assertEqual(self.rally_base.summary[0]['success'], []) + self.assertEqual(self.rally_base.summary[0]['failures'], ['sub_task']) + + def test_is_successful_false(self): + with mock.patch('six.moves.builtins.super') as mock_super: + self.rally_base.summary = [{"task_status": True}, + {"task_status": False}] + self.assertEqual(self.rally_base.is_successful(), + testcase.TestCase.EX_TESTCASE_FAILED) + mock_super(rally.RallyBase, self).is_successful.assert_not_called() + + def test_is_successful_true(self): + with mock.patch('six.moves.builtins.super') as mock_super: + mock_super(rally.RallyBase, self).is_successful.return_value = 424 + self.rally_base.summary = [{"task_status": True}, + {"task_status": True}] + self.assertEqual(self.rally_base.is_successful(), 424) + mock_super(rally.RallyBase, self).is_successful.assert_called() + + @mock.patch('subprocess.check_output', + side_effect=subprocess.CalledProcessError('', '')) + def test_export_task_ko(self, *args): + file_name = (f"{self.rally_base.results_dir}/" + f"{self.rally_base.case_name}.html") + with self.assertRaises(subprocess.CalledProcessError): + self.rally_base.export_task(file_name) + cmd = ["rally", "task", "export", "--type", "html", "--deployment", + str(getattr(config.CONF, 'rally_deployment_name')), + "--to", file_name] + args[0].assert_called_with(cmd, stderr=subprocess.STDOUT) + + @mock.patch('subprocess.check_output', return_value=b'') + def test_export_task(self, *args): + file_name = (f"{self.rally_base.results_dir}/" + f"{self.rally_base.case_name}.html") + self.assertEqual(self.rally_base.export_task(file_name), None) + cmd = ["rally", "task", "export", "--type", "html", "--deployment", + str(getattr(config.CONF, 'rally_deployment_name')), + "--to", file_name] + args[0].assert_called_with(cmd, stderr=subprocess.STDOUT) + + @mock.patch('subprocess.check_output', + side_effect=subprocess.CalledProcessError('', '')) + def test_verify_report_ko(self, *args): + file_name = (f"{self.rally_base.results_dir}/" + f"{self.rally_base.case_name}.html") + with self.assertRaises(subprocess.CalledProcessError): + self.rally_base.verify_report(file_name, "1") + cmd = ["rally", "verify", "report", "--type", "html", "--uuid", "1", + "--to", file_name] + args[0].assert_called_with(cmd, stderr=subprocess.STDOUT) + + @mock.patch('subprocess.check_output', return_value=b'') + def test_verify_report(self, *args): + file_name = (f"{self.rally_base.results_dir}/" + f"{self.rally_base.case_name}.html") + self.assertEqual(self.rally_base.verify_report(file_name, "1"), None) + cmd = ["rally", "verify", "report", "--type", "html", "--uuid", "1", + "--to", file_name] + args[0].assert_called_with(cmd, stderr=subprocess.STDOUT) if __name__ == "__main__": diff --git a/functest/tests/unit/openstack/refstack_client/__init__.py b/functest/tests/unit/openstack/refstack_client/__init__.py deleted file mode 100644 index e69de29bb..000000000 --- a/functest/tests/unit/openstack/refstack_client/__init__.py +++ /dev/null diff --git a/functest/tests/unit/openstack/refstack_client/test_refstack_client.py b/functest/tests/unit/openstack/refstack_client/test_refstack_client.py deleted file mode 100644 index 61e950a6b..000000000 --- a/functest/tests/unit/openstack/refstack_client/test_refstack_client.py +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2017 Huawei Technologies Co.,Ltd and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -# pylint: disable=missing-docstring - -import logging -import mock -import pkg_resources -import unittest - -from functest.core import testcase -from functest.opnfv_tests.openstack.refstack_client.refstack_client import \ - RefstackClient, RefstackClientParser -from functest.utils.constants import CONST - -from snaps.openstack.os_credentials import OSCreds - -__author__ = ("Matthew Li <matthew.lijun@huawei.com>," - "Linda Wang <wangwulin@huawei.com>") - - -class OSRefstackClientTesting(unittest.TestCase): - """The class testing RefstackClient """ - # pylint: disable=missing-docstring, too-many-public-methods - - _config = pkg_resources.resource_filename( - 'functest', - 'opnfv_tests/openstack/refstack_client/refstack_tempest.conf') - _testlist = pkg_resources.resource_filename( - 'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt') - - def setUp(self): - self.default_args = {'config': self._config, - 'testlist': self._testlist} - CONST.__setattr__('OS_AUTH_URL', 'https://ip:5000/v3') - CONST.__setattr__('OS_INSECURE', 'true') - self.case_name = 'refstack_defcore' - self.result = 0 - self.os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - self.details = {"tests": 3, - "failures": 1, - "success": ['tempest.api.compute [18.464988s]'], - "errors": ['tempest.api.volume [0.230334s]'], - "skipped": ['tempest.api.network [1.265828s]']} - - @mock.patch('functest.opnfv_tests.openstack.refstack_client.tempest_conf.' - 'TempestConf', return_value=mock.Mock()) - def _create_client(self, *args): - with mock.patch('snaps.openstack.tests.openstack_tests.' - 'get_credentials', return_value=self.os_creds): - return RefstackClient() - - def test_run_defcore_insecure(self): - insecure = '-k' - config = 'tempest.conf' - testlist = 'testlist' - client = self._create_client() - with mock.patch('functest.opnfv_tests.openstack.refstack_client.' - 'refstack_client.ft_utils.execute_command') as m_cmd: - cmd = ("refstack-client test {0} -c {1} -v --test-list {2}" - .format(insecure, config, testlist)) - client.run_defcore(config, testlist) - m_cmd.assert_any_call(cmd) - - def test_run_defcore(self): - CONST.__setattr__('OS_AUTH_URL', 'http://ip:5000/v3') - insecure = '' - config = 'tempest.conf' - testlist = 'testlist' - client = self._create_client() - with mock.patch('functest.opnfv_tests.openstack.refstack_client.' - 'refstack_client.ft_utils.execute_command') as m_cmd: - cmd = ("refstack-client test {0} -c {1} -v --test-list {2}" - .format(insecure, config, testlist)) - client.run_defcore(config, testlist) - m_cmd.assert_any_call(cmd) - - @mock.patch('functest.opnfv_tests.openstack.refstack_client.' - 'refstack_client.LOGGER.info') - @mock.patch('__builtin__.open', side_effect=Exception) - def test_parse_refstack_result_fail(self, *args): - self._create_client().parse_refstack_result() - args[1].assert_called_once_with( - "Testcase %s success_rate is %s%%", - self.case_name, self.result) - - def test_parse_refstack_result_ok(self): - log_file = (''' - {0} tempest.api.compute [18.464988s] ... ok - {0} tempest.api.volume [0.230334s] ... FAILED - {0} tempest.api.network [1.265828s] ... SKIPPED: - Ran: 3 tests in 1259.0000 sec. - - Passed: 1 - - Skipped: 1 - - Failed: 1 - ''') - client = self._create_client() - with mock.patch('__builtin__.open', - mock.mock_open(read_data=log_file)): - client.parse_refstack_result() - self.assertEqual(client.details, self.details) - - def _get_main_kwargs(self, key=None): - kwargs = {'config': self._config, - 'testlist': self._testlist} - if key: - del kwargs[key] - return kwargs - - def _test_main_missing_keyword(self, key): - kwargs = self._get_main_kwargs(key) - client = self._create_client() - self.assertEqual(client.main(**kwargs), - testcase.TestCase.EX_RUN_ERROR) - - def test_main_missing_conf(self): - self._test_main_missing_keyword('config') - - def test_main_missing_testlist(self): - self._test_main_missing_keyword('testlist') - - def _test_argparser(self, arg, value): - self.default_args[arg] = value - parser = RefstackClientParser() - self.assertEqual(parser.parse_args(["--{}={}".format(arg, value)]), - self.default_args) - - def test_argparser_conf(self): - self._test_argparser('config', self._config) - - def test_argparser_testlist(self): - self._test_argparser('testlist', self._testlist) - - def test_argparser_multiple_args(self): - self.default_args['config'] = self._config - self.default_args['testlist'] = self._testlist - parser = RefstackClientParser() - self.assertEqual(parser.parse_args( - ["--config={}".format(self._config), - "--testlist={}".format(self._testlist) - ]), self.default_args) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/openstack/snaps/__init__.py b/functest/tests/unit/openstack/snaps/__init__.py deleted file mode 100644 index e69de29bb..000000000 --- a/functest/tests/unit/openstack/snaps/__init__.py +++ /dev/null diff --git a/functest/tests/unit/openstack/snaps/test_snaps.py b/functest/tests/unit/openstack/snaps/test_snaps.py deleted file mode 100644 index 83d6341f7..000000000 --- a/functest/tests/unit/openstack/snaps/test_snaps.py +++ /dev/null @@ -1,228 +0,0 @@ -# Copyright (c) 2017 Cable Television Laboratories, Inc. and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# -# http://www.apache.org/licenses/LICENSE-2.0 - -import mock -import os -import unittest - -from snaps.openstack.os_credentials import OSCreds - -from functest.core.testcase import TestCase -from functest.opnfv_tests.openstack.snaps import (connection_check, api_check, - health_check, smoke) - - -class ConnectionCheckTesting(unittest.TestCase): - """ - Ensures the VPingUserdata class can run in Functest. This test does not - actually connect with an OpenStack pod. - """ - - def setUp(self): - self.os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - - self.connection_check = connection_check.ConnectionCheck( - os_creds=self.os_creds, ext_net_name='foo') - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_client_tests') - def test_run_success(self, add_os_client_tests): - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = [] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.connection_check.run()) - self.assertEquals(TestCase.EX_OK, - self.connection_check.is_successful()) - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_client_tests') - def test_run_1_of_100_failures(self, add_os_client_tests): - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = ['foo'] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.connection_check.run()) - self.assertEquals(TestCase.EX_TESTCASE_FAILED, - self.connection_check.is_successful()) - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_client_tests') - def test_run_1_of_100_failures_within_criteria(self, add_os_client_tests): - self.connection_check.criteria = 90 - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = ['foo'] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.connection_check.run()) - self.assertEquals(TestCase.EX_OK, - self.connection_check.is_successful()) - - -class APICheckTesting(unittest.TestCase): - """ - Ensures the VPingUserdata class can run in Functest. This test does not - actually connect with an OpenStack pod. - """ - - def setUp(self): - self.os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - - self.api_check = api_check.ApiCheck( - os_creds=self.os_creds, ext_net_name='foo') - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_api_tests') - def test_run_success(self, add_tests): - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = [] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.api_check.run()) - self.assertEquals(TestCase.EX_OK, - self.api_check.is_successful()) - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_api_tests') - def test_run_1_of_100_failures(self, add_tests): - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = ['foo'] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.api_check.run()) - self.assertEquals(TestCase.EX_TESTCASE_FAILED, - self.api_check.is_successful()) - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_api_tests') - def test_run_1_of_100_failures_within_criteria(self, add_tests): - self.api_check.criteria = 90 - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = ['foo'] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.api_check.run()) - self.assertEquals(TestCase.EX_OK, - self.api_check.is_successful()) - - -class HealthCheckTesting(unittest.TestCase): - """ - Ensures the VPingUserdata class can run in Functest. This test does not - actually connect with an OpenStack pod. - """ - - def setUp(self): - self.os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - - self.health_check = health_check.HealthCheck( - os_creds=self.os_creds, ext_net_name='foo') - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_client_tests') - def test_run_success(self, add_tests): - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = [] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.health_check.run()) - self.assertEquals(TestCase.EX_OK, - self.health_check.is_successful()) - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_client_tests') - def test_run_1_of_100_failures(self, add_tests): - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = ['foo'] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.health_check.run()) - self.assertEquals(TestCase.EX_TESTCASE_FAILED, - self.health_check.is_successful()) - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_client_tests') - def test_run_1_of_100_failures_within_criteria(self, add_tests): - self.health_check.criteria = 90 - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = ['foo'] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.health_check.run()) - self.assertEquals(TestCase.EX_OK, - self.health_check.is_successful()) - - -class SmokeTesting(unittest.TestCase): - """ - Ensures the VPingUserdata class can run in Functest. This test does not - actually connect with an OpenStack pod. - """ - - def setUp(self): - self.os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - - self.smoke = smoke.SnapsSmoke( - os_creds=self.os_creds, ext_net_name='foo') - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_integration_tests') - @mock.patch('os.path.join', return_value=os.getcwd()) - def test_run_success(self, add_tests, cwd): - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = [] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.smoke.run()) - self.assertEquals(TestCase.EX_OK, - self.smoke.is_successful()) - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_integration_tests') - @mock.patch('os.path.join', return_value=os.getcwd()) - def test_run_1_of_100_failures(self, add_tests, cwd): - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = ['foo'] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.smoke.run()) - self.assertEquals(TestCase.EX_TESTCASE_FAILED, - self.smoke.is_successful()) - - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_suite_builder.' - 'add_openstack_integration_tests') - @mock.patch('os.path.join', return_value=os.getcwd()) - def test_run_1_of_100_failures_within_criteria(self, add_tests, cwd): - self.smoke.criteria = 90 - result = mock.MagicMock(name='unittest.TextTestResult') - result.testsRun = 100 - result.failures = ['foo'] - result.errors = [] - with mock.patch('unittest.TextTestRunner.run', return_value=result): - self.assertEquals(TestCase.EX_OK, self.smoke.run()) - self.assertEquals(TestCase.EX_OK, - self.smoke.is_successful()) diff --git a/functest/tests/unit/openstack/tempest/test_conf_utils.py b/functest/tests/unit/openstack/tempest/test_conf_utils.py deleted file mode 100644 index 7eeffdd67..000000000 --- a/functest/tests/unit/openstack/tempest/test_conf_utils.py +++ /dev/null @@ -1,340 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -import logging -import unittest - -import mock - -from functest.opnfv_tests.openstack.tempest import tempest, conf_utils -from functest.utils.constants import CONST -from snaps.openstack.os_credentials import OSCreds - - -class OSTempestConfUtilsTesting(unittest.TestCase): - - def setUp(self): - self.os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - - @mock.patch('snaps.openstack.utils.deploy_utils.create_project', - return_value=mock.Mock()) - @mock.patch('snaps.openstack.utils.deploy_utils.create_user', - return_value=mock.Mock()) - @mock.patch('snaps.openstack.utils.deploy_utils.create_network', - return_value=None) - @mock.patch('snaps.openstack.utils.deploy_utils.create_image', - return_value=mock.Mock()) - def test_create_tempest_resources_missing_network_dic(self, *mock_args): - tempest_resources = tempest.TempestResourcesManager(os_creds={}) - with self.assertRaises(Exception) as context: - tempest_resources.create() - msg = 'Failed to create private network' - self.assertTrue(msg in context.exception) - - @mock.patch('snaps.openstack.utils.deploy_utils.create_project', - return_value=mock.Mock()) - @mock.patch('snaps.openstack.utils.deploy_utils.create_user', - return_value=mock.Mock()) - @mock.patch('snaps.openstack.utils.deploy_utils.create_network', - return_value=mock.Mock()) - @mock.patch('snaps.openstack.utils.deploy_utils.create_image', - return_value=None) - def test_create_tempest_resources_missing_image(self, *mock_args): - tempest_resources = tempest.TempestResourcesManager(os_creds={}) - - with self.assertRaises(Exception) as context: - tempest_resources.create() - msg = 'Failed to create image' - self.assertTrue(msg in context.exception, msg=str(context.exception)) - - @mock.patch('snaps.openstack.utils.deploy_utils.create_project', - return_value=mock.Mock()) - @mock.patch('snaps.openstack.utils.deploy_utils.create_user', - return_value=mock.Mock()) - @mock.patch('snaps.openstack.utils.deploy_utils.create_network', - return_value=mock.Mock()) - @mock.patch('snaps.openstack.utils.deploy_utils.create_image', - return_value=mock.Mock()) - @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create', - return_value=None) - def test_create_tempest_resources_missing_flavor(self, *mock_args): - tempest_resources = tempest.TempestResourcesManager( - os_creds=self.os_creds) - - CONST.__setattr__('tempest_use_custom_flavors', 'True') - with self.assertRaises(Exception) as context: - tempest_resources.create() - msg = 'Failed to create flavor' - self.assertTrue(msg in context.exception, msg=str(context.exception)) - - CONST.__setattr__('tempest_use_custom_flavors', 'False') - with self.assertRaises(Exception) as context: - tempest_resources.create(use_custom_flavors=True) - msg = 'Failed to create flavor' - self.assertTrue(msg in context.exception, msg=str(context.exception)) - - @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils' - '.logger.info') - @mock.patch('functest.utils.functest_utils.execute_command_raise') - @mock.patch('functest.utils.functest_utils.execute_command') - def test_create_rally_deployment(self, mock_exec, mock_exec_raise, - mock_logger_info): - - conf_utils.create_rally_deployment() - - cmd = "rally deployment destroy opnfv-rally" - error_msg = "Deployment %s does not exist." % \ - CONST.__getattribute__('rally_deployment_name') - mock_logger_info.assert_any_call("Creating Rally environment...") - mock_exec.assert_any_call(cmd, error_msg=error_msg, verbose=False) - - cmd = "rally deployment create --fromenv --name=" - cmd += CONST.__getattribute__('rally_deployment_name') - error_msg = "Problem while creating Rally deployment" - mock_exec_raise.assert_any_call(cmd, error_msg=error_msg) - - cmd = "rally deployment check" - error_msg = ("OpenStack not responding or " - "faulty Rally deployment.") - mock_exec_raise.assert_any_call(cmd, error_msg=error_msg) - - @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils' - '.logger.debug') - def test_create_verifier(self, mock_logger_debug): - mock_popen = mock.Mock() - attrs = {'poll.return_value': None, - 'stdout.readline.return_value': '0'} - mock_popen.configure_mock(**attrs) - - CONST.__setattr__('tempest_verifier_name', 'test_veifier_name') - with mock.patch('functest.utils.functest_utils.execute_command_raise', - side_effect=Exception), \ - self.assertRaises(Exception): - conf_utils.create_verifier() - mock_logger_debug.assert_any_call("Tempest test_veifier_name" - " does not exist") - - @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.' - 'create_verifier', return_value=mock.Mock()) - @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.' - 'create_rally_deployment', return_value=mock.Mock()) - def test_get_verifier_id_missing_verifier(self, mock_rally, mock_tempest): - CONST.__setattr__('tempest_verifier_name', 'test_verifier_name') - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.subprocess.Popen') as mock_popen, \ - self.assertRaises(Exception): - mock_stdout = mock.Mock() - attrs = {'stdout.readline.return_value': ''} - mock_stdout.configure_mock(**attrs) - mock_popen.return_value = mock_stdout - conf_utils.get_verifier_id() - - @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.' - 'create_verifier', return_value=mock.Mock()) - @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.' - 'create_rally_deployment', return_value=mock.Mock()) - def test_get_verifier_id_default(self, mock_rally, mock_tempest): - CONST.__setattr__('tempest_verifier_name', 'test_verifier_name') - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.subprocess.Popen') as mock_popen: - mock_stdout = mock.Mock() - attrs = {'stdout.readline.return_value': 'test_deploy_id'} - mock_stdout.configure_mock(**attrs) - mock_popen.return_value = mock_stdout - - self.assertEqual(conf_utils.get_verifier_id(), - 'test_deploy_id') - - def test_get_verifier_deployment_id_missing_rally(self): - CONST.__setattr__('tempest_verifier_name', 'test_deploy_name') - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.subprocess.Popen') as mock_popen, \ - self.assertRaises(Exception): - mock_stdout = mock.Mock() - attrs = {'stdout.readline.return_value': ''} - mock_stdout.configure_mock(**attrs) - mock_popen.return_value = mock_stdout - conf_utils.get_verifier_deployment_id(), - - def test_get_verifier_deployment_id_default(self): - CONST.__setattr__('tempest_verifier_name', 'test_deploy_name') - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.subprocess.Popen') as mock_popen: - mock_stdout = mock.Mock() - attrs = {'stdout.readline.return_value': 'test_deploy_id'} - mock_stdout.configure_mock(**attrs) - mock_popen.return_value = mock_stdout - - self.assertEqual(conf_utils.get_verifier_deployment_id(), - 'test_deploy_id') - - def test_get_verifier_repo_dir_default(self): - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.os.path.join', - return_value='test_verifier_repo_dir'), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.get_verifier_id') as m: - self.assertEqual(conf_utils.get_verifier_repo_dir(''), - 'test_verifier_repo_dir') - self.assertTrue(m.called) - - def test_get_verifier_deployment_dir_default(self): - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.os.path.join', - return_value='test_verifier_repo_dir'), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.get_verifier_id') as m1, \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.get_verifier_deployment_id') as m2: - self.assertEqual(conf_utils.get_verifier_deployment_dir('', ''), - 'test_verifier_repo_dir') - self.assertTrue(m1.called) - self.assertTrue(m2.called) - - def test_backup_tempest_config_default(self): - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.os.path.exists', - return_value=False), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.os.makedirs') as m1, \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.shutil.copyfile') as m2: - conf_utils.backup_tempest_config('test_conf_file') - self.assertTrue(m1.called) - self.assertTrue(m2.called) - - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.os.path.exists', - return_value=True), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.shutil.copyfile') as m2: - conf_utils.backup_tempest_config('test_conf_file') - self.assertTrue(m2.called) - - def test_configure_tempest_default(self): - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.configure_verifier', - return_value='test_conf_file'), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.configure_tempest_update_params') as m1: - conf_utils.configure_tempest('test_dep_dir') - self.assertTrue(m1.called) - - def test_configure_tempest_defcore_default(self): - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.configure_verifier', - return_value='test_conf_file'), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.configure_tempest_update_params'), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.ConfigParser.RawConfigParser.' - 'set') as mset, \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.ConfigParser.RawConfigParser.' - 'read') as mread, \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.ConfigParser.RawConfigParser.' - 'write') as mwrite, \ - mock.patch('__builtin__.open', mock.mock_open()), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.generate_test_accounts_file'), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.shutil.copyfile'): - conf_utils.configure_tempest_defcore( - 'test_dep_dir', 'test_image_id', 'test_flavor_id', - 'test_image_alt_id', 'test_flavor_alt_id', 'test_tenant_id') - mset.assert_any_call('compute', 'image_ref', 'test_image_id') - mset.assert_any_call('compute', 'image_ref_alt', - 'test_image_alt_id') - mset.assert_any_call('compute', 'flavor_ref', 'test_flavor_id') - mset.assert_any_call('compute', 'flavor_ref_alt', - 'test_flavor_alt_id') - self.assertTrue(mread.called) - self.assertTrue(mwrite.called) - - def test_generate_test_accounts_file_default(self): - with mock.patch("__builtin__.open", mock.mock_open()), \ - mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.' - 'yaml.dump') as mock_dump: - conf_utils.generate_test_accounts_file('test_tenant_id') - self.assertTrue(mock_dump.called) - - def _test_missing_param(self, params, image_id, flavor_id): - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.ConfigParser.RawConfigParser.' - 'set') as mset, \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.ConfigParser.RawConfigParser.' - 'read') as mread, \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.ConfigParser.RawConfigParser.' - 'write') as mwrite, \ - mock.patch('__builtin__.open', mock.mock_open()), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.backup_tempest_config'), \ - mock.patch('functest.utils.functest_utils.yaml.safe_load', - return_value={'validation': {'ssh_timeout': 300}}): - CONST.__setattr__('OS_ENDPOINT_TYPE', None) - conf_utils.configure_tempest_update_params( - 'test_conf_file', image_id=image_id, flavor_id=flavor_id) - mset.assert_any_call(params[0], params[1], params[2]) - self.assertTrue(mread.called) - self.assertTrue(mwrite.called) - - def test_configure_tempest_update_params_missing_image_id(self): - self._test_missing_param(('compute', 'image_ref', - 'test_image_id'), 'test_image_id', - None) - - def test_configure_tempest_update_params_missing_image_id_alt(self): - conf_utils.IMAGE_ID_ALT = 'test_image_id_alt' - self._test_missing_param(('compute', 'image_ref_alt', - 'test_image_id_alt'), None, None) - - def test_configure_tempest_update_params_missing_flavor_id(self): - CONST.__setattr__('tempest_use_custom_flavors', 'True') - self._test_missing_param(('compute', 'flavor_ref', - 'test_flavor_id'), None, - 'test_flavor_id') - - def test_configure_tempest_update_params_missing_flavor_id_alt(self): - CONST.__setattr__('tempest_use_custom_flavors', 'True') - conf_utils.FLAVOR_ID_ALT = 'test_flavor_id_alt' - self._test_missing_param(('compute', 'flavor_ref_alt', - 'test_flavor_id_alt'), None, - None) - - def test_configure_verifier_missing_temp_conf_file(self): - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.os.path.isfile', - return_value=False), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.ft_utils.execute_command') as mexe, \ - self.assertRaises(Exception) as context: - conf_utils.configure_verifier('test_dep_dir') - mexe.assert_any_call("rally verify configure-verifier") - msg = ("Tempest configuration file 'test_dep_dir/tempest.conf'" - " NOT found.") - self.assertTrue(msg in context) - - def test_configure_verifier_default(self): - with mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.os.path.isfile', - return_value=True), \ - mock.patch('functest.opnfv_tests.openstack.tempest.' - 'conf_utils.ft_utils.execute_command') as mexe: - self.assertEqual(conf_utils.configure_verifier('test_dep_dir'), - 'test_dep_dir/tempest.conf') - mexe.assert_any_call("rally verify configure-verifier " - "--reconfigure") - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/openstack/tempest/test_tempest.py b/functest/tests/unit/openstack/tempest/test_tempest.py index 6fe103f18..efc4393c8 100644 --- a/functest/tests/unit/openstack/tempest/test_tempest.py +++ b/functest/tests/unit/openstack/tempest/test_tempest.py @@ -5,164 +5,185 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 +# pylint: disable=missing-docstring + import logging +import os import unittest import mock +from xtesting.core import testcase -from functest.core import testcase +from functest.opnfv_tests.openstack.rally import rally from functest.opnfv_tests.openstack.tempest import tempest -from functest.opnfv_tests.openstack.tempest import conf_utils -from functest.utils.constants import CONST - -from snaps.openstack.os_credentials import OSCreds +from functest.utils import config class OSTempestTesting(unittest.TestCase): + # pylint: disable=too-many-public-methods def setUp(self): - os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - - with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'conf_utils.get_verifier_id', - return_value='test_deploy_id'), \ - mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'conf_utils.get_verifier_deployment_id', - return_value='test_deploy_id'), \ - mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'conf_utils.get_verifier_repo_dir', - return_value='test_verifier_repo_dir'), \ - mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'conf_utils.get_verifier_deployment_dir', - return_value='test_verifier_deploy_dir'), \ - mock.patch('snaps.openstack.tests.openstack_tests.get_credentials', - return_value=os_creds): + with mock.patch('os_client_config.get_config'), \ + mock.patch('shade.OpenStackCloud'), \ + mock.patch('functest.core.tenantnetwork.NewProject'), \ + mock.patch('functest.opnfv_tests.openstack.rally.rally.' + 'RallyBase.create_rally_deployment'), \ + mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' + 'TempestCommon.create_verifier'), \ + mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' + 'TempestCommon.get_verifier_id', + return_value='test_deploy_id'), \ + mock.patch('functest.opnfv_tests.openstack.rally.rally.' + 'RallyBase.get_verifier_deployment_id', + return_value='test_deploy_id'), \ + mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' + 'TempestCommon.get_verifier_repo_dir', + return_value='test_verifier_repo_dir'), \ + mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' + 'TempestCommon.get_verifier_deployment_dir', + return_value='test_verifier_deploy_dir'), \ + mock.patch('os_client_config.make_shade'): self.tempestcommon = tempest.TempestCommon() - self.tempestsmoke_serial = tempest.TempestSmokeSerial() - self.tempestsmoke_parallel = tempest.TempestSmokeParallel() - self.tempestfull_parallel = tempest.TempestFullParallel() - self.tempestcustom = tempest.TempestCustom() - self.tempestdefcore = tempest.TempestDefcore() - - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.logger.debug') - def test_generate_test_list_defcore_mode(self, mock_logger_debug): - self.tempestcommon.MODE = 'defcore' - with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'shutil.copyfile') as m: - self.tempestcommon.generate_test_list('test_verifier_repo_dir') - self.assertTrue(m.called) - - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.logger.error') - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.logger.debug') - def test_generate_test_list_custom_mode_missing_file(self, - mock_logger_debug, - mock_logger_error): - self.tempestcommon.MODE = 'custom' + + @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.error') + @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.debug') + def test_gen_tl_cm_missing_file(self, mock_logger_debug, + mock_logger_error): + # pylint: disable=unused-argument + self.tempestcommon.mode = 'custom' with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' 'os.path.isfile', return_value=False), \ self.assertRaises(Exception) as context: msg = "Tempest test list file %s NOT found." - self.tempestcommon.generate_test_list('test_verifier_repo_dir') - self.assertTrue((msg % conf_utils.TEMPEST_CUSTOM) in context) + self.tempestcommon.generate_test_list() + self.assertTrue( + (msg % self.tempestcommon.tempest_custom) in context.exception) - def test_generate_test_list_custom_mode_default(self): - self.tempestcommon.MODE = 'custom' + @mock.patch('subprocess.check_output') + @mock.patch('os.remove') + def test_gen_tl_cm_default(self, *args): + self.tempestcommon.mode = 'custom' with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'shutil.copyfile') as m, \ + 'shutil.copyfile') as mock_copyfile, \ mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' 'os.path.isfile', return_value=True): - self.tempestcommon.generate_test_list('test_verifier_repo_dir') - self.assertTrue(m.called) - - def _test_generate_test_list_mode_default(self, mode): - self.tempestcommon.MODE = mode - if self.tempestcommon.MODE == 'smoke': - testr_mode = "smoke" - elif self.tempestcommon.MODE == 'full': - testr_mode = "" + self.tempestcommon.generate_test_list() + self.assertTrue(mock_copyfile.called) + args[0].assert_called_once_with('/etc/tempest.conf') + + @mock.patch('os.remove') + @mock.patch('shutil.copyfile') + @mock.patch('subprocess.check_output') + def _test_gen_tl_mode_default(self, mode, *args): + if mode == 'smoke': + testr_mode = r'^tempest\.(api|scenario).*\[.*\bsmoke\b.*\]$' + elif mode == 'full': + testr_mode = r'^tempest\.' else: - testr_mode = 'tempest.api.' + self.tempestcommon.MODE - conf_utils.TEMPEST_RAW_LIST = 'raw_list' + testr_mode = self.tempestcommon.mode verifier_repo_dir = 'test_verifier_repo_dir' - with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'ft_utils.execute_command') as m: - cmd = ("cd {0};" - "testr list-tests {1} > {2};" - "cd -;".format(verifier_repo_dir, - testr_mode, - conf_utils.TEMPEST_RAW_LIST)) - self.tempestcommon.generate_test_list('test_verifier_repo_dir') - m.assert_any_call(cmd) - - def test_generate_test_list_smoke_mode(self): - self._test_generate_test_list_mode_default('smoke') - - def test_generate_test_list_full_mode(self): - self._test_generate_test_list_mode_default('full') - - def test_parse_verifier_result_missing_verification_uuid(self): - self.tempestcommon.VERIFICATION_ID = None + self.tempestcommon.verifier_repo_dir = verifier_repo_dir + cmd = (f"(cd {verifier_repo_dir}; stestr list '{testr_mode}' > " + f"{self.tempestcommon.list} 2>/dev/null)") + self.tempestcommon.generate_test_list(mode=testr_mode) + args[0].assert_called_once_with(cmd, shell=True) + args[2].assert_called_once_with('/etc/tempest.conf') + + def test_gen_tl_smoke_mode(self): + self._test_gen_tl_mode_default('smoke') + + def test_gen_tl_full_mode(self): + self._test_gen_tl_mode_default('full') + + def test_verif_res_missing_verif_id(self): + self.tempestcommon.verification_id = None with self.assertRaises(Exception): self.tempestcommon.parse_verifier_result() - def test_apply_tempest_blacklist_no_blacklist(self): - with mock.patch('__builtin__.open', mock.mock_open()) as m, \ + def test_backup_config_default(self): + with mock.patch('os.path.exists', return_value=False), \ + mock.patch('os.makedirs') as mock_makedirs, \ + mock.patch('shutil.copyfile') as mock_copyfile: + self.tempestcommon.backup_tempest_config( + 'test_conf_file', res_dir='test_dir') + self.assertTrue(mock_makedirs.called) + self.assertTrue(mock_copyfile.called) + + with mock.patch('os.path.exists', return_value=True), \ + mock.patch('shutil.copyfile') as mock_copyfile: + self.tempestcommon.backup_tempest_config( + 'test_conf_file', res_dir='test_dir') + self.assertTrue(mock_copyfile.called) + + @mock.patch("os.rename") + @mock.patch("os.remove") + @mock.patch("os.path.exists", return_value=True) + def test_apply_missing_blacklist(self, *args): + with mock.patch('six.moves.builtins.open', + mock.mock_open()) as mock_open, \ mock.patch.object(self.tempestcommon, 'read_file', return_value=['test1', 'test2']): - conf_utils.TEMPEST_BLACKLIST = Exception - CONST.__setattr__('INSTALLER_TYPE', 'installer_type') - CONST.__setattr__('DEPLOY_SCENARIO', 'deploy_scenario') - self.tempestcommon.apply_tempest_blacklist() - obj = m() + self.tempestcommon.tempest_blacklist = Exception + os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario' + self.tempestcommon.apply_tempest_blacklist( + self.tempestcommon.tempest_blacklist) + obj = mock_open() obj.write.assert_any_call('test1\n') obj.write.assert_any_call('test2\n') + args[0].assert_called_once_with(self.tempestcommon.raw_list) + args[1].assert_called_once_with(self.tempestcommon.raw_list) + args[2].assert_called_once_with( + self.tempestcommon.list, self.tempestcommon.raw_list) - def test_apply_tempest_blacklist_default(self): + @mock.patch("os.rename") + @mock.patch("os.remove") + @mock.patch("os.path.exists", return_value=True) + def test_apply_blacklist_default(self, *args): item_dict = {'scenarios': ['deploy_scenario'], - 'installers': ['installer_type'], 'tests': ['test2']} - with mock.patch('__builtin__.open', mock.mock_open()) as m, \ + with mock.patch('six.moves.builtins.open', + mock.mock_open()) as mock_open, \ mock.patch.object(self.tempestcommon, 'read_file', return_value=['test1', 'test2']), \ mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' 'yaml.safe_load', return_value=item_dict): - CONST.__setattr__('INSTALLER_TYPE', 'installer_type') - CONST.__setattr__('DEPLOY_SCENARIO', 'deploy_scenario') - self.tempestcommon.apply_tempest_blacklist() - obj = m() + os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario' + self.tempestcommon.apply_tempest_blacklist( + self.tempestcommon.tempest_blacklist) + obj = mock_open() obj.write.assert_any_call('test1\n') self.assertFalse(obj.write.assert_any_call('test2\n')) + args[0].assert_called_once_with(self.tempestcommon.raw_list) + args[1].assert_called_once_with(self.tempestcommon.raw_list) + args[2].assert_called_once_with( + self.tempestcommon.list, self.tempestcommon.raw_list) - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.logger.info') - def test_run_verifier_tests_default(self, mock_logger_info): - with mock.patch('__builtin__.open', mock.mock_open()), \ - mock.patch('__builtin__.iter', return_value=['\} tempest\.']), \ - mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'subprocess.Popen'): - conf_utils.TEMPEST_LIST = 'test_tempest_list' - cmd_line = ("rally verify start --load-list " - "test_tempest_list --detailed") + @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' + 'subprocess.Popen') + @mock.patch('six.moves.builtins.open', mock.mock_open()) + @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.info') + def test_run_verifier_tests_default(self, *args): + self.tempestcommon.tempest_list = 'test_tempest_list' + cmd = ["rally", "verify", "start", "--load-list", + self.tempestcommon.tempest_list] + with self.assertRaises(Exception): self.tempestcommon.run_verifier_tests() - mock_logger_info. \ - assert_any_call("Starting Tempest test suite: '%s'." - % cmd_line) + args[0].assert_any_call("Starting Tempest test suite: '%s'.", cmd) @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' 'os.path.exists', return_value=False) @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs', side_effect=Exception) def test_run_makedirs_ko(self, *args): + # pylint: disable=unused-argument self.assertEqual(self.tempestcommon.run(), testcase.TestCase.EX_RUN_ERROR) @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' 'os.path.exists', return_value=False) @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs') - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'TempestResourcesManager.create', side_effect=Exception) - def test_run_tempest_create_resources_ko(self, *args): + def test_run_create_resources_ko(self, *args): + # pylint: disable=unused-argument self.assertEqual(self.tempestcommon.run(), testcase.TestCase.EX_RUN_ERROR) @@ -170,23 +191,9 @@ class OSTempestTesting(unittest.TestCase): 'os.path.exists', return_value=False) @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs') @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'TempestResourcesManager.create', return_value={}) - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_active_compute_cnt', side_effect=Exception) - def test_run_get_active_compute_cnt_ko(self, *args): - self.assertEqual(self.tempestcommon.run(), - testcase.TestCase.EX_RUN_ERROR) - - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'os.path.exists', return_value=False) - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs') - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'TempestResourcesManager.create', return_value={}) - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_active_compute_cnt', return_value=2) - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'conf_utils.configure_tempest', side_effect=Exception) + 'TempestCommon.configure', side_effect=Exception) def test_run_configure_tempest_ko(self, *args): + # pylint: disable=unused-argument self.assertEqual(self.tempestcommon.run(), testcase.TestCase.EX_RUN_ERROR) @@ -194,27 +201,24 @@ class OSTempestTesting(unittest.TestCase): 'os.path.exists', return_value=False) @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs') @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'TempestResourcesManager.create', return_value={}) - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_active_compute_cnt', return_value=2) - @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'conf_utils.configure_tempest') + 'TempestCommon.configure') def _test_run(self, status, *args): + # pylint: disable=unused-argument self.assertEqual(self.tempestcommon.run(), status) - def test_run_missing_generate_test_list(self): + def test_run_missing_gen_test_list(self): with mock.patch.object(self.tempestcommon, 'generate_test_list', side_effect=Exception): self._test_run(testcase.TestCase.EX_RUN_ERROR) - def test_run_apply_tempest_blacklist_ko(self): + def test_run_apply_blacklist_ko(self): with mock.patch.object(self.tempestcommon, 'generate_test_list'), \ - mock.patch.object(self.tempestcommon, - 'apply_tempest_blacklist', - side_effect=Exception()): + mock.patch.object(self.tempestcommon, + 'apply_tempest_blacklist', + side_effect=Exception()): self._test_run(testcase.TestCase.EX_RUN_ERROR) - def test_run_verifier_tests_ko(self, *args): + def test_run_verifier_tests_ko(self): with mock.patch.object(self.tempestcommon, 'generate_test_list'), \ mock.patch.object(self.tempestcommon, 'apply_tempest_blacklist'), \ @@ -224,7 +228,7 @@ class OSTempestTesting(unittest.TestCase): side_effect=Exception): self._test_run(testcase.TestCase.EX_RUN_ERROR) - def test_run_parse_verifier_result_ko(self, *args): + def test_run_verif_result_ko(self): with mock.patch.object(self.tempestcommon, 'generate_test_list'), \ mock.patch.object(self.tempestcommon, 'apply_tempest_blacklist'), \ @@ -233,13 +237,155 @@ class OSTempestTesting(unittest.TestCase): side_effect=Exception): self._test_run(testcase.TestCase.EX_RUN_ERROR) + @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.TempestCommon.' + 'run', return_value=testcase.TestCase.EX_OK) def test_run(self, *args): - with mock.patch.object(self.tempestcommon, 'generate_test_list'), \ + with mock.patch.object(self.tempestcommon, 'update_rally_regex'), \ + mock.patch.object(self.tempestcommon, 'generate_test_list'), \ mock.patch.object(self.tempestcommon, 'apply_tempest_blacklist'), \ mock.patch.object(self.tempestcommon, 'run_verifier_tests'), \ - mock.patch.object(self.tempestcommon, 'parse_verifier_result'): + mock.patch.object(self.tempestcommon, + 'parse_verifier_result'): self._test_run(testcase.TestCase.EX_OK) + args[0].assert_called_once_with() + + @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.debug') + def test_create_verifier(self, mock_logger_debug): + mock_popen = mock.Mock() + attrs = {'poll.return_value': None, + 'stdout.readline.return_value': '0'} + mock_popen.configure_mock(**attrs) + + setattr(config.CONF, 'tempest_verifier_name', 'test_verifier_name') + with mock.patch('subprocess.Popen', side_effect=Exception), \ + self.assertRaises(Exception): + self.tempestcommon.create_verifier() + mock_logger_debug.assert_any_call("Tempest test_verifier_name" + " does not exist") + + def test_get_verifier_id_default(self): + setattr(config.CONF, 'tempest_verifier_name', 'test_verifier_name') + + with mock.patch('functest.opnfv_tests.openstack.tempest.' + 'tempest.subprocess.Popen') as mock_popen: + attrs = {'return_value.__enter__.return_value.' + 'stdout.readline.return_value': b'test_deploy_id'} + mock_popen.configure_mock(**attrs) + + self.assertEqual(self.tempestcommon.get_verifier_id(), + 'test_deploy_id') + + def test_get_depl_id_default(self): + setattr(config.CONF, 'tempest_verifier_name', 'test_deploy_name') + with mock.patch('functest.opnfv_tests.openstack.tempest.' + 'tempest.subprocess.Popen') as mock_popen: + attrs = {'return_value.__enter__.return_value.' + 'stdout.readline.return_value': b'test_deploy_id'} + mock_popen.configure_mock(**attrs) + + self.assertEqual(rally.RallyBase.get_verifier_deployment_id(), + 'test_deploy_id') + + def test_get_verif_repo_dir_default(self): + with mock.patch('functest.opnfv_tests.openstack.tempest.' + 'tempest.os.path.join', + return_value='test_verifier_repo_dir'): + self.assertEqual(self.tempestcommon.get_verifier_repo_dir(''), + 'test_verifier_repo_dir') + + def test_get_depl_dir_default(self): + with mock.patch('functest.opnfv_tests.openstack.tempest.' + 'tempest.os.path.join', + return_value='test_verifier_repo_dir'): + self.assertEqual( + self.tempestcommon.get_verifier_deployment_dir('', ''), + 'test_verifier_repo_dir') + + def _test_missing_param(self, params, image_id, flavor_id, alt=False): + with mock.patch('six.moves.configparser.RawConfigParser.' + 'set') as mset, \ + mock.patch('six.moves.configparser.RawConfigParser.' + 'read') as mread, \ + mock.patch('six.moves.configparser.RawConfigParser.' + 'write') as mwrite, \ + mock.patch('six.moves.builtins.open', mock.mock_open()), \ + mock.patch('functest.utils.functest_utils.yaml.safe_load', + return_value={'validation': {'ssh_timeout': 300}}): + os.environ['OS_INTERFACE'] = '' + if not alt: + self.tempestcommon.configure_tempest_update_params( + 'test_conf_file', image_id=image_id, + flavor_id=flavor_id) + mset.assert_any_call(params[0], params[1], params[2]) + else: + self.tempestcommon.configure_tempest_update_params( + 'test_conf_file', image_alt_id=image_id, + flavor_alt_id=flavor_id) + mset.assert_any_call(params[0], params[1], params[2]) + self.assertTrue(mread.called) + self.assertTrue(mwrite.called) + + def test_upd_missing_image_id(self): + self._test_missing_param(('compute', 'image_ref', 'test_image_id'), + 'test_image_id', None) + + def test_upd_missing_image_id_alt(self): + self._test_missing_param( + ('compute', 'image_ref_alt', 'test_image_id_alt'), + 'test_image_id_alt', None, alt=True) + + def test_upd_missing_flavor_id(self): + self._test_missing_param(('compute', 'flavor_ref', 'test_flavor_id'), + None, 'test_flavor_id') + + def test_upd_missing_flavor_id_alt(self): + self._test_missing_param( + ('compute', 'flavor_ref_alt', 'test_flavor_id_alt'), + None, 'test_flavor_id_alt', alt=True) + + def test_verif_missing_conf_file(self): + with mock.patch('functest.opnfv_tests.openstack.tempest.' + 'tempest.os.path.isfile', + return_value=False), \ + mock.patch('subprocess.check_output') as mexe, \ + self.assertRaises(Exception) as context: + self.tempestcommon.configure_verifier('test_dep_dir') + mexe.assert_called_once_with("rally verify configure-verifier") + msg = ("Tempest configuration file 'test_dep_dir/tempest.conf'" + " NOT found.") + self.assertTrue(msg in context.exception) + + def test_configure_verifier_default(self): + with mock.patch('functest.opnfv_tests.openstack.tempest.' + 'tempest.os.path.isfile', + return_value=True), \ + mock.patch('subprocess.check_output') as mexe: + self.assertEqual( + self.tempestcommon.configure_verifier('test_dep_dir'), + 'test_dep_dir/tempest.conf') + mexe.assert_called_once_with( + ['rally', 'verify', 'configure-verifier', '--reconfigure', + '--id', str(getattr(config.CONF, 'tempest_verifier_name'))]) + + def test_is_successful_false(self): + with mock.patch('six.moves.builtins.super') as mock_super: + self.tempestcommon.deny_skipping = True + self.tempestcommon.details = {"skipped_number": 2} + self.assertEqual(self.tempestcommon.is_successful(), + testcase.TestCase.EX_TESTCASE_FAILED) + mock_super(tempest.TempestCommon, + self).is_successful.assert_not_called() + + def test_is_successful_true(self): + with mock.patch('six.moves.builtins.super') as mock_super: + self.tempestcommon.deny_skipping = False + self.tempestcommon.details = {"skipped_number": 2} + mock_super(tempest.TempestCommon, + self).is_successful.return_value = 567 + self.assertEqual(self.tempestcommon.is_successful(), 567) + mock_super(tempest.TempestCommon, + self).is_successful.assert_called() if __name__ == "__main__": diff --git a/functest/tests/unit/cli/__init__.py b/functest/tests/unit/openstack/vmtp/__init__.py index e69de29bb..e69de29bb 100644 --- a/functest/tests/unit/cli/__init__.py +++ b/functest/tests/unit/openstack/vmtp/__init__.py diff --git a/functest/tests/unit/openstack/vmtp/test_vmtp.py b/functest/tests/unit/openstack/vmtp/test_vmtp.py new file mode 100644 index 000000000..850273476 --- /dev/null +++ b/functest/tests/unit/openstack/vmtp/test_vmtp.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python + +# Copyright (c) 2018 Orange and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 + +# pylint: disable=missing-docstring + +import logging +import unittest + +import mock +import munch +import shade + +from functest.opnfv_tests.openstack.vmtp import vmtp + + +class VmtpInitTesting(unittest.TestCase): + + def _test_exc_init(self): + testcase = vmtp.Vmtp() + self.assertEqual(testcase.case_name, "vmtp") + self.assertEqual(testcase.result, 0) + for func in ['generate_keys', 'write_config', 'run_vmtp']: + with self.assertRaises(AssertionError): + getattr(testcase, func)() + self.assertEqual(testcase.run(), testcase.EX_RUN_ERROR) + self.assertEqual(testcase.clean(), None) + + @mock.patch('os_client_config.get_config', side_effect=Exception) + def test_init1(self, *args): + self._test_exc_init() + args[0].assert_called_once_with() + + @mock.patch('os_client_config.get_config') + @mock.patch('shade.OpenStackCloud', side_effect=Exception) + def test_init2(self, *args): + self._test_exc_init() + args[0].assert_called_once_with(cloud_config=mock.ANY) + args[1].assert_called_once_with() + + @mock.patch('os_client_config.get_config') + @mock.patch('shade.OpenStackCloud') + def test_case_name(self, *args): + testcase = vmtp.Vmtp(case_name="foo") + self.assertEqual(testcase.case_name, "foo") + args[0].assert_called_once_with(cloud_config=mock.ANY) + args[1].assert_called_once_with() + + +class VmtpTesting(unittest.TestCase): + + def setUp(self): + with mock.patch('os_client_config.get_config'), \ + mock.patch('shade.OpenStackCloud'): + self.testcase = vmtp.Vmtp() + self.testcase.cloud = mock.Mock() + self.testcase.cloud.create_keypair.return_value = munch.Munch( + private_key="priv", public_key="pub", id="id") + + @mock.patch('six.moves.builtins.open') + def test_generate_keys1(self, *args): + self.testcase.generate_keys() + self.testcase.cloud.create_keypair.assert_called_once_with( + f'vmtp_{self.testcase.guid}') + self.testcase.cloud.delete_keypair.assert_called_once_with('id') + calls = [mock.call( + self.testcase.privkey_filename, 'w', encoding='utf-8'), + mock.call( + self.testcase.pubkey_filename, 'w', encoding='utf-8')] + args[0].assert_has_calls(calls, any_order=True) + + @mock.patch('six.moves.builtins.open') + def test_generate_keys2(self, *args): + with mock.patch.object( + self.testcase.cloud, "create_keypair", + side_effect=shade.OpenStackCloudException(None)) as mock_obj, \ + self.assertRaises(shade.OpenStackCloudException): + self.testcase.generate_keys() + mock_obj.assert_called_once_with(f'vmtp_{self.testcase.guid}') + args[0].assert_not_called() + + +if __name__ == "__main__": + logging.disable(logging.CRITICAL) + unittest.main(verbosity=2) diff --git a/functest/tests/unit/cli/commands/__init__.py b/functest/tests/unit/openstack/vping/__init__.py index e69de29bb..e69de29bb 100644 --- a/functest/tests/unit/cli/commands/__init__.py +++ b/functest/tests/unit/openstack/vping/__init__.py diff --git a/functest/tests/unit/openstack/vping/test_vping.py b/functest/tests/unit/openstack/vping/test_vping.py deleted file mode 100644 index dbfb679f2..000000000 --- a/functest/tests/unit/openstack/vping/test_vping.py +++ /dev/null @@ -1,159 +0,0 @@ -# Copyright (c) 2017 Cable Television Laboratories, Inc. and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# -# http://www.apache.org/licenses/LICENSE-2.0 - -import unittest - -import mock - -from snaps.config.keypair import KeypairConfig -from snaps.config.network import NetworkConfig, PortConfig, SubnetConfig -from snaps.config.router import RouterConfig -from snaps.config.security_group import SecurityGroupConfig -from snaps.config.vm_inst import VmInstanceConfig - -from snaps.openstack.create_image import OpenStackImage -from snaps.openstack.create_instance import OpenStackVmInstance -from snaps.openstack.create_keypairs import OpenStackKeypair -from snaps.openstack.create_network import OpenStackNetwork -from snaps.openstack.create_router import OpenStackRouter -from snaps.openstack.create_security_group import OpenStackSecurityGroup - -from snaps.openstack.os_credentials import OSCreds - -from functest.core.testcase import TestCase -from functest.opnfv_tests.openstack.vping import vping_userdata, vping_ssh - - -class VPingUserdataTesting(unittest.TestCase): - """ - Ensures the VPingUserdata class can run in Functest. This test does not - actually connect with an OpenStack pod. - """ - - def setUp(self): - self.os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - - self.vping_userdata = vping_userdata.VPingUserdata( - os_creds=self.os_creds) - - @mock.patch('snaps.openstack.utils.deploy_utils.create_vm_instance') - @mock.patch('functest.opnfv_tests.openstack.vping.vping_base.os.' - 'path.exists', return_value=True) - @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create', - return_value=None) - @mock.patch('snaps.openstack.create_instance.OpenStackVmInstance.' - 'get_port_ip', return_value='10.0.0.1') - @mock.patch('snaps.openstack.create_instance.OpenStackVmInstance.' - 'vm_active', return_value=True) - def test_vping_userdata(self, deploy_vm, path_exists, create_flavor, - get_port_ip, vm_active): - with mock.patch('snaps.openstack.utils.deploy_utils.create_image', - return_value=OpenStackImage(self.os_creds, None)), \ - mock.patch('snaps.openstack.utils.deploy_utils.create_network', - return_value=OpenStackNetwork( - self.os_creds, NetworkConfig(name='foo'))), \ - mock.patch('snaps.openstack.utils.deploy_utils.' - 'create_vm_instance', - return_value=OpenStackVmInstance( - self.os_creds, - VmInstanceConfig( - name='foo', flavor='bar', - port_settings=[PortConfig( - name='foo', network_name='bar')]), - None)), \ - mock.patch('snaps.openstack.create_instance.' - 'OpenStackVmInstance.get_console_output', - return_value='vPing OK'): - self.assertEquals(TestCase.EX_OK, self.vping_userdata.run()) - - -class VPingSSHTesting(unittest.TestCase): - """ - Ensures the VPingUserdata class can run in Functest. This test does not - actually connect with an OpenStack pod. - """ - - def setUp(self): - self.os_creds = OSCreds( - username='user', password='pass', - auth_url='http://foo.com:5000/v3', project_name='bar') - - self.vping_ssh = vping_ssh.VPingSSH( - os_creds=self.os_creds) - - @mock.patch('snaps.openstack.utils.deploy_utils.create_vm_instance') - @mock.patch('functest.opnfv_tests.openstack.vping.vping_base.os.' - 'path.exists', return_value=True) - @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create', - return_value=None) - @mock.patch('snaps.openstack.create_instance.OpenStackVmInstance.' - 'get_port_ip', return_value='10.0.0.1') - @mock.patch('snaps.openstack.create_instance.OpenStackVmInstance.' - 'vm_active', return_value=True) - @mock.patch('snaps.openstack.create_instance.OpenStackVmInstance.' - 'vm_ssh_active', return_value=True) - @mock.patch('snaps.openstack.create_instance.OpenStackVmInstance.' - 'ssh_client', return_value=True) - @mock.patch('scp.SCPClient') - @mock.patch('functest.opnfv_tests.openstack.vping.vping_ssh.' - 'VPingSSH._transfer_ping_script', return_value=True) - @mock.patch('functest.opnfv_tests.openstack.vping.vping_ssh.' - 'VPingSSH._do_vping_ssh', return_value=TestCase.EX_OK) - @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.' - 'get_ext_net_name', return_value='foo') - def test_vping_ssh(self, create_vm, path_exists, - flavor_create, get_port_ip, vm_active, ssh_active, - ssh_client, scp_client, trans_script, do_vping_ssh, - ext_net_name): - os_vm_inst = mock.MagicMock(name='get_console_output') - os_vm_inst.get_console_output.return_value = 'vPing OK' - ssh_client = mock.MagicMock(name='get_transport') - ssh_client.get_transport.return_value = None - scp_client = mock.MagicMock(name='put') - scp_client.put.return_value = None - - with mock.patch('snaps.openstack.utils.deploy_utils.create_image', - return_value=OpenStackImage(self.os_creds, None)), \ - mock.patch('snaps.openstack.utils.deploy_utils.create_network', - return_value=OpenStackNetwork( - self.os_creds, - NetworkConfig( - name='foo', - subnet_settings=[ - SubnetConfig( - name='bar', - cidr='10.0.0.1/24')]))), \ - mock.patch('snaps.openstack.utils.deploy_utils.' - 'create_vm_instance', - return_value=OpenStackVmInstance( - self.os_creds, - VmInstanceConfig( - name='foo', flavor='bar', - port_settings=[PortConfig( - name='foo', network_name='bar')]), - None)), \ - mock.patch('snaps.openstack.utils.deploy_utils.create_keypair', - return_value=OpenStackKeypair( - self.os_creds, KeypairConfig(name='foo'))), \ - mock.patch('snaps.openstack.utils.deploy_utils.create_router', - return_value=OpenStackRouter( - self.os_creds, RouterConfig(name='foo'))), \ - mock.patch('snaps.openstack.utils.deploy_utils.' - 'create_security_group', - return_value=OpenStackSecurityGroup( - self.os_creds, - SecurityGroupConfig(name='foo'))), \ - mock.patch('snaps.openstack.create_instance.' - 'OpenStackVmInstance.' - 'get_vm_inst', return_value=os_vm_inst), \ - mock.patch('snaps.openstack.create_instance.' - 'OpenStackVmInstance.' - 'ssh_client', return_value=ssh_client): - self.assertEquals(TestCase.EX_OK, self.vping_ssh.run()) diff --git a/functest/tests/unit/openstack/vping/test_vping_ssh.py b/functest/tests/unit/openstack/vping/test_vping_ssh.py new file mode 100644 index 000000000..a07148aab --- /dev/null +++ b/functest/tests/unit/openstack/vping/test_vping_ssh.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python + +# Copyright (c) 2018 Orange and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 + +# pylint: disable=missing-docstring + +import logging +import unittest + +from paramiko import ssh_exception +import mock +import munch +import shade + +from functest.opnfv_tests.openstack.vping import vping_ssh +from functest.utils import config + + +class VpingSSHTesting(unittest.TestCase): + + def setUp(self): + with mock.patch('functest.core.singlevm.SingleVm2.__init__'): + self.vping = vping_ssh.VPingSSH() + self.vping.cloud = mock.Mock() + self.vping.case_name = 'vping' + self.vping.guid = '1' + + @mock.patch('functest.core.singlevm.SingleVm2.prepare', + side_effect=Exception) + def test_prepare_exc1(self, *args): + with self.assertRaises(Exception): + self.vping.prepare() + args[0].assert_called_once_with() + + @mock.patch('functest.opnfv_tests.openstack.vping.vping_ssh.VPingSSH.' + 'boot_vm', + side_effect=Exception) + @mock.patch('functest.core.singlevm.SingleVm2.prepare') + def test_prepare_exc2(self, *args): + self.vping.sec = munch.Munch(id='foo') + with self.assertRaises(Exception): + self.vping.prepare() + args[0].assert_called_once_with() + args[1].assert_called_once_with( + f'{self.vping.case_name}-vm2_{self.vping.guid}', + security_groups=[self.vping.sec.id]) + + @mock.patch('functest.opnfv_tests.openstack.vping.vping_ssh.VPingSSH.' + 'boot_vm') + @mock.patch('functest.core.singlevm.SingleVm2.prepare') + def test_prepare(self, *args): + self.vping.sec = munch.Munch(id='foo') + self.vping.prepare() + args[0].assert_called_once_with() + args[1].assert_called_once_with( + f'{self.vping.case_name}-vm2_{self.vping.guid}', + security_groups=[self.vping.sec.id]) + + @mock.patch('functest.opnfv_tests.openstack.vping.vping_ssh.VPingSSH.' + 'check_regex_in_console', return_value=True) + def test_execute_exc(self, *args): + self.vping.vm2 = munch.Munch(private_v4='127.0.0.1', name='foo') + self.vping.ssh = mock.Mock() + self.vping.ssh.exec_command.side_effect = ssh_exception.SSHException + with self.assertRaises(ssh_exception.SSHException): + self.vping.execute() + self.vping.ssh.exec_command.assert_called_once_with( + f'ping -c 1 {self.vping.vm2.private_v4}') + args[0].assert_called_once_with('foo') + + @mock.patch('functest.opnfv_tests.openstack.vping.vping_ssh.VPingSSH.' + 'check_regex_in_console', return_value=False) + def test_execute_exc2(self, *args): + self.vping.vm2 = munch.Munch(private_v4='127.0.0.1', name='foo') + self.vping.ssh = mock.Mock() + self.vping.execute() + self.vping.ssh.exec_command.assert_not_called() + args[0].assert_called_once_with('foo') + + def _test_execute(self, ret=0): + self.vping.vm2 = munch.Munch(private_v4='127.0.0.1', name='foo') + self.vping.ssh = mock.Mock() + stdout = mock.Mock() + stdout.channel.recv_exit_status.return_value = ret + self.vping.ssh.exec_command.return_value = (None, stdout, mock.Mock()) + with mock.patch( + 'functest.opnfv_tests.openstack.vping.vping_ssh.VPingSSH.' + 'check_regex_in_console', return_value=True) as mock_check: + self.assertEqual(self.vping.execute(), ret) + mock_check.assert_called_once_with('foo') + self.vping.ssh.exec_command.assert_called_once_with( + f'ping -c 1 {self.vping.vm2.private_v4}') + + def test_execute1(self): + self._test_execute() + + def test_execute2(self): + self._test_execute(1) + + def test_clean_exc1(self): + self.vping.cloud = None + with self.assertRaises(AssertionError): + self.vping.clean() + + def test_clean_exc2(self): + self.vping.vm2 = munch.Munch(id='vm2') + mdelete_server = self.vping.cloud.delete_server + mdelete_server.side_effect = shade.OpenStackCloudException(None) + with self.assertRaises(shade.OpenStackCloudException): + self.vping.clean() + + @mock.patch('functest.core.singlevm.SingleVm2.clean', + side_effect=Exception) + def test_clean_exc3(self, *args): + self.vping.vm2 = munch.Munch(id='vm2') + with self.assertRaises(Exception): + self.vping.clean() + self.vping.cloud.delete_server.assert_called_once_with( + self.vping.vm2, wait=True, + timeout=getattr(config.CONF, 'vping_vm_delete_timeout')) + args[0].assert_called_once_with() + + @mock.patch('functest.core.singlevm.SingleVm2.clean') + def test_clean1(self, *args): + self.vping.vm2 = None + self.vping.clean() + self.vping.cloud.delete_server.assert_not_called() + args[0].assert_called_once_with() + + @mock.patch('functest.core.singlevm.SingleVm2.clean') + def test_clean2(self, *args): + self.vping.vm2 = munch.Munch(id='vm2') + self.vping.clean() + self.vping.cloud.delete_server.assert_called_once_with( + self.vping.vm2, wait=True, + timeout=getattr(config.CONF, 'vping_vm_delete_timeout')) + args[0].assert_called_once_with() + + +if __name__ == '__main__': + logging.disable(logging.CRITICAL) + unittest.main(verbosity=2) diff --git a/functest/tests/unit/test_utils.py b/functest/tests/unit/test_utils.py deleted file mode 100644 index 159047649..000000000 --- a/functest/tests/unit/test_utils.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -import re - - -class RegexMatch(object): - def __init__(self, msg): - self.msg = msg - - def __eq__(self, other): - match = re.search(self.msg, other) - if match: - return True - return False - - -class SubstrMatch(object): - def __init__(self, msg): - self.msg = msg - - def __eq__(self, other): - if self.msg in other: - return True - return False diff --git a/functest/tests/unit/utils/test_decorators.py b/functest/tests/unit/utils/test_decorators.py deleted file mode 100644 index 82291fa2d..000000000 --- a/functest/tests/unit/utils/test_decorators.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2017 Orange and others. -# -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -"""Define the class required to fully cover decorators.""" - -from datetime import datetime -import errno -import json -import logging -import os -import unittest - -import mock - -from functest.utils import decorators -from functest.utils import functest_utils -from functest.utils.constants import CONST - -__author__ = "Cedric Ollivier <cedric.ollivier@orange.com>" - -VERSION = 'master' -DIR = '/dev' -FILE = '{}/null'.format(DIR) -URL = 'file://{}'.format(FILE) - - -class DecoratorsTesting(unittest.TestCase): - # pylint: disable=missing-docstring - - _case_name = 'base' - _project_name = 'functest' - _start_time = 1.0 - _stop_time = 2.0 - _result = 'PASS' - _build_tag = VERSION - _node_name = 'bar' - _deploy_scenario = 'foo' - _installer_type = 'debian' - - def setUp(self): - os.environ['INSTALLER_TYPE'] = self._installer_type - os.environ['DEPLOY_SCENARIO'] = self._deploy_scenario - os.environ['NODE_NAME'] = self._node_name - os.environ['BUILD_TAG'] = self._build_tag - - def test_wraps(self): - self.assertEqual(functest_utils.push_results_to_db.__name__, - "push_results_to_db") - - def _get_json(self): - stop_time = datetime.fromtimestamp(self._stop_time).strftime( - '%Y-%m-%d %H:%M:%S') - start_time = datetime.fromtimestamp(self._start_time).strftime( - '%Y-%m-%d %H:%M:%S') - data = {'project_name': self._project_name, - 'stop_date': stop_time, 'start_date': start_time, - 'case_name': self._case_name, 'build_tag': self._build_tag, - 'pod_name': self._node_name, 'installer': self._installer_type, - 'scenario': self._deploy_scenario, 'version': VERSION, - 'details': {}, 'criteria': self._result} - return json.dumps(data, sort_keys=True) - - @mock.patch('{}.get_version'.format(functest_utils.__name__), - return_value=VERSION) - @mock.patch('requests.post') - def test_http_shema(self, *args): - CONST.__setattr__('results_test_db_url', 'http://127.0.0.1') - self.assertTrue(functest_utils.push_results_to_db( - self._project_name, self._case_name, self._start_time, - self._stop_time, self._result, {})) - args[1].assert_called_once_with() - args[0].assert_called_once_with( - 'http://127.0.0.1', data=self._get_json(), - headers={'Content-Type': 'application/json'}) - - def test_wrong_shema(self): - CONST.__setattr__('results_test_db_url', '/dev/null') - self.assertFalse(functest_utils.push_results_to_db( - self._project_name, self._case_name, self._start_time, - self._stop_time, self._result, {})) - - @mock.patch('{}.get_version'.format(functest_utils.__name__), - return_value=VERSION) - def _test_dump(self, *args): - CONST.__setattr__('results_test_db_url', URL) - with mock.patch.object(decorators, 'open', mock.mock_open(), - create=True) as mock_open: - self.assertTrue(functest_utils.push_results_to_db( - self._project_name, self._case_name, self._start_time, - self._stop_time, self._result, {})) - mock_open.assert_called_once_with(FILE, 'a') - handle = mock_open() - call_args, _ = handle.write.call_args - self.assertIn('POST', call_args[0]) - self.assertIn(self._get_json(), call_args[0]) - args[0].assert_called_once_with() - - @mock.patch('os.makedirs') - def test_default_dump(self, mock_method=None): - self._test_dump() - mock_method.assert_called_once_with(DIR) - - @mock.patch('os.makedirs', side_effect=OSError(errno.EEXIST, '')) - def test_makedirs_dir_exists(self, mock_method=None): - self._test_dump() - mock_method.assert_called_once_with(DIR) - - @mock.patch('os.makedirs', side_effect=OSError) - def test_makedirs_exc(self, *args): - CONST.__setattr__('results_test_db_url', URL) - self.assertFalse( - functest_utils.push_results_to_db( - self._project_name, self._case_name, self._start_time, - self._stop_time, self._result, {})) - args[0].assert_called_once_with(DIR) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/utils/test_env.py b/functest/tests/unit/utils/test_env.py new file mode 100644 index 000000000..49d2d974c --- /dev/null +++ b/functest/tests/unit/utils/test_env.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +# Copyright (c) 2018 Orange and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 + +# pylint: disable=missing-docstring + +import logging +import os +import unittest + +from six.moves import reload_module + +from functest.utils import env + + +class EnvTesting(unittest.TestCase): + # pylint: disable=missing-docstring + + def setUp(self): + os.environ['FOO'] = 'foo' + os.environ['BUILD_TAG'] = 'master' + os.environ['CI_LOOP'] = 'weekly' + + def test_get_unset_unknown_env(self): + del os.environ['FOO'] + self.assertEqual(env.get('FOO'), None) + + def test_get_unknown_env(self): + self.assertEqual(env.get('FOO'), 'foo') + reload_module(env) + + def test_get_unset_env(self): + del os.environ['CI_LOOP'] + self.assertEqual( + env.get('CI_LOOP'), env.INPUTS['CI_LOOP']) + + def test_get_env(self): + self.assertEqual( + env.get('CI_LOOP'), 'weekly') + + def test_get_unset_env2(self): + del os.environ['BUILD_TAG'] + self.assertEqual( + env.get('BUILD_TAG'), env.INPUTS['BUILD_TAG']) + + def test_get_env2(self): + self.assertEqual(env.get('BUILD_TAG'), 'master') + + +if __name__ == "__main__": + logging.disable(logging.CRITICAL) + unittest.main(verbosity=2) diff --git a/functest/tests/unit/utils/test_functest_utils.py b/functest/tests/unit/utils/test_functest_utils.py index 7a77d25b9..4b642ff9d 100644 --- a/functest/tests/unit/utils/test_functest_utils.py +++ b/functest/tests/unit/utils/test_functest_utils.py @@ -7,22 +7,24 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 +# pylint: disable=missing-docstring + import logging -import pkg_resources -import os import time import unittest import mock -import requests -from six.moves import urllib +import pkg_resources +import six -from functest.tests.unit import test_utils from functest.utils import functest_utils -from functest.utils.constants import CONST class FunctestUtilsTesting(unittest.TestCase): + # pylint: disable=too-many-instance-attributes,too-many-public-methods + + readline = 0 + test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15'] def setUp(self): self.url = 'http://www.opnfv.org/' @@ -53,8 +55,6 @@ class FunctestUtilsTesting(unittest.TestCase): self.cmd = 'test_cmd' self.output_file = 'test_output_file' self.testname = 'testname' - self.testcase_dict = {'case_name': 'testname', - 'criteria': self.criteria} self.parameter = 'general.openstack.image_name' self.config_yaml = pkg_resources.resource_filename( 'functest', 'ci/config_functest.yaml') @@ -63,56 +63,6 @@ class FunctestUtilsTesting(unittest.TestCase): self.file_yaml = {'general': {'openstack': {'image_name': 'test_image_name'}}} - @mock.patch('six.moves.urllib.request.urlopen', - side_effect=urllib.error.URLError('no host given')) - def test_check_internet_connectivity_failed(self, mock_method): - self.assertFalse(functest_utils.check_internet_connectivity()) - mock_method.assert_called_once_with(self.url, timeout=self.timeout) - - @mock.patch('six.moves.urllib.request.urlopen') - def test_check_internet_connectivity_default(self, mock_method): - self.assertTrue(functest_utils.check_internet_connectivity()) - mock_method.assert_called_once_with(self.url, timeout=self.timeout) - - @mock.patch('six.moves.urllib.request.urlopen') - def test_check_internet_connectivity_debian(self, mock_method): - self.url = "https://www.debian.org/" - self.assertTrue(functest_utils.check_internet_connectivity(self.url)) - mock_method.assert_called_once_with(self.url, timeout=self.timeout) - - @mock.patch('six.moves.urllib.request.urlopen', - side_effect=urllib.error.URLError('no host given')) - def test_download_url_failed(self, mock_url): - self.assertFalse(functest_utils.download_url(self.url, self.dest_path)) - - @mock.patch('six.moves.urllib.request.urlopen') - def test_download_url_default(self, mock_url): - with mock.patch("six.moves.builtins.open", mock.mock_open()) as m, \ - mock.patch('functest.utils.functest_utils.shutil.copyfileobj')\ - as mock_sh: - name = self.url.rsplit('/')[-1] - dest = self.dest_path + "/" + name - self.assertTrue(functest_utils.download_url(self.url, - self.dest_path)) - m.assert_called_once_with(dest, 'wb') - self.assertTrue(mock_sh.called) - - def test_get_version_daily_job(self): - CONST.__setattr__('BUILD_TAG', self.build_tag) - self.assertEqual(functest_utils.get_version(), self.version) - - def test_get_version_weekly_job(self): - CONST.__setattr__('BUILD_TAG', self.build_tag_week) - self.assertEqual(functest_utils.get_version(), self.version) - - def test_get_version_with_dummy_build_tag(self): - CONST.__setattr__('BUILD_TAG', 'whatever') - self.assertEqual(functest_utils.get_version(), 'unknown') - - def test_get_version_unknown(self): - CONST.__setattr__('BUILD_TAG', 'unknown_build_tag') - self.assertEqual(functest_utils.get_version(), "unknown") - def _get_env_dict(self, var): dic = {'INSTALLER_TYPE': self.installer, 'DEPLOY_SCENARIO': self.scenario, @@ -121,87 +71,6 @@ class FunctestUtilsTesting(unittest.TestCase): dic.pop(var, None) return dic - def _test_push_results_to_db_missing_env(self, env_var): - dic = self._get_env_dict(env_var) - CONST.__setattr__('results_test_db_url', self.db_url) - with mock.patch.dict(os.environ, - dic, - clear=True), \ - mock.patch('functest.utils.functest_utils.logger.error') \ - as mock_logger_error: - functest_utils.push_results_to_db(self.project, self.case_name, - self.start_date, self.stop_date, - self.result, self.details) - mock_logger_error.assert_called_once_with("Please set env var: " + - str("\'" + env_var + - "\'")) - - def test_push_results_to_db_missing_installer(self): - self._test_push_results_to_db_missing_env('INSTALLER_TYPE') - - def test_push_results_to_db_missing_scenario(self): - self._test_push_results_to_db_missing_env('DEPLOY_SCENARIO') - - def test_push_results_to_db_missing_nodename(self): - self._test_push_results_to_db_missing_env('NODE_NAME') - - def test_push_results_to_db_missing_buildtag(self): - self._test_push_results_to_db_missing_env('BUILD_TAG') - - def test_push_results_to_db_request_post_failed(self): - dic = self._get_env_dict(None) - CONST.__setattr__('results_test_db_url', self.db_url) - with mock.patch.dict(os.environ, - dic, - clear=True), \ - mock.patch('functest.utils.functest_utils.logger.error') \ - as mock_logger_error, \ - mock.patch('functest.utils.functest_utils.requests.post', - side_effect=requests.RequestException): - self.assertFalse(functest_utils. - push_results_to_db(self.project, self.case_name, - self.start_date, - self.stop_date, - self.result, self.details)) - mock_logger_error.assert_called_once_with(test_utils. - RegexMatch("Pushing " - "Result to" - " DB" - "(\S+\s*) " - "failed:")) - - def test_push_results_to_db_request_post_exception(self): - dic = self._get_env_dict(None) - CONST.__setattr__('results_test_db_url', self.db_url) - with mock.patch.dict(os.environ, - dic, - clear=True), \ - mock.patch('functest.utils.functest_utils.logger.error') \ - as mock_logger_error, \ - mock.patch('functest.utils.functest_utils.requests.post', - side_effect=Exception): - self.assertFalse(functest_utils. - push_results_to_db(self.project, self.case_name, - self.start_date, - self.stop_date, - self.result, self.details)) - self.assertTrue(mock_logger_error.called) - - def test_push_results_to_db_default(self): - dic = self._get_env_dict(None) - CONST.__setattr__('results_test_db_url', self.db_url) - with mock.patch.dict(os.environ, - dic, - clear=True), \ - mock.patch('functest.utils.functest_utils.requests.post'): - self.assertTrue(functest_utils. - push_results_to_db(self.project, self.case_name, - self.start_date, - self.stop_date, - self.result, self.details)) - readline = 0 - test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15'] - @staticmethod def readline_side(): if FunctestUtilsTesting.readline == \ @@ -210,173 +79,96 @@ class FunctestUtilsTesting(unittest.TestCase): FunctestUtilsTesting.readline += 1 return FunctestUtilsTesting.test_ip[FunctestUtilsTesting.readline] - # TODO: get_resolvconf_ns - @mock.patch('functest.utils.functest_utils.dns.resolver.Resolver') - def test_get_resolvconf_ns_default(self, mock_dns_resolve): - attrs = {'query.return_value': ["test"]} - mock_dns_resolve.configure_mock(**attrs) - - m = mock.Mock() - attrs = {'readline.side_effect': self.readline_side} - m.configure_mock(**attrs) - - with mock.patch("six.moves.builtins.open") as mo: - mo.return_value = m - self.assertEqual(functest_utils.get_resolvconf_ns(), - self.test_ip[1:]) - - def _get_environ(self, var): + def _get_environ(self, var, *args): # pylint: disable=unused-argument if var == 'INSTALLER_TYPE': return self.installer - elif var == 'DEPLOY_SCENARIO': + if var == 'DEPLOY_SCENARIO': return self.scenario return var - def test_get_ci_envvars_default(self): - with mock.patch('os.environ.get', - side_effect=self._get_environ): - dic = {"installer": self.installer, - "scenario": self.scenario} - self.assertDictEqual(functest_utils.get_ci_envvars(), dic) - - def cmd_readline(self): + @staticmethod + def cmd_readline(): return 'test_value\n' - @mock.patch('functest.utils.functest_utils.logger.error') - @mock.patch('functest.utils.functest_utils.logger.info') - def test_execute_command_args_present_with_error(self, mock_logger_info, - mock_logger_error): + @mock.patch('functest.utils.functest_utils.LOGGER.error') + @mock.patch('functest.utils.functest_utils.LOGGER.info') + def test_exec_cmd_args_present_ko(self, mock_logger_info, + mock_logger_error): with mock.patch('functest.utils.functest_utils.subprocess.Popen') \ as mock_subproc_open, \ mock.patch('six.moves.builtins.open', mock.mock_open()) as mopen: - - FunctestUtilsTesting.readline = 0 - - mock_obj = mock.Mock() - attrs = {'readline.side_effect': self.cmd_readline()} - mock_obj.configure_mock(**attrs) - - mock_obj2 = mock.Mock() - attrs = {'stdout': mock_obj, 'wait.return_value': 1} - mock_obj2.configure_mock(**attrs) - - mock_subproc_open.return_value = mock_obj2 - - resp = functest_utils.execute_command(self.cmd, info=True, - error_msg=self.error_msg, - verbose=True, - output_file=self.output_file) + stream = six.BytesIO() + stream.write(self.cmd_readline().encode("utf-8")) + attrs = { + 'return_value.__enter__.return_value.stdout': stream, + 'return_value.__enter__.return_value.wait.return_value': 1} + mock_subproc_open.configure_mock(**attrs) + resp = functest_utils.execute_command( + self.cmd, info=True, error_msg=self.error_msg, verbose=True, + output_file=self.output_file) self.assertEqual(resp, 1) - msg_exec = ("Executing command: '%s'" % self.cmd) + msg_exec = f"Executing command: '{self.cmd}'" mock_logger_info.assert_called_once_with(msg_exec) - mopen.assert_called_once_with(self.output_file, "w") + mopen.assert_called_once_with( + self.output_file, "w", encoding='utf-8') mock_logger_error.assert_called_once_with(self.error_msg) - @mock.patch('functest.utils.functest_utils.logger.info') - def test_execute_command_args_present_with_success(self, mock_logger_info, - ): + @mock.patch('functest.utils.functest_utils.LOGGER.info') + def test_exec_cmd_args_present_ok(self, mock_logger_info): with mock.patch('functest.utils.functest_utils.subprocess.Popen') \ as mock_subproc_open, \ mock.patch('six.moves.builtins.open', mock.mock_open()) as mopen: - - FunctestUtilsTesting.readline = 0 - - mock_obj = mock.Mock() - attrs = {'readline.side_effect': self.cmd_readline()} - mock_obj.configure_mock(**attrs) - - mock_obj2 = mock.Mock() - attrs = {'stdout': mock_obj, 'wait.return_value': 0} - mock_obj2.configure_mock(**attrs) - - mock_subproc_open.return_value = mock_obj2 - - resp = functest_utils.execute_command(self.cmd, info=True, - error_msg=self.error_msg, - verbose=True, - output_file=self.output_file) + stream = six.BytesIO() + stream.write(self.cmd_readline().encode("utf-8")) + attrs = { + 'return_value.__enter__.return_value.stdout': stream, + 'return_value.__enter__.return_value.wait.return_value': 0} + mock_subproc_open.configure_mock(**attrs) + resp = functest_utils.execute_command( + self.cmd, info=True, error_msg=self.error_msg, verbose=True, + output_file=self.output_file) self.assertEqual(resp, 0) - msg_exec = ("Executing command: '%s'" % self.cmd) + msg_exec = (f"Executing command: '{self.cmd}'") mock_logger_info.assert_called_once_with(msg_exec) - mopen.assert_called_once_with(self.output_file, "w") + mopen.assert_called_once_with( + self.output_file, "w", encoding='utf-8') @mock.patch('sys.stdout') - def test_execute_command_args_missing_with_success(self, stdout=None): + def test_exec_cmd_args_missing_ok(self, stdout=None): + # pylint: disable=unused-argument with mock.patch('functest.utils.functest_utils.subprocess.Popen') \ as mock_subproc_open: - - FunctestUtilsTesting.readline = 2 - - mock_obj = mock.Mock() - attrs = {'readline.side_effect': self.cmd_readline()} - mock_obj.configure_mock(**attrs) - - mock_obj2 = mock.Mock() - attrs = {'stdout': mock_obj, 'wait.return_value': 0} - mock_obj2.configure_mock(**attrs) - - mock_subproc_open.return_value = mock_obj2 - - resp = functest_utils.execute_command(self.cmd, info=False, - error_msg="", - verbose=False, - output_file=None) + stream = six.BytesIO() + stream.write(self.cmd_readline().encode("utf-8")) + attrs = { + 'return_value.__enter__.return_value.stdout': stream, + 'return_value.__enter__.return_value.wait.return_value': 0} + mock_subproc_open.configure_mock(**attrs) + resp = functest_utils.execute_command( + self.cmd, info=False, error_msg="", verbose=False, + output_file=None) self.assertEqual(resp, 0) @mock.patch('sys.stdout') - def test_execute_command_args_missing_with_error(self, stdout=None): + def test_exec_cmd_args_missing_ko(self, stdout=None): + # pylint: disable=unused-argument with mock.patch('functest.utils.functest_utils.subprocess.Popen') \ as mock_subproc_open: - - FunctestUtilsTesting.readline = 2 - mock_obj = mock.Mock() - attrs = {'readline.side_effect': self.cmd_readline()} - mock_obj.configure_mock(**attrs) - - mock_obj2 = mock.Mock() - attrs = {'stdout': mock_obj, 'wait.return_value': 1} - mock_obj2.configure_mock(**attrs) - - mock_subproc_open.return_value = mock_obj2 - - resp = functest_utils.execute_command(self.cmd, info=False, - error_msg="", - verbose=False, - output_file=None) + attrs = {} + stream = six.BytesIO() + stream.write(self.cmd_readline().encode("utf-8")) + attrs = { + 'return_value.__enter__.return_value.stdout': stream, + 'return_value.__enter__.return_value.wait.return_value': 1} + mock_subproc_open.configure_mock(**attrs) + resp = functest_utils.execute_command( + self.cmd, info=False, error_msg="", verbose=False, + output_file=None) self.assertEqual(resp, 1) - def _get_functest_config(self, var): - return var - - @mock.patch('functest.utils.functest_utils.logger.error') - def test_get_dict_by_test(self, mock_logger_error): - with mock.patch('six.moves.builtins.open', mock.mock_open()), \ - mock.patch('functest.utils.functest_utils.yaml.safe_load') \ - as mock_yaml: - mock_obj = mock.Mock() - attrs = {'get.return_value': [{'testcases': [self.testcase_dict]}]} - mock_obj.configure_mock(**attrs) - - mock_yaml.return_value = mock_obj - - self.assertDictEqual(functest_utils. - get_dict_by_test(self.testname), - self.testcase_dict) - - @mock.patch('functest.utils.functest_utils.get_dict_by_test') - def test_get_criteria_by_test_default(self, mock_get_dict_by_test): - mock_get_dict_by_test.return_value = self.testcase_dict - self.assertEqual(functest_utils.get_criteria_by_test(self.testname), - self.criteria) - - @mock.patch('functest.utils.functest_utils.get_dict_by_test') - def test_get_criteria_by_test_failed(self, mock_get_dict_by_test): - mock_get_dict_by_test.return_value = None - self.assertIsNone(functest_utils.get_criteria_by_test(self.testname)) - - def test_get_parameter_from_yaml_failed(self): + def test_get_param_from_yaml_failed(self): self.file_yaml['general'] = None with mock.patch('six.moves.builtins.open', mock.mock_open()), \ mock.patch('functest.utils.functest_utils.yaml.safe_load') \ @@ -385,11 +177,11 @@ class FunctestUtilsTesting(unittest.TestCase): mock_yaml.return_value = self.file_yaml functest_utils.get_parameter_from_yaml(self.parameter, self.test_file) - self.assertTrue(("The parameter %s is not" - " defined in config_functest.yaml" % - self.parameter) in excep.exception) + self.assertTrue((f"The parameter {self.parameter} is not" + " defined in config_functest.yaml" + ) in excep.exception) - def test_get_parameter_from_yaml_default(self): + def test_get_param_from_yaml_def(self): with mock.patch('six.moves.builtins.open', mock.mock_open()), \ mock.patch('functest.utils.functest_utils.yaml.safe_load') \ as mock_yaml: @@ -399,28 +191,217 @@ class FunctestUtilsTesting(unittest.TestCase): self.test_file), 'test_image_name') - @mock.patch('functest.utils.functest_utils.get_parameter_from_yaml') - def test_get_functest_config_default(self, mock_get_parameter_from_yaml): - with mock.patch.dict(os.environ, - {'CONFIG_FUNCTEST_YAML': self.config_yaml}): - functest_utils.get_functest_config(self.parameter) - mock_get_parameter_from_yaml. \ - assert_called_once_with(self.parameter, - self.config_yaml) - - def test_get_functest_yaml(self): - with mock.patch('six.moves.builtins.open', mock.mock_open()), \ - mock.patch('functest.utils.functest_utils.yaml.safe_load') \ - as mock_yaml: - mock_yaml.return_value = self.file_yaml - resp = functest_utils.get_functest_yaml() - self.assertEqual(resp, self.file_yaml) - - @mock.patch('functest.utils.functest_utils.logger.info') - def test_print_separator(self, mock_logger_info): - functest_utils.print_separator() - mock_logger_info.assert_called_once_with("=======================" - "=======================") + def test_nova_version_exc1(self): + # pylint: disable=protected-access + cloud = mock.Mock() + cloud._compute_client.request.return_value = None + self.assertEqual(functest_utils.get_nova_version(cloud), None) + cloud._compute_client.request.assert_called_once_with('/', 'GET') + + def test_nova_version_exc2(self): + # pylint: disable=protected-access + cloud = mock.Mock() + cloud._compute_client.request.return_value = {"version": None} + self.assertEqual(functest_utils.get_nova_version(cloud), None) + cloud._compute_client.request.assert_called_once_with('/', 'GET') + + def test_nova_version_exc3(self): + # pylint: disable=protected-access + cloud = mock.Mock() + cloud._compute_client.request.return_value = { + "version": {"version": None}} + self.assertEqual(functest_utils.get_nova_version(cloud), None) + cloud._compute_client.request.assert_called_once_with('/', 'GET') + + def test_nova_version_exc4(self): + # pylint: disable=protected-access + cloud = mock.Mock() + cloud._compute_client.request.return_value = { + "version": {"version": "a.b"}} + self.assertEqual(functest_utils.get_nova_version(cloud), None) + cloud._compute_client.request.assert_called_once_with('/', 'GET') + + def test_nova_version(self): + # pylint: disable=protected-access + cloud = mock.Mock() + cloud._compute_client.request.return_value = { + "version": {"version": "2.1"}} + self.assertEqual(functest_utils.get_nova_version(cloud), (2, 1)) + cloud._compute_client.request.assert_called_once_with('/', 'GET') + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 61)) + def test_openstack_version1(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version( + cloud), "Rocky") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 60)) + def test_openstack_version2(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version(cloud), "Queens") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 43)) + def test_openstack_version3(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version(cloud), "Pike") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 39)) + def test_openstack_version4(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version(cloud), "Ocata") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 26)) + def test_openstack_version5(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version(cloud), "Newton") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 13)) + def test_openstack_version6(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version(cloud), "Mitaka") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 4)) + def test_openstack_version7(self, *args): + cloud = mock.Mock() + self.assertEqual( + functest_utils.get_openstack_version(cloud), "Liberty") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 1)) + def test_openstack_version8(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version(cloud), "Kilo") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(1, 9)) + def test_openstack_version9(self, *args): + cloud = mock.Mock() + self.assertEqual( + functest_utils.get_openstack_version(cloud), "Unknown") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(3, 1)) + def test_openstack_version10(self, *args): + cloud = mock.Mock() + self.assertEqual( + functest_utils.get_openstack_version(cloud), "Master") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 66)) + def test_openstack_version11(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version( + cloud), "Stein") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 78)) + def test_openstack_version12(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version( + cloud), "Train") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 87)) + def test_openstack_version13(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version( + cloud), "Ussuri") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 88)) + def test_openstack_version14(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version( + cloud), "Wallaby") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 89)) + def test_openstack_version15(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version( + cloud), "Xena") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=(2, 92)) + def test_openstack_version16(self, *args): + cloud = mock.Mock() + self.assertEqual(functest_utils.get_openstack_version( + cloud), "Zed") + args[0].assert_called_once_with(cloud) + + @mock.patch('functest.utils.functest_utils.get_nova_version', + return_value=None) + def test_openstack_version_exc(self, *args): + cloud = mock.Mock() + self.assertEqual( + functest_utils.get_openstack_version(cloud), "Unknown") + args[0].assert_called_once_with(cloud) + + def test_convert_dict_to_ini(self): + self.assertEqual( + functest_utils.convert_dict_to_ini({}), "") + self.assertEqual( + functest_utils.convert_dict_to_ini({"a": "b"}), "a:b") + value = functest_utils.convert_dict_to_ini({"a": "b", "c": "d"}) + self.assertTrue(value in ('a:b,c:d', 'c:d,a:b')) + with self.assertRaises(AssertionError): + functest_utils.convert_list_to_ini("") + + def test_convert_list_to_ini(self): + self.assertEqual( + functest_utils.convert_list_to_ini([]), "") + self.assertEqual( + functest_utils.convert_list_to_ini(["a"]), "a") + self.assertEqual( + functest_utils.convert_list_to_ini(["a", "b"]), "a,b") + with self.assertRaises(AssertionError): + functest_utils.convert_list_to_ini("") + + def test_convert_ini_to_dict(self): + self.assertEqual( + functest_utils.convert_ini_to_dict(""), {}) + self.assertEqual( + functest_utils.convert_ini_to_dict("a:b"), {"a": "b"}) + self.assertEqual( + functest_utils.convert_ini_to_dict( + "a:b,c:d"), {"a": "b", "c": "d"}) + self.assertEqual( + functest_utils.convert_ini_to_dict( + "a:b:c,d:e:f"), {"a:b": "c", "d:e": "f"}) + with self.assertRaises(AssertionError): + functest_utils.convert_list_to_ini({}) + + def test_convert_ini_to_list(self): + self.assertEqual( + functest_utils.convert_ini_to_list(""), []) + self.assertEqual( + functest_utils.convert_ini_to_list("a"), ["a"]) + self.assertEqual( + functest_utils.convert_ini_to_list("a,b"), ["a", "b"]) + with self.assertRaises(AssertionError): + functest_utils.convert_ini_to_list([]) if __name__ == "__main__": diff --git a/functest/tests/unit/utils/test_openstack_utils.py b/functest/tests/unit/utils/test_openstack_utils.py deleted file mode 100644 index 01085bb7d..000000000 --- a/functest/tests/unit/utils/test_openstack_utils.py +++ /dev/null @@ -1,1811 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -import copy -import logging -import os -import unittest - -import mock - -from functest.utils import openstack_utils -from functest.utils.constants import CONST - - -class OSUtilsTesting(unittest.TestCase): - - def _get_env_cred_dict(self, os_prefix=''): - return {'OS_USERNAME': os_prefix + 'username', - 'OS_PASSWORD': os_prefix + 'password', - 'OS_AUTH_URL': os_prefix + 'auth_url', - 'OS_TENANT_NAME': os_prefix + 'tenant_name', - 'OS_USER_DOMAIN_NAME': os_prefix + 'user_domain_name', - 'OS_PROJECT_DOMAIN_NAME': os_prefix + 'project_domain_name', - 'OS_PROJECT_NAME': os_prefix + 'project_name', - 'OS_ENDPOINT_TYPE': os_prefix + 'endpoint_type', - 'OS_REGION_NAME': os_prefix + 'region_name', - 'OS_CACERT': os_prefix + 'https_cacert', - 'OS_INSECURE': os_prefix + 'https_insecure'} - - def _get_os_env_vars(self): - return {'username': 'test_username', 'password': 'test_password', - 'auth_url': 'test_auth_url', 'tenant_name': 'test_tenant_name', - 'user_domain_name': 'test_user_domain_name', - 'project_domain_name': 'test_project_domain_name', - 'project_name': 'test_project_name', - 'endpoint_type': 'test_endpoint_type', - 'region_name': 'test_region_name', - 'https_cacert': 'test_https_cacert', - 'https_insecure': 'test_https_insecure'} - - def setUp(self): - self.env_vars = ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD'] - self.tenant_name = 'test_tenant_name' - self.env_cred_dict = self._get_env_cred_dict() - self.os_environs = self._get_env_cred_dict(os_prefix='test_') - self.os_env_vars = self._get_os_env_vars() - - mock_obj = mock.Mock() - attrs = {'name': 'test_flavor', - 'id': 'flavor_id', - 'ram': 2} - mock_obj.configure_mock(**attrs) - self.flavor = mock_obj - - mock_obj = mock.Mock() - attrs = {'name': 'test_aggregate', - 'id': 'aggregate_id', - 'hosts': ['host_name']} - mock_obj.configure_mock(**attrs) - self.aggregate = mock_obj - - mock_obj = mock.Mock() - attrs = {'id': 'instance_id', - 'name': 'test_instance', - 'status': 'ok'} - mock_obj.configure_mock(**attrs) - self.instance = mock_obj - - mock_obj = mock.Mock() - attrs = {'id': 'azone_id', - 'zoneName': 'test_azone', - 'status': 'ok'} - mock_obj.configure_mock(**attrs) - self.availability_zone = mock_obj - - mock_obj = mock.Mock() - attrs = {'floating_network_id': 'floating_id', - 'floating_ip_address': 'test_floating_ip'} - mock_obj.configure_mock(**attrs) - self.floating_ip = mock_obj - - mock_obj = mock.Mock() - attrs = {'id': 'hypervisor_id', - 'hypervisor_hostname': 'test_hostname', - 'state': 'up'} - mock_obj.configure_mock(**attrs) - self.hypervisor = mock_obj - - mock_obj = mock.Mock() - attrs = {'id': 'image_id', - 'name': 'test_image'} - mock_obj.configure_mock(**attrs) - self.image = mock_obj - - mock_obj = mock.Mock() - self.mock_return = mock_obj - - self.nova_client = mock.Mock() - attrs = {'servers.list.return_value': [self.instance], - 'servers.get.return_value': self.instance, - 'servers.find.return_value': self.instance, - 'servers.create.return_value': self.instance, - 'flavors.list.return_value': [self.flavor], - 'flavors.find.return_value': self.flavor, - 'servers.add_floating_ip.return_value': mock.Mock(), - 'servers.force_delete.return_value': mock.Mock(), - 'aggregates.list.return_value': [self.aggregate], - 'aggregates.add_host.return_value': mock.Mock(), - 'aggregates.remove_host.return_value': mock.Mock(), - 'aggregates.get.return_value': self.aggregate, - 'aggregates.delete.return_value': mock.Mock(), - 'availability_zones.list.return_value': - [self.availability_zone], - 'hypervisors.list.return_value': [self.hypervisor], - 'create.return_value': mock.Mock(), - 'add_security_group.return_value': mock.Mock(), - 'images.list.return_value': [self.image], - 'images.delete.return_value': mock.Mock(), - } - self.nova_client.configure_mock(**attrs) - - self.glance_client = mock.Mock() - attrs = {'images.list.return_value': [self.image], - 'images.create.return_value': self.image, - 'images.upload.return_value': mock.Mock()} - self.glance_client.configure_mock(**attrs) - - mock_obj = mock.Mock() - attrs = {'id': 'volume_id', - 'name': 'test_volume'} - mock_obj.configure_mock(**attrs) - self.volume = mock_obj - - self.cinder_client = mock.Mock() - attrs = {'volumes.list.return_value': [self.volume], - 'quotas.update.return_value': mock.Mock(), - 'volumes.detach.return_value': mock.Mock(), - 'volumes.force_delete.return_value': mock.Mock(), - 'volumes.delete.return_value': mock.Mock() - } - self.cinder_client.configure_mock(**attrs) - - self.resource = mock.Mock() - attrs = {'id': 'resource_test_id', - 'name': 'resource_test_name' - } - - self.heat_client = mock.Mock() - attrs = {'resources.get.return_value': self.resource} - self.heat_client.configure_mock(**attrs) - - mock_obj = mock.Mock() - attrs = {'id': 'tenant_id', - 'name': 'test_tenant'} - mock_obj.configure_mock(**attrs) - self.tenant = mock_obj - - mock_obj = mock.Mock() - attrs = {'id': 'user_id', - 'name': 'test_user'} - mock_obj.configure_mock(**attrs) - self.user = mock_obj - - mock_obj = mock.Mock() - attrs = {'id': 'role_id', - 'name': 'test_role'} - mock_obj.configure_mock(**attrs) - self.role = mock_obj - - mock_obj = mock.Mock() - attrs = {'id': 'domain_id', - 'name': 'test_domain'} - mock_obj.configure_mock(**attrs) - self.domain = mock_obj - - self.keystone_client = mock.Mock() - attrs = {'projects.list.return_value': [self.tenant], - 'tenants.list.return_value': [self.tenant], - 'users.list.return_value': [self.user], - 'roles.list.return_value': [self.role], - 'domains.list.return_value': [self.domain], - 'projects.create.return_value': self.tenant, - 'tenants.create.return_value': self.tenant, - 'users.create.return_value': self.user, - 'roles.grant.return_value': mock.Mock(), - 'roles.add_user_role.return_value': mock.Mock(), - 'projects.delete.return_value': mock.Mock(), - 'tenants.delete.return_value': mock.Mock(), - 'users.delete.return_value': mock.Mock(), - } - self.keystone_client.configure_mock(**attrs) - - self.router = {'id': 'router_id', - 'name': 'test_router'} - - self.subnet = {'id': 'subnet_id', - 'name': 'test_subnet'} - - self.networks = [{'id': 'network_id', - 'name': 'test_network', - 'router:external': False, - 'shared': True, - 'subnets': [self.subnet]}, - {'id': 'network_id1', - 'name': 'test_network1', - 'router:external': True, - 'shared': True, - 'subnets': [self.subnet]}] - - self.port = {'id': 'port_id', - 'name': 'test_port'} - - self.sec_group = {'id': 'sec_group_id', - 'name': 'test_sec_group'} - - self.sec_group_rule = {'id': 'sec_group_rule_id', - 'direction': 'direction', - 'protocol': 'protocol', - 'port_range_max': 'port_max', - 'security_group_id': self.sec_group['id'], - 'port_range_min': 'port_min'} - self.neutron_floatingip = {'id': 'fip_id', - 'floating_ip_address': 'test_ip'} - self.neutron_client = mock.Mock() - attrs = {'list_networks.return_value': {'networks': self.networks}, - 'list_routers.return_value': {'routers': [self.router]}, - 'list_ports.return_value': {'ports': [self.port]}, - 'list_subnets.return_value': {'subnets': [self.subnet]}, - 'create_network.return_value': {'network': self.networks[0]}, - 'create_subnet.return_value': {'subnets': [self.subnet]}, - 'create_router.return_value': {'router': self.router}, - 'create_port.return_value': {'port': self.port}, - 'create_floatingip.return_value': {'floatingip': - self.neutron_floatingip}, - 'update_network.return_value': mock.Mock(), - 'update_port.return_value': {'port': self.port}, - 'add_interface_router.return_value': mock.Mock(), - 'add_gateway_router.return_value': mock.Mock(), - 'delete_network.return_value': mock.Mock(), - 'delete_subnet.return_value': mock.Mock(), - 'delete_router.return_value': mock.Mock(), - 'delete_port.return_value': mock.Mock(), - 'remove_interface_router.return_value': mock.Mock(), - 'remove_gateway_router.return_value': mock.Mock(), - 'list_security_groups.return_value': {'security_groups': - [self.sec_group]}, - 'list_security_group_rules.' - 'return_value': {'security_group_rules': - [self.sec_group_rule]}, - 'create_security_group_rule.return_value': mock.Mock(), - 'create_security_group.return_value': {'security_group': - self.sec_group}, - 'update_quota.return_value': mock.Mock(), - 'delete_security_group.return_value': mock.Mock(), - 'list_floatingips.return_value': {'floatingips': - [self.floating_ip]}, - 'delete_floatingip.return_value': mock.Mock(), - } - self.neutron_client.configure_mock(**attrs) - - self.empty_client = mock.Mock() - attrs = {'list_networks.return_value': {'networks': []}, - 'list_routers.return_value': {'routers': []}, - 'list_ports.return_value': {'ports': []}, - 'list_subnets.return_value': {'subnets': []}} - self.empty_client.configure_mock(**attrs) - - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value=None) - def test_is_keystone_v3_missing_identity(self, mock_os_getenv): - self.assertEqual(openstack_utils.is_keystone_v3(), False) - - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value='3') - def test_is_keystone_v3_default(self, mock_os_getenv): - self.assertEqual(openstack_utils.is_keystone_v3(), True) - - @mock.patch('functest.utils.openstack_utils.is_keystone_v3', - return_value=False) - def test_get_rc_env_vars_missing_identity(self, mock_get_rc_env): - exp_resp = self.env_vars - exp_resp.extend(['OS_TENANT_NAME']) - self.assertEqual(openstack_utils.get_rc_env_vars(), exp_resp) - - @mock.patch('functest.utils.openstack_utils.is_keystone_v3', - return_value=True) - def test_get_rc_env_vars_default(self, mock_get_rc_env): - exp_resp = self.env_vars - exp_resp.extend(['OS_PROJECT_NAME', - 'OS_USER_DOMAIN_NAME', - 'OS_PROJECT_DOMAIN_NAME']) - self.assertEqual(openstack_utils.get_rc_env_vars(), exp_resp) - - @mock.patch('functest.utils.openstack_utils.get_rc_env_vars') - def test_check_credentials_missing_env(self, mock_get_rc_env): - exp_resp = self.env_vars - exp_resp.extend(['OS_TENANT_NAME']) - mock_get_rc_env.return_value = exp_resp - with mock.patch.dict('functest.utils.openstack_utils.os.environ', {}, - clear=True): - self.assertEqual(openstack_utils.check_credentials(), False) - - @mock.patch('functest.utils.openstack_utils.get_rc_env_vars') - def test_check_credentials_default(self, mock_get_rc_env): - exp_resp = ['OS_TENANT_NAME'] - mock_get_rc_env.return_value = exp_resp - with mock.patch.dict('functest.utils.openstack_utils.os.environ', - {'OS_TENANT_NAME': self.tenant_name}, - clear=True): - self.assertEqual(openstack_utils.check_credentials(), True) - - def test_get_env_cred_dict(self): - self.assertDictEqual(openstack_utils.get_env_cred_dict(), - self.env_cred_dict) - - @mock.patch('functest.utils.openstack_utils.get_rc_env_vars') - def test_get_credentials_default(self, mock_get_rc_env): - mock_get_rc_env.return_value = self.env_cred_dict.keys() - with mock.patch.dict('functest.utils.openstack_utils.os.environ', - self.os_environs, - clear=True): - self.assertDictEqual(openstack_utils.get_credentials(), - self.os_env_vars) - - def _get_credentials_missing_env(self, var): - dic = copy.deepcopy(self.os_environs) - dic.pop(var) - with mock.patch('functest.utils.openstack_utils.get_rc_env_vars', - return_value=self.env_cred_dict.keys()), \ - mock.patch.dict('functest.utils.openstack_utils.os.environ', - dic, - clear=True): - self.assertRaises(openstack_utils.MissingEnvVar, - lambda: openstack_utils.get_credentials()) - - def test_get_credentials_missing_username(self): - self._get_credentials_missing_env('OS_USERNAME') - - def test_get_credentials_missing_password(self): - self._get_credentials_missing_env('OS_PASSWORD') - - def test_get_credentials_missing_auth_url(self): - self._get_credentials_missing_env('OS_AUTH_URL') - - def test_get_credentials_missing_tenantname(self): - self._get_credentials_missing_env('OS_TENANT_NAME') - - def test_get_credentials_missing_domainname(self): - self._get_credentials_missing_env('OS_USER_DOMAIN_NAME') - - def test_get_credentials_missing_projectname(self): - self._get_credentials_missing_env('OS_PROJECT_NAME') - - def test_get_credentials_missing_endpoint_type(self): - self._get_credentials_missing_env('OS_ENDPOINT_TYPE') - - def _test_source_credentials(self, msg, key='OS_TENANT_NAME', - value='admin'): - try: - del os.environ[key] - except: - pass - f = 'rc_file' - with mock.patch('six.moves.builtins.open', - mock.mock_open(read_data=msg), - create=True) as m: - m.return_value.__iter__ = lambda self: iter(self.readline, '') - openstack_utils.source_credentials(f) - m.assert_called_once_with(f, 'r') - self.assertEqual(os.environ[key], value) - - def test_source_credentials(self): - self._test_source_credentials('OS_TENANT_NAME=admin') - self._test_source_credentials('OS_TENANT_NAME= admin') - self._test_source_credentials('OS_TENANT_NAME = admin') - self._test_source_credentials('OS_TENANT_NAME = "admin"') - self._test_source_credentials('export OS_TENANT_NAME=admin') - self._test_source_credentials('export OS_TENANT_NAME =admin') - self._test_source_credentials('export OS_TENANT_NAME = admin') - self._test_source_credentials('export OS_TENANT_NAME = "admin"') - # This test will fail as soon as rc_file is fixed - self._test_source_credentials( - 'export "\'OS_TENANT_NAME\'" = "\'admin\'"') - - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value=None) - def test_get_keystone_client_version_missing_env(self, mock_os_getenv): - self.assertEqual(openstack_utils.get_keystone_client_version(), - openstack_utils.DEFAULT_API_VERSION) - - @mock.patch('functest.utils.openstack_utils.logger.info') - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value='3') - def test_get_keystone_client_version_default(self, mock_os_getenv, - mock_logger_info): - self.assertEqual(openstack_utils.get_keystone_client_version(), - '3') - mock_logger_info.assert_called_once_with("OS_IDENTITY_API_VERSION is " - "set in env as '%s'", '3') - - @mock.patch('functest.utils.openstack_utils.get_session') - @mock.patch('functest.utils.openstack_utils.keystoneclient.Client') - @mock.patch('functest.utils.openstack_utils.get_keystone_client_version', - return_value='3') - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value='public') - def test_get_keystone_client_with_interface(self, mock_os_getenv, - mock_keystoneclient_version, - mock_key_client, - mock_get_session): - mock_keystone_obj = mock.Mock() - mock_session_obj = mock.Mock() - mock_key_client.return_value = mock_keystone_obj - mock_get_session.return_value = mock_session_obj - self.assertEqual(openstack_utils.get_keystone_client(), - mock_keystone_obj) - mock_key_client.assert_called_once_with('3', - session=mock_session_obj, - interface='public') - - @mock.patch('functest.utils.openstack_utils.get_session') - @mock.patch('functest.utils.openstack_utils.keystoneclient.Client') - @mock.patch('functest.utils.openstack_utils.get_keystone_client_version', - return_value='3') - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value='admin') - def test_get_keystone_client_no_interface(self, mock_os_getenv, - mock_keystoneclient_version, - mock_key_client, - mock_get_session): - mock_keystone_obj = mock.Mock() - mock_session_obj = mock.Mock() - mock_key_client.return_value = mock_keystone_obj - mock_get_session.return_value = mock_session_obj - self.assertEqual(openstack_utils.get_keystone_client(), - mock_keystone_obj) - mock_key_client.assert_called_once_with('3', - session=mock_session_obj, - interface='admin') - - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value=None) - def test_get_nova_client_version_missing_env(self, mock_os_getenv): - self.assertEqual(openstack_utils.get_nova_client_version(), - openstack_utils.DEFAULT_API_VERSION) - - @mock.patch('functest.utils.openstack_utils.logger.info') - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value='3') - def test_get_nova_client_version_default(self, mock_os_getenv, - mock_logger_info): - self.assertEqual(openstack_utils.get_nova_client_version(), - '3') - mock_logger_info.assert_called_once_with("OS_COMPUTE_API_VERSION is " - "set in env as '%s'", '3') - - def test_get_nova_client(self): - mock_nova_obj = mock.Mock() - mock_session_obj = mock.Mock() - with mock.patch('functest.utils.openstack_utils' - '.get_nova_client_version', return_value='3'), \ - mock.patch('functest.utils.openstack_utils' - '.novaclient.Client', - return_value=mock_nova_obj) \ - as mock_nova_client, \ - mock.patch('functest.utils.openstack_utils.get_session', - return_value=mock_session_obj): - self.assertEqual(openstack_utils.get_nova_client(), - mock_nova_obj) - mock_nova_client.assert_called_once_with('3', - session=mock_session_obj) - - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value=None) - def test_get_cinder_client_version_missing_env(self, mock_os_getenv): - self.assertEqual(openstack_utils.get_cinder_client_version(), - openstack_utils.DEFAULT_API_VERSION) - - @mock.patch('functest.utils.openstack_utils.logger.info') - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value='3') - def test_get_cinder_client_version_default(self, mock_os_getenv, - mock_logger_info): - self.assertEqual(openstack_utils.get_cinder_client_version(), - '3') - mock_logger_info.assert_called_once_with("OS_VOLUME_API_VERSION is " - "set in env as '%s'", '3') - - def test_get_cinder_client(self): - mock_cinder_obj = mock.Mock() - mock_session_obj = mock.Mock() - with mock.patch('functest.utils.openstack_utils' - '.get_cinder_client_version', return_value='3'), \ - mock.patch('functest.utils.openstack_utils' - '.cinderclient.Client', - return_value=mock_cinder_obj) \ - as mock_cind_client, \ - mock.patch('functest.utils.openstack_utils.get_session', - return_value=mock_session_obj): - self.assertEqual(openstack_utils.get_cinder_client(), - mock_cinder_obj) - mock_cind_client.assert_called_once_with('3', - session=mock_session_obj) - - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value=None) - def test_get_neutron_client_version_missing_env(self, mock_os_getenv): - self.assertEqual(openstack_utils.get_neutron_client_version(), - openstack_utils.DEFAULT_API_VERSION) - - @mock.patch('functest.utils.openstack_utils.logger.info') - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value='3') - def test_get_neutron_client_version_default(self, mock_os_getenv, - mock_logger_info): - self.assertEqual(openstack_utils.get_neutron_client_version(), - '3') - mock_logger_info.assert_called_once_with("OS_NETWORK_API_VERSION is " - "set in env as '%s'", '3') - - def test_get_neutron_client(self): - mock_neutron_obj = mock.Mock() - mock_session_obj = mock.Mock() - with mock.patch('functest.utils.openstack_utils' - '.get_neutron_client_version', return_value='3'), \ - mock.patch('functest.utils.openstack_utils' - '.neutronclient.Client', - return_value=mock_neutron_obj) \ - as mock_neut_client, \ - mock.patch('functest.utils.openstack_utils.get_session', - return_value=mock_session_obj): - self.assertEqual(openstack_utils.get_neutron_client(), - mock_neutron_obj) - mock_neut_client.assert_called_once_with('3', - session=mock_session_obj) - - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value=None) - def test_get_glance_client_version_missing_env(self, mock_os_getenv): - self.assertEqual(openstack_utils.get_glance_client_version(), - openstack_utils.DEFAULT_API_VERSION) - - @mock.patch('functest.utils.openstack_utils.logger.info') - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value='3') - def test_get_glance_client_version_default(self, mock_os_getenv, - mock_logger_info): - self.assertEqual(openstack_utils.get_glance_client_version(), - '3') - mock_logger_info.assert_called_once_with("OS_IMAGE_API_VERSION is " - "set in env as '%s'", '3') - - def test_get_glance_client(self): - mock_glance_obj = mock.Mock() - mock_session_obj = mock.Mock() - with mock.patch('functest.utils.openstack_utils' - '.get_glance_client_version', return_value='3'), \ - mock.patch('functest.utils.openstack_utils' - '.glanceclient.Client', - return_value=mock_glance_obj) \ - as mock_glan_client, \ - mock.patch('functest.utils.openstack_utils.get_session', - return_value=mock_session_obj): - self.assertEqual(openstack_utils.get_glance_client(), - mock_glance_obj) - mock_glan_client.assert_called_once_with('3', - session=mock_session_obj) - - @mock.patch('functest.utils.openstack_utils.os.getenv', - return_value=None) - def test_get_heat_client_version_missing_env(self, mock_os_getenv): - self.assertEqual(openstack_utils.get_heat_client_version(), - openstack_utils.DEFAULT_HEAT_API_VERSION) - - @mock.patch('functest.utils.openstack_utils.logger.info') - @mock.patch('functest.utils.openstack_utils.os.getenv', return_value='1') - def test_get_heat_client_version_default(self, mock_os_getenv, - mock_logger_info): - self.assertEqual(openstack_utils.get_heat_client_version(), '1') - mock_logger_info.assert_called_once_with( - "OS_ORCHESTRATION_API_VERSION is set in env as '%s'", '1') - - def test_get_heat_client(self): - mock_heat_obj = mock.Mock() - mock_session_obj = mock.Mock() - with mock.patch('functest.utils.openstack_utils' - '.get_heat_client_version', return_value='1'), \ - mock.patch('functest.utils.openstack_utils' - '.heatclient.Client', - return_value=mock_heat_obj) \ - as mock_heat_client, \ - mock.patch('functest.utils.openstack_utils.get_session', - return_value=mock_session_obj): - self.assertEqual(openstack_utils.get_heat_client(), - mock_heat_obj) - mock_heat_client.assert_called_once_with('1', - session=mock_session_obj) - - def test_get_instances_default(self): - self.assertEqual(openstack_utils.get_instances(self.nova_client), - [self.instance]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_instances_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_instances(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_instance_status_default(self): - self.assertEqual(openstack_utils.get_instance_status(self.nova_client, - self.instance), - 'ok') - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_instance_status_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_instance_status(Exception, - self.instance), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_instance_by_name_default(self): - self.assertEqual(openstack_utils. - get_instance_by_name(self.nova_client, - 'test_instance'), - self.instance) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_instance_by_name_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_instance_by_name(Exception, - 'test_instance'), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_flavor_id_default(self): - self.assertEqual(openstack_utils. - get_flavor_id(self.nova_client, - 'test_flavor'), - self.flavor.id) - - def test_get_flavor_id_by_ram_range_default(self): - self.assertEqual(openstack_utils. - get_flavor_id_by_ram_range(self.nova_client, - 1, 3), - self.flavor.id) - - def test_get_aggregates_default(self): - self.assertEqual(openstack_utils. - get_aggregates(self.nova_client), - [self.aggregate]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_aggregates_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_aggregates(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_aggregate_id_default(self): - with mock.patch('functest.utils.openstack_utils.get_aggregates', - return_value=[self.aggregate]): - self.assertEqual(openstack_utils. - get_aggregate_id(self.nova_client, - 'test_aggregate'), - 'aggregate_id') - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_aggregate_id_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_aggregate_id(Exception, - 'test_aggregate'), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_availability_zone_names_default(self): - with mock.patch('functest.utils.openstack_utils' - '.get_availability_zones', - return_value=[self.availability_zone]): - self.assertEqual(openstack_utils. - get_availability_zone_names(self.nova_client), - ['test_azone']) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_availability_zone_names_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_availability_zone_names(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_availability_zones_default(self): - self.assertEqual(openstack_utils. - get_availability_zones(self.nova_client), - [self.availability_zone]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_availability_zones_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_availability_zones(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_floating_ips_default(self): - self.assertEqual(openstack_utils. - get_floating_ips(self.neutron_client), - [self.floating_ip]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_floating_ips_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_floating_ips(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_hypervisors_default(self): - self.assertEqual(openstack_utils. - get_hypervisors(self.nova_client), - ['test_hostname']) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_hypervisors_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_hypervisors(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_create_aggregate_default(self): - self.assertTrue(openstack_utils. - create_aggregate(self.nova_client, - 'test_aggregate', - 'azone')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_aggregate_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - create_aggregate(Exception, - 'test_aggregate', - 'azone'), - None) - self.assertTrue(mock_logger_error.called) - - def test_add_host_to_aggregate_default(self): - with mock.patch('functest.utils.openstack_utils.get_aggregate_id'): - self.assertTrue(openstack_utils. - add_host_to_aggregate(self.nova_client, - 'test_aggregate', - 'test_hostname')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_add_host_to_aggregate_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - add_host_to_aggregate(Exception, - 'test_aggregate', - 'test_hostname'), - None) - self.assertTrue(mock_logger_error.called) - - def test_create_aggregate_with_host_default(self): - with mock.patch('functest.utils.openstack_utils.create_aggregate'), \ - mock.patch('functest.utils.openstack_utils.' - 'add_host_to_aggregate'): - self.assertTrue(openstack_utils. - create_aggregate_with_host(self.nova_client, - 'test_aggregate', - 'test_azone', - 'test_hostname')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_aggregate_with_host_exception(self, mock_logger_error): - with mock.patch('functest.utils.openstack_utils.create_aggregate', - side_effect=Exception): - self.assertEqual(openstack_utils. - create_aggregate_with_host(Exception, - 'test_aggregate', - 'test_azone', - 'test_hostname'), - None) - self.assertTrue(mock_logger_error.called) - - def test_create_instance_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_nova_client', - return_value=self.nova_client): - self.assertEqual(openstack_utils. - create_instance('test_flavor', - 'image_id', - 'network_id'), - self.instance) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_instance_exception(self, mock_logger_error): - with mock.patch('functest.utils.openstack_utils.' - 'get_nova_client', - return_value=self.nova_client): - self.nova_client.flavors.find.side_effect = Exception - self.assertEqual(openstack_utils. - create_instance('test_flavor', - 'image_id', - 'network_id'), - None) - self.assertTrue(mock_logger_error) - - def test_create_floating_ip_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_external_net_id', - return_value='external_net_id'): - exp_resp = {'fip_addr': 'test_ip', 'fip_id': 'fip_id'} - self.assertEqual(openstack_utils. - create_floating_ip(self.neutron_client), - exp_resp) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_floating_ip_exception(self, mock_logger_error): - with mock.patch('functest.utils.openstack_utils.' - 'get_external_net_id', - return_value='external_net_id'): - self.assertEqual(openstack_utils. - create_floating_ip(Exception), - None) - self.assertTrue(mock_logger_error) - - def test_add_floating_ip_default(self): - with mock.patch('functest.utils.openstack_utils.get_aggregate_id'): - self.assertTrue(openstack_utils. - add_floating_ip(self.nova_client, - 'test_serverid', - 'test_floatingip_addr')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_add_floating_ip_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - add_floating_ip(Exception, - 'test_serverid', - 'test_floatingip_addr')) - self.assertTrue(mock_logger_error.called) - - def test_delete_instance_default(self): - self.assertTrue(openstack_utils. - delete_instance(self.nova_client, - 'instance_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_instance_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_instance(Exception, - 'instance_id')) - self.assertTrue(mock_logger_error.called) - - def test_delete_floating_ip_default(self): - self.assertTrue(openstack_utils. - delete_floating_ip(self.neutron_client, - 'floating_ip_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_floating_ip_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_floating_ip(Exception, - 'floating_ip_id')) - self.assertTrue(mock_logger_error.called) - - def test_remove_host_from_aggregate_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_aggregate_id'): - self.assertTrue(openstack_utils. - remove_host_from_aggregate(self.nova_client, - 'agg_name', - 'host_name')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_remove_host_from_aggregate_exception(self, mock_logger_error): - with mock.patch('functest.utils.openstack_utils.' - 'get_aggregate_id', side_effect=Exception): - self.assertFalse(openstack_utils. - remove_host_from_aggregate(self.nova_client, - 'agg_name', - 'host_name')) - self.assertTrue(mock_logger_error.called) - - def test_remove_hosts_from_aggregate_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_aggregate_id'), \ - mock.patch('functest.utils.openstack_utils.' - 'remove_host_from_aggregate', - return_value=True) \ - as mock_method: - openstack_utils.remove_hosts_from_aggregate(self.nova_client, - 'test_aggregate') - mock_method.assert_any_call(self.nova_client, - 'test_aggregate', - 'host_name') - - def test_delete_aggregate_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'remove_hosts_from_aggregate'): - self.assertTrue(openstack_utils. - delete_aggregate(self.nova_client, - 'agg_name')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_aggregate_exception(self, mock_logger_error): - with mock.patch('functest.utils.openstack_utils.' - 'remove_hosts_from_aggregate', side_effect=Exception): - self.assertFalse(openstack_utils. - delete_aggregate(self.nova_client, - 'agg_name')) - self.assertTrue(mock_logger_error.called) - - def test_get_network_list_default(self): - self.assertEqual(openstack_utils. - get_network_list(self.neutron_client), - self.networks) - - def test_get_network_list_missing_network(self): - self.assertEqual(openstack_utils. - get_network_list(self.empty_client), - None) - - def test_get_router_list_default(self): - self.assertEqual(openstack_utils. - get_router_list(self.neutron_client), - [self.router]) - - def test_get_router_list_missing_router(self): - self.assertEqual(openstack_utils. - get_router_list(self.empty_client), - None) - - def test_get_port_list_default(self): - self.assertEqual(openstack_utils. - get_port_list(self.neutron_client), - [self.port]) - - def test_get_port_list_missing_port(self): - self.assertEqual(openstack_utils. - get_port_list(self.empty_client), - None) - - def test_get_network_id_default(self): - self.assertEqual(openstack_utils. - get_network_id(self.neutron_client, - 'test_network'), - 'network_id') - - def test_get_subnet_id_default(self): - self.assertEqual(openstack_utils. - get_subnet_id(self.neutron_client, - 'test_subnet'), - 'subnet_id') - - def test_get_router_id_default(self): - self.assertEqual(openstack_utils. - get_router_id(self.neutron_client, - 'test_router'), - 'router_id') - - def test_get_private_net_default(self): - self.assertEqual(openstack_utils. - get_private_net(self.neutron_client), - self.networks[0]) - - def test_get_private_net_missing_net(self): - self.assertEqual(openstack_utils. - get_private_net(self.empty_client), - None) - - def test_get_external_net_default(self): - self.assertEqual(openstack_utils. - get_external_net(self.neutron_client), - 'test_network1') - - def test_get_external_net_missing_net(self): - self.assertEqual(openstack_utils. - get_external_net(self.empty_client), - None) - - def test_get_external_net_id_default(self): - self.assertEqual(openstack_utils. - get_external_net_id(self.neutron_client), - 'network_id1') - - def test_get_external_net_id_missing_net(self): - self.assertEqual(openstack_utils. - get_external_net_id(self.empty_client), - None) - - def test_check_neutron_net_default(self): - self.assertTrue(openstack_utils. - check_neutron_net(self.neutron_client, - 'test_network')) - - def test_check_neutron_net_missing_net(self): - self.assertFalse(openstack_utils. - check_neutron_net(self.empty_client, - 'test_network')) - - def test_create_neutron_net_default(self): - self.assertEqual(openstack_utils. - create_neutron_net(self.neutron_client, - 'test_network'), - 'network_id') - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_neutron_net_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - create_neutron_net(Exception, - 'test_network'), - None) - self.assertTrue(mock_logger_error.called) - - def test_create_neutron_subnet_default(self): - self.assertEqual(openstack_utils. - create_neutron_subnet(self.neutron_client, - 'test_subnet', - 'test_cidr', - 'network_id'), - 'subnet_id') - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_neutron_subnet_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - create_neutron_subnet(Exception, - 'test_subnet', - 'test_cidr', - 'network_id'), - None) - self.assertTrue(mock_logger_error.called) - - def test_create_neutron_router_default(self): - self.assertEqual(openstack_utils. - create_neutron_router(self.neutron_client, - 'test_router'), - 'router_id') - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_neutron_router_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - create_neutron_router(Exception, - 'test_router'), - None) - self.assertTrue(mock_logger_error.called) - - def test_create_neutron_port_default(self): - self.assertEqual(openstack_utils. - create_neutron_port(self.neutron_client, - 'test_port', - 'network_id', - 'test_ip'), - 'port_id') - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_neutron_port_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - create_neutron_port(Exception, - 'test_port', - 'network_id', - 'test_ip'), - None) - self.assertTrue(mock_logger_error.called) - - def test_update_neutron_net_default(self): - self.assertTrue(openstack_utils. - update_neutron_net(self.neutron_client, - 'network_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_update_neutron_net_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - update_neutron_net(Exception, - 'network_id')) - self.assertTrue(mock_logger_error.called) - - def test_update_neutron_port_default(self): - self.assertEqual(openstack_utils. - update_neutron_port(self.neutron_client, - 'port_id', - 'test_owner'), - 'port_id') - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_update_neutron_port_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - update_neutron_port(Exception, - 'port_id', - 'test_owner'), - None) - self.assertTrue(mock_logger_error.called) - - def test_add_interface_router_default(self): - self.assertTrue(openstack_utils. - add_interface_router(self.neutron_client, - 'router_id', - 'subnet_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_add_interface_router_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - add_interface_router(Exception, - 'router_id', - 'subnet_id')) - self.assertTrue(mock_logger_error.called) - - def test_add_gateway_router_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_external_net_id', - return_value='network_id'): - self.assertTrue(openstack_utils. - add_gateway_router(self.neutron_client, - 'router_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_add_gateway_router_exception(self, mock_logger_error): - with mock.patch('functest.utils.openstack_utils.' - 'get_external_net_id', - return_value='network_id'): - self.assertFalse(openstack_utils. - add_gateway_router(Exception, - 'router_id')) - self.assertTrue(mock_logger_error.called) - - def test_delete_neutron_net_default(self): - self.assertTrue(openstack_utils. - delete_neutron_net(self.neutron_client, - 'network_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_neutron_net_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_neutron_net(Exception, - 'network_id')) - self.assertTrue(mock_logger_error.called) - - def test_delete_neutron_subnet_default(self): - self.assertTrue(openstack_utils. - delete_neutron_subnet(self.neutron_client, - 'subnet_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_neutron_subnet_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_neutron_subnet(Exception, - 'subnet_id')) - self.assertTrue(mock_logger_error.called) - - def test_delete_neutron_router_default(self): - self.assertTrue(openstack_utils. - delete_neutron_router(self.neutron_client, - 'router_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_neutron_router_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_neutron_router(Exception, - 'router_id')) - self.assertTrue(mock_logger_error.called) - - def test_delete_neutron_port_default(self): - self.assertTrue(openstack_utils. - delete_neutron_port(self.neutron_client, - 'port_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_neutron_port_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_neutron_port(Exception, - 'port_id')) - self.assertTrue(mock_logger_error.called) - - def test_remove_interface_router_default(self): - self.assertTrue(openstack_utils. - remove_interface_router(self.neutron_client, - 'router_id', - 'subnet_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_remove_interface_router_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - remove_interface_router(Exception, - 'router_id', - 'subnet_id')) - self.assertTrue(mock_logger_error.called) - - def test_remove_gateway_router_default(self): - self.assertTrue(openstack_utils. - remove_gateway_router(self.neutron_client, - 'router_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_remove_gateway_router_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - remove_gateway_router(Exception, - 'router_id')) - self.assertTrue(mock_logger_error.called) - - def test_get_security_groups_default(self): - self.assertEqual(openstack_utils. - get_security_groups(self.neutron_client), - [self.sec_group]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_security_groups_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_security_groups(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_security_group_id_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_security_groups', - return_value=[self.sec_group]): - self.assertEqual(openstack_utils. - get_security_group_id(self.neutron_client, - 'test_sec_group'), - 'sec_group_id') - - def test_get_security_group_rules_default(self): - self.assertEqual(openstack_utils. - get_security_group_rules(self.neutron_client, - self.sec_group['id']), - [self.sec_group_rule]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_security_group_rules_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_security_group_rules(Exception, - 'sec_group_id'), - None) - self.assertTrue(mock_logger_error.called) - - def test_check_security_group_rules_not_exists(self): - self.assertEqual(openstack_utils. - check_security_group_rules(self.neutron_client, - 'sec_group_id_2', - 'direction', - 'protocol', - 'port_min', - 'port_max'), - True) - - def test_check_security_group_rules_exists(self): - self.assertEqual(openstack_utils. - check_security_group_rules(self.neutron_client, - self.sec_group['id'], - 'direction', - 'protocol', - 'port_min', - 'port_max'), - False) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_check_security_group_rules_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - check_security_group_rules(Exception, - 'sec_group_id', - 'direction', - 'protocol', - 'port_max', - 'port_min'), - None) - self.assertTrue(mock_logger_error.called) - - def test_create_security_group_default(self): - self.assertEqual(openstack_utils. - create_security_group(self.neutron_client, - 'test_sec_group', - 'sec_group_desc'), - self.sec_group) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_security_group_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - create_security_group(Exception, - 'test_sec_group', - 'sec_group_desc'), - None) - self.assertTrue(mock_logger_error.called) - - def test_create_secgroup_rule_default(self): - self.assertTrue(openstack_utils. - create_secgroup_rule(self.neutron_client, - 'sg_id', - 'direction', - 'protocol', - 80, - 80)) - self.assertTrue(openstack_utils. - create_secgroup_rule(self.neutron_client, - 'sg_id', - 'direction', - 'protocol')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_secgroup_rule_invalid_port_range(self, mock_logger_error): - self.assertFalse(openstack_utils. - create_secgroup_rule(self.neutron_client, - 'sg_id', - 'direction', - 'protocol', - 80)) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_secgroup_rule_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - create_secgroup_rule(Exception, - 'sg_id', - 'direction', - 'protocol')) - - @mock.patch('functest.utils.openstack_utils.logger.info') - def test_create_security_group_full_default(self, mock_logger_info): - with mock.patch('functest.utils.openstack_utils.' - 'get_security_group_id', - return_value='sg_id'): - self.assertEqual(openstack_utils. - create_security_group_full(self.neutron_client, - 'sg_name', - 'sg_desc'), - 'sg_id') - self.assertTrue(mock_logger_info) - - @mock.patch('functest.utils.openstack_utils.logger.info') - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_security_group_full_sec_group_fail(self, - mock_logger_error, - mock_logger_info): - with mock.patch('functest.utils.openstack_utils.' - 'get_security_group_id', - return_value=''), \ - mock.patch('functest.utils.openstack_utils.' - 'create_security_group', - return_value=False): - self.assertEqual(openstack_utils. - create_security_group_full(self.neutron_client, - 'sg_name', - 'sg_desc'), - None) - self.assertTrue(mock_logger_error) - self.assertTrue(mock_logger_info) - - @mock.patch('functest.utils.openstack_utils.logger.debug') - @mock.patch('functest.utils.openstack_utils.logger.info') - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_security_group_full_secgroup_rule_fail(self, - mock_logger_error, - mock_logger_info, - mock_logger_debug): - with mock.patch('functest.utils.openstack_utils.' - 'get_security_group_id', - return_value=''), \ - mock.patch('functest.utils.openstack_utils.' - 'create_security_group', - return_value={'id': 'sg_id', - 'name': 'sg_name'}), \ - mock.patch('functest.utils.openstack_utils.' - 'create_secgroup_rule', - return_value=False): - self.assertEqual(openstack_utils. - create_security_group_full(self.neutron_client, - 'sg_name', - 'sg_desc'), - None) - self.assertTrue(mock_logger_error) - self.assertTrue(mock_logger_info) - self.assertTrue(mock_logger_debug) - - def test_add_secgroup_to_instance_default(self): - self.assertTrue(openstack_utils. - add_secgroup_to_instance(self.nova_client, - 'instance_id', - 'sec_group_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_add_secgroup_to_instance_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - add_secgroup_to_instance(Exception, - 'instance_id', - 'sec_group_id')) - self.assertTrue(mock_logger_error.called) - - def test_update_sg_quota_default(self): - self.assertTrue(openstack_utils. - update_sg_quota(self.neutron_client, - 'tenant_id', - 'sg_quota', - 'sg_rule_quota')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_update_sg_quota_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - update_sg_quota(Exception, - 'tenant_id', - 'sg_quota', - 'sg_rule_quota')) - self.assertTrue(mock_logger_error.called) - - def test_delete_security_group_default(self): - self.assertTrue(openstack_utils. - delete_security_group(self.neutron_client, - 'sec_group_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_security_group_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_security_group(Exception, - 'sec_group_id')) - self.assertTrue(mock_logger_error.called) - - def test_get_images_default(self): - self.assertEqual(openstack_utils. - get_images(self.glance_client), - [self.image]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_images_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_images(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_image_id_default(self): - self.assertEqual(openstack_utils. - get_image_id(self.glance_client, - 'test_image'), - 'image_id') - - # create_glance_image, get_or_create_image - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_glance_image_file_present(self, mock_logger_error): - with mock.patch('functest.utils.openstack_utils.' - 'os.path.isfile', - return_value=False): - self.assertEqual(openstack_utils. - create_glance_image(self.glance_client, - 'test_image', - 'file_path'), - None) - self.assertTrue(mock_logger_error.called) - - @mock.patch('functest.utils.openstack_utils.logger.info') - def test_create_glance_image_already_exist(self, mock_logger_info): - with mock.patch('functest.utils.openstack_utils.' - 'os.path.isfile', - return_value=True), \ - mock.patch('functest.utils.openstack_utils.get_image_id', - return_value='image_id'): - self.assertEqual(openstack_utils. - create_glance_image(self.glance_client, - 'test_image', - 'file_path'), - 'image_id') - self.assertTrue(mock_logger_info.called) - - @mock.patch('functest.utils.openstack_utils.logger.info') - def test_create_glance_image_default(self, mock_logger_info): - with mock.patch('functest.utils.openstack_utils.' - 'os.path.isfile', - return_value=True), \ - mock.patch('functest.utils.openstack_utils.get_image_id', - return_value=''), \ - mock.patch('six.moves.builtins.open', - mock.mock_open(read_data='1')) as m: - self.assertEqual(openstack_utils. - create_glance_image(self.glance_client, - 'test_image', - 'file_path'), - 'image_id') - m.assert_called_once_with('file_path') - self.assertTrue(mock_logger_info.called) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_glance_image_exception(self, mock_logger_error): - with mock.patch('functest.utils.openstack_utils.' - 'os.path.isfile', - return_value=True), \ - mock.patch('functest.utils.openstack_utils.get_image_id', - side_effect=Exception): - self.assertEqual(openstack_utils. - create_glance_image(self.glance_client, - 'test_image', - 'file_path'), - None) - self.assertTrue(mock_logger_error.called) - - def test_delete_glance_image_default(self): - self.assertTrue(openstack_utils. - delete_glance_image(self.nova_client, - 'image_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_glance_image_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_glance_image(Exception, - 'image_id')) - self.assertTrue(mock_logger_error.called) - - def test_get_volumes_default(self): - self.assertEqual(openstack_utils. - get_volumes(self.cinder_client), - [self.volume]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_volumes_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_volumes(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_update_cinder_quota_default(self): - self.assertTrue(openstack_utils. - update_cinder_quota(self.cinder_client, - 'tenant_id', - 'vols_quota', - 'snap_quota', - 'giga_quota')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_update_cinder_quota_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - update_cinder_quota(Exception, - 'tenant_id', - 'vols_quota', - 'snap_quota', - 'giga_quota')) - self.assertTrue(mock_logger_error.called) - - def test_delete_volume_default(self): - self.assertTrue(openstack_utils. - delete_volume(self.cinder_client, - 'volume_id', - forced=False)) - - self.assertTrue(openstack_utils. - delete_volume(self.cinder_client, - 'volume_id', - forced=True)) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_volume_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_volume(Exception, - 'volume_id', - forced=True)) - self.assertTrue(mock_logger_error.called) - - def test_get_tenants_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=True): - self.assertEqual(openstack_utils. - get_tenants(self.keystone_client), - [self.tenant]) - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=False): - self.assertEqual(openstack_utils. - get_tenants(self.keystone_client), - [self.tenant]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_tenants_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_tenants(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_users_default(self): - self.assertEqual(openstack_utils. - get_users(self.keystone_client), - [self.user]) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_users_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_users(Exception), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_tenant_id_default(self): - self.assertEqual(openstack_utils. - get_tenant_id(self.keystone_client, - 'test_tenant'), - 'tenant_id') - - def test_get_user_id_default(self): - self.assertEqual(openstack_utils. - get_user_id(self.keystone_client, - 'test_user'), - 'user_id') - - def test_get_role_id_default(self): - self.assertEqual(openstack_utils. - get_role_id(self.keystone_client, - 'test_role'), - 'role_id') - - def test_get_domain_id_default(self): - self.assertEqual(openstack_utils. - get_domain_id(self.keystone_client, - 'test_domain'), - 'domain_id') - - def test_create_tenant_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=True): - CONST.__setattr__('OS_PROJECT_DOMAIN_NAME', 'Default') - self.assertEqual(openstack_utils. - create_tenant(self.keystone_client, - 'test_tenant', - 'tenant_desc'), - 'tenant_id') - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=False): - self.assertEqual(openstack_utils. - create_tenant(self.keystone_client, - 'test_tenant', - 'tenant_desc'), - 'tenant_id') - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_tenant_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - create_tenant(Exception, - 'test_tenant', - 'tenant_desc'), - None) - self.assertTrue(mock_logger_error.called) - - def test_create_user_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=True): - self.assertEqual(openstack_utils. - create_user(self.keystone_client, - 'test_user', - 'password', - 'email', - 'tenant_id'), - 'user_id') - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=False): - self.assertEqual(openstack_utils. - create_user(self.keystone_client, - 'test_user', - 'password', - 'email', - 'tenant_id'), - 'user_id') - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_create_user_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - create_user(Exception, - 'test_user', - 'password', - 'email', - 'tenant_id'), - None) - self.assertTrue(mock_logger_error.called) - - def test_add_role_user_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=True): - self.assertTrue(openstack_utils. - add_role_user(self.keystone_client, - 'user_id', - 'role_id', - 'tenant_id')) - - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=False): - self.assertTrue(openstack_utils. - add_role_user(self.keystone_client, - 'user_id', - 'role_id', - 'tenant_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_add_role_user_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - add_role_user(Exception, - 'user_id', - 'role_id', - 'tenant_id')) - self.assertTrue(mock_logger_error.called) - - def test_delete_tenant_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=True): - self.assertTrue(openstack_utils. - delete_tenant(self.keystone_client, - 'tenant_id')) - - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=False): - self.assertTrue(openstack_utils. - delete_tenant(self.keystone_client, - 'tenant_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_tenant_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_tenant(Exception, - 'tenant_id')) - self.assertTrue(mock_logger_error.called) - - def test_delete_user_default(self): - self.assertTrue(openstack_utils. - delete_user(self.keystone_client, - 'user_id')) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_delete_user_exception(self, mock_logger_error): - self.assertFalse(openstack_utils. - delete_user(Exception, - 'user_id')) - self.assertTrue(mock_logger_error.called) - - def test_get_resource_default(self): - with mock.patch('functest.utils.openstack_utils.' - 'is_keystone_v3', return_value=True): - self.assertEqual(openstack_utils. - get_resource(self.heat_client, - 'stack_id', - 'resource'), - self.resource) - - @mock.patch('functest.utils.openstack_utils.logger.error') - def test_get_resource_exception(self, mock_logger_error): - self.assertEqual(openstack_utils. - get_resource(Exception, - 'stack_id', - 'resource'), - None) - self.assertTrue(mock_logger_error.called) - - def test_get_or_create_user_for_vnf_get(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_user_id', - return_value='user_id'), \ - mock.patch('functest.utils.openstack_utils.get_tenant_id', - return_value='tenant_id'): - self.assertFalse(openstack_utils. - get_or_create_user_for_vnf(self.keystone_client, - 'my_vnf')) - - def test_get_or_create_user_for_vnf_create(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_user_id', - return_value=None), \ - mock.patch('functest.utils.openstack_utils.get_tenant_id', - return_value='tenant_id'): - self.assertTrue(openstack_utils. - get_or_create_user_for_vnf(self.keystone_client, - 'my_vnf')) - - def test_get_or_create_user_for_vnf_error_get_user_id(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_user_id', - side_effect=Exception): - self.assertRaises(Exception) - - def test_get_or_create_user_for_vnf_error_get_tenant_id(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_user_id', - return_value='user_id'), \ - mock.patch('functest.utils.openstack_utils.get_tenant_id', - side_effect='Exception'): - self.assertRaises(Exception) - - def test_get_or_create_tenant_for_vnf_get(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_tenant_id', - return_value='tenant_id'): - self.assertFalse( - openstack_utils.get_or_create_tenant_for_vnf( - self.keystone_client, 'tenant_name', 'tenant_description')) - - def test_get_or_create_tenant_for_vnf_create(self): - with mock.patch('functest.utils.openstack_utils.get_tenant_id', - return_value=None): - self.assertTrue( - openstack_utils.get_or_create_tenant_for_vnf( - self.keystone_client, 'tenant_name', 'tenant_description')) - - def test_get_or_create_tenant_for_vnf_error_get_tenant_id(self): - with mock.patch('functest.utils.openstack_utils.' - 'get_tenant_id', - side_effect=Exception): - self.assertRaises(Exception) - - def test_download_and_add_image_on_glance_image_creation_failure(self): - with mock.patch('functest.utils.openstack_utils.' - 'os.makedirs'), \ - mock.patch('functest.utils.openstack_utils.' - 'ft_utils.download_url', - return_value=True), \ - mock.patch('functest.utils.openstack_utils.' - 'create_glance_image', - return_value=''): - resp = openstack_utils.download_and_add_image_on_glance( - self.glance_client, - 'image_name', - 'http://url', - 'data_dir') - self.assertEqual(resp, False) - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/core/__init__.py b/functest/tests/unit/vnf/epc/__init__.py index e69de29bb..e69de29bb 100644 --- a/functest/tests/unit/core/__init__.py +++ b/functest/tests/unit/vnf/epc/__init__.py diff --git a/functest/tests/unit/vnf/epc/test_juju_epc.py b/functest/tests/unit/vnf/epc/test_juju_epc.py index 2b7453128..a72c61586 100644 --- a/functest/tests/unit/vnf/epc/test_juju_epc.py +++ b/functest/tests/unit/vnf/epc/test_juju_epc.py @@ -18,7 +18,7 @@ from functest.opnfv_tests.vnf.epc import juju_epc class JujuEpcTesting(unittest.TestCase): - + # pylint: disable=missing-docstring """Unittest for ABoT EPC with juju orchestrator""" def setUp(self): @@ -52,15 +52,7 @@ class JujuEpcTesting(unittest.TestCase): return_value={'tenant_images': 'foo', 'orchestrator': self.orchestrator, 'vnf': self.vnf, 'vnf_test_suite': '', - 'version': 'whatever'}), \ - mock.patch('functest.utils.openstack_utils.get_keystone_client', - return_value='test'), \ - mock.patch('functest.utils.openstack_utils.get_glance_client', - return_value='test'), \ - mock.patch('functest.utils.openstack_utils.get_neutron_client', - return_value='test'), \ - mock.patch('functest.utils.openstack_utils.get_nova_client', - return_value='test'): + 'version': 'whatever'}): self.epc_vnf = juju_epc.JujuEpc() self.images = {'image1': 'url1', @@ -69,16 +61,7 @@ class JujuEpcTesting(unittest.TestCase): 'vnf': {}, 'test_vnf': {}} - @mock.patch('functest.utils.openstack_utils.get_keystone_client', - return_value='test') - @mock.patch('functest.utils.openstack_utils.get_or_create_tenant_for_vnf', - return_value=True) - @mock.patch('functest.utils.openstack_utils.get_or_create_user_for_vnf', - return_value=True) - @mock.patch('functest.utils.openstack_utils.get_credentials', - return_value={'auth_url': 'test/v1', - 'project_name': 'test_tenant'}) - @mock.patch('snaps.openstack.create_image.OpenStackImage.create') + @unittest.skip("It must be fixed. Please see JIRA FUNCTEST-915") @mock.patch('os.system') def test_prepare_default(self, *args): """ Unittest for Prepare testcase """ diff --git a/functest/tests/unit/vnf/ims/test_ims_base.py b/functest/tests/unit/vnf/ims/test_clearwater.py index 66d35e39f..f590a2857 100644 --- a/functest/tests/unit/vnf/ims/test_ims_base.py +++ b/functest/tests/unit/vnf/ims/test_clearwater.py @@ -5,20 +5,23 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 +# pylint: disable=missing-docstring + import logging import unittest import mock -from functest.opnfv_tests.vnf.ims import clearwater_ims_base as ims_base +from functest.opnfv_tests.vnf.ims import clearwater -class ClearwaterOnBoardingBaseTesting(unittest.TestCase): +class ClearwaterTesting(unittest.TestCase): def setUp(self): with mock.patch('functest.opnfv_tests.vnf.ims.cloudify_ims.' 'os.makedirs'): - self.ims_vnf = ims_base.ClearwaterOnBoardingBase() + self.ims_vnf = clearwater.ClearwaterTesting( + "foo", "0.0.0.0", "0.0.0.0") self.mock_post = mock.Mock() attrs = {'status_code': 201, @@ -35,6 +38,7 @@ class ClearwaterOnBoardingBaseTesting(unittest.TestCase): 'cookies': ""} self.mock_post_200.configure_mock(**attrs) + if __name__ == "__main__": logging.disable(logging.CRITICAL) unittest.main(verbosity=2) diff --git a/functest/tests/unit/vnf/ims/test_cloudify_ims.py b/functest/tests/unit/vnf/ims/test_cloudify_ims.py index cdd657aac..c84adf0ff 100644 --- a/functest/tests/unit/vnf/ims/test_cloudify_ims.py +++ b/functest/tests/unit/vnf/ims/test_cloudify_ims.py @@ -5,59 +5,14 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 +# pylint: disable=missing-docstring + import logging import unittest -import mock - -from functest.core import vnf -from functest.opnfv_tests.vnf.ims import cloudify_ims - class CloudifyImsTesting(unittest.TestCase): - - def setUp(self): - - self.tenant = 'cloudify_ims' - self.creds = {'username': 'user', - 'password': 'pwd'} - self.orchestrator = {'name': 'cloudify', - 'version': '4.0', - 'object': 'foo', - 'requirements': {'flavor': {'name': 'm1.medium', - 'ram_min': 4096}, - 'os_image': 'manager_4.0'}} - - self.vnf = {'name': 'clearwater', - 'descriptor': {'version': '108', - 'file_name': 'openstack-blueprint.yaml', - 'name': 'clearwater-opnfv', - 'url': 'https://foo', - 'requirements': {'flavor': - {'name': 'm1.medium', - 'ram_min': 2048}}}} - - with mock.patch('functest.opnfv_tests.vnf.ims.cloudify_ims.' - 'os.makedirs'), \ - mock.patch('functest.opnfv_tests.vnf.ims.cloudify_ims.' - 'get_config', return_value={ - 'tenant_images': 'foo', - 'orchestrator': self.orchestrator, - 'vnf': self.vnf, - 'vnf_test_suite': '', - 'version': 'whatever'}): - - self.ims_vnf = cloudify_ims.CloudifyIms() - - self.images = {'image1': 'url1', - 'image2': 'url2'} - self.details = {'orchestrator': {'status': 'PASS', 'duration': 120}, - 'vnf': {}, - 'test_vnf': {}} - - def test_prepare_missing_param(self): - with self.assertRaises(vnf.VnfPreparationException): - self.ims_vnf.prepare() + pass if __name__ == "__main__": diff --git a/functest/tests/unit/vnf/ims/test_orchestra_clearwaterims.py b/functest/tests/unit/vnf/ims/test_orchestra_clearwaterims.py deleted file mode 100644 index 2e83f30a4..000000000 --- a/functest/tests/unit/vnf/ims/test_orchestra_clearwaterims.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -"""Test module for orchestra_clearwaterims""" - -import logging -import unittest - -import mock - -from functest.core import vnf -from functest.opnfv_tests.vnf.ims import orchestra_clearwaterims - - -class OrchestraClearwaterImsTesting(unittest.TestCase): - """Test class for orchestra_clearwaterims""" - def setUp(self): - - self.tenant = 'orchestra_clearwaterims' - self.creds = {'username': 'mocked_username', - 'password': 'mocked_password'} - self.tenant_images = { - 'image1': 'mocked_image_url_1', - 'image2': 'mocked_image_url_2' - } - self.mano = { - 'name': 'openbaton', - 'version': '3.2.0', - 'object': 'foo', - 'requirements': { - 'flavor': { - 'name': 'mocked_flavor', - 'ram_min': 4096, - 'disk': 5, - 'vcpus': 2 - }, - 'os_image': 'mocked_image' - }, - 'bootstrap': { - 'url': 'mocked_bootstrap_url', - 'config': { - 'url': 'mocked_config_url'} - }, - 'gvnfm': { - 'userdata': { - 'url': 'mocked_userdata_url' - } - }, - 'credentials': { - 'username': 'mocked_username', - 'password': 'mocked_password' - } - } - self.vnf = { - 'name': 'openims', - 'descriptor': { - 'url': 'mocked_descriptor_url' - }, - 'requirements': { - 'flavor': { - 'name': 'mocked_flavor', - 'ram_min': 2048, - 'disk': 5, - 'vcpus': 2} - } - } - self.clearwaterims = { - 'scscf': { - 'ports': [3870, 6060] - }, - 'pcscf': { - 'ports': [4060] - }, - 'icscf': { - 'ports': [3869, 5060] - }, - 'fhoss': { - 'ports': [3868] - }, - 'bind9': { - 'ports': [] - } - } - with mock.patch('functest.opnfv_tests.vnf.ims.orchestra_clearwaterims.' - 'os.makedirs'),\ - mock.patch('functest.opnfv_tests.vnf.ims.orchestra_clearwaterims.' - 'get_config', return_value={ - 'orchestrator': self.mano, - 'name': self.mano['name'], - 'version': self.mano['version'], - 'requirements': self.mano['requirements'], - 'credentials': self.mano['credentials'], - 'bootstrap': self.mano['bootstrap'], - 'gvnfm': self.mano['gvnfm'], - 'os_image': self.mano['requirements']['os_image'], - 'flavor': self.mano['requirements']['flavor'], - 'url': self.mano['bootstrap']['url'], - 'config': self.mano['bootstrap']['config'], - 'tenant_images': self.tenant_images, - 'vnf': self.vnf, - 'orchestra_clearwaterims': self.clearwaterims}): - self.ims_vnf = orchestra_clearwaterims.ClearwaterImsVnf() - - self.details = {'orchestrator': {'status': 'PASS', 'duration': 120}, - 'vnf': {}, - 'test_vnf': {}} - - def test_prepare_missing_param(self): - """Testing prepare function with missing param""" - with self.assertRaises(vnf.VnfPreparationException): - self.ims_vnf.prepare() - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/vnf/ims/test_orchestra_openims.py b/functest/tests/unit/vnf/ims/test_orchestra_openims.py deleted file mode 100644 index 47a8d0338..000000000 --- a/functest/tests/unit/vnf/ims/test_orchestra_openims.py +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -"""Test module for orchestra_openims""" - -import logging -import unittest - -import mock - -from functest.core import vnf -from functest.opnfv_tests.vnf.ims import orchestra_openims - - -class OrchestraOpenImsTesting(unittest.TestCase): - """Test class for orchestra_openims""" - def setUp(self): - - self.tenant = 'orchestra_openims' - self.creds = {'username': 'mocked_username', - 'password': 'mocked_password'} - self.tenant_images = { - 'image1': 'mocked_image_url_1', - 'image2': 'mocked_image_url_2' - } - self.mano = { - 'name': 'openbaton', - 'version': '3.2.0', - 'object': 'foo', - 'requirements': { - 'flavor': { - 'name': 'mocked_flavor', - 'ram_min': 4096, - 'disk': 5, - 'vcpus': 2 - }, - 'os_image': 'mocked_image' - }, - 'bootstrap': { - 'url': 'mocked_bootstrap_url', - 'config': { - 'url': 'mocked_config_url'} - }, - 'gvnfm': { - 'userdata': { - 'url': 'mocked_userdata_url' - } - }, - 'credentials': { - 'username': 'mocked_username', - 'password': 'mocked_password' - } - } - self.vnf = { - 'name': 'openims', - 'descriptor': { - 'url': 'mocked_descriptor_url' - }, - 'requirements': { - 'flavor': { - 'name': 'mocked_flavor', - 'ram_min': 2048, - 'disk': 5, - 'vcpus': 2} - } - } - self.openims = { - 'scscf': { - 'ports': [3870, 6060] - }, - 'pcscf': { - 'ports': [4060] - }, - 'icscf': { - 'ports': [3869, 5060] - }, - 'fhoss': { - 'ports': [3868] - }, - 'bind9': { - 'ports': [] - } - } - with mock.patch('functest.opnfv_tests.vnf.ims.orchestra_openims.' - 'os.makedirs'),\ - mock.patch('functest.opnfv_tests.vnf.ims.orchestra_openims.' - 'get_config', return_value={ - 'orchestrator': self.mano, - 'name': self.mano['name'], - 'version': self.mano['version'], - 'requirements': self.mano['requirements'], - 'credentials': self.mano['credentials'], - 'bootstrap': self.mano['bootstrap'], - 'gvnfm': self.mano['gvnfm'], - 'os_image': - self.mano['requirements']['os_image'], - 'flavor': - self.mano['requirements']['flavor'], - 'url': self.mano['bootstrap']['url'], - 'config': self.mano['bootstrap']['config'], - 'tenant_images': self.tenant_images, - 'vnf': self.vnf, - 'orchestra_openims': self.openims}): - self.ims_vnf = orchestra_openims.OpenImsVnf() - - self.details = {'orchestrator': {'status': 'PASS', 'duration': 120}, - 'vnf': {}, - 'test_vnf': {}} - - def test_prepare_missing_param(self): - """Testing prepare function with missing param""" - with self.assertRaises(vnf.VnfPreparationException): - self.ims_vnf.prepare() - - -if __name__ == "__main__": - logging.disable(logging.CRITICAL) - unittest.main(verbosity=2) diff --git a/functest/tests/unit/vnf/router/test_cloudify_vrouter.py b/functest/tests/unit/vnf/router/test_cloudify_vrouter.py index 4d8e9405b..b3f83e946 100644 --- a/functest/tests/unit/vnf/router/test_cloudify_vrouter.py +++ b/functest/tests/unit/vnf/router/test_cloudify_vrouter.py @@ -7,62 +7,15 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 +# pylint: disable=missing-docstring + import logging import unittest -import mock - -from functest.core import vnf -from functest.opnfv_tests.vnf.router import cloudify_vrouter - class CloudifyVrouterTesting(unittest.TestCase): - @mock.patch('functest.opnfv_tests.vnf.router.cloudify_vrouter.Utilvnf') - @mock.patch('functest.opnfv_tests.vnf.router.cloudify_vrouter.vrouter_base' - '.Utilvnf') - @mock.patch('os.makedirs') - def setUp(self, *args): - - self.tenant = 'cloudify_vrouter' - self.creds = {'username': 'user', - 'password': 'pwd'} - self.orchestrator = {'name': 'cloudify', - 'version': '4.0', - 'object': 'foo', - 'requirements': {'flavor': {'name': 'm1.medium', - 'ram_min': 4096}, - 'os_image': 'manager_4.0'}} - - self.vnf = {'name': 'vrouter', - 'descriptor': {'version': '100', - 'file_name': 'function-test-' + - 'openstack-blueprint.yaml', - 'name': 'vrouter-opnfv', - 'url': 'https://foo', - 'requirements': {'flavor': - {'name': 'm1.medium', - 'ram_min': 2048}}}} - - with mock.patch('functest.opnfv_tests.vnf.router.cloudify_vrouter.' - 'get_config', return_value={ - 'tenant_images': 'foo', - 'orchestrator': self.orchestrator, - 'vnf': self.vnf, - 'vnf_test_suite': '', - 'version': 'whatever'}): - - self.router_vnf = cloudify_vrouter.CloudifyVrouter() - - self.images = {'image1': 'url1', - 'image2': 'url2'} - self.details = {'orchestrator': {'status': 'PASS', 'duration': 120}, - 'vnf': {}, - 'test_vnf': {}} - - def test_prepare_missing_param(self): - with self.assertRaises(vnf.VnfPreparationException): - self.router_vnf.prepare() + pass if __name__ == "__main__": diff --git a/functest/tests/unit/vnf/router/test_vrouter_base.py b/functest/tests/unit/vnf/router/test_vrouter_base.py index def201d16..330093658 100644 --- a/functest/tests/unit/vnf/router/test_vrouter_base.py +++ b/functest/tests/unit/vnf/router/test_vrouter_base.py @@ -7,20 +7,14 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 +# pylint: disable=missing-docstring + import logging import unittest -import mock - -from functest.opnfv_tests.vnf.router import vrouter_base - class VrouterOnBoardingBaseTesting(unittest.TestCase): - - def setUp(self): - with mock.patch('functest.opnfv_tests.vnf.router.cloudify_vrouter.' - 'os.makedirs'): - self.vrouter_vnf = vrouter_base.VrouterOnBoardingBase() + pass if __name__ == "__main__": |