diff options
Diffstat (limited to 'functest/tests/unit')
-rw-r--r-- | functest/tests/unit/odl/test_odl.py | 51 | ||||
-rw-r--r-- | functest/tests/unit/openstack/cinder/test_cinder.py | 11 | ||||
-rw-r--r-- | functest/tests/unit/openstack/rally/test_rally.py | 78 | ||||
-rw-r--r-- | functest/tests/unit/openstack/tempest/test_tempest.py | 51 | ||||
-rw-r--r-- | functest/tests/unit/openstack/vmtp/test_vmtp.py | 11 | ||||
-rw-r--r-- | functest/tests/unit/openstack/vping/test_vping_ssh.py | 32 | ||||
-rw-r--r-- | functest/tests/unit/utils/test_functest_utils.py | 173 | ||||
-rw-r--r-- | functest/tests/unit/vnf/ims/test_clearwater.py | 4 |
8 files changed, 232 insertions, 179 deletions
diff --git a/functest/tests/unit/odl/test_odl.py b/functest/tests/unit/odl/test_odl.py index 1b2e10b07..c675c2988 100644 --- a/functest/tests/unit/odl/test_odl.py +++ b/functest/tests/unit/odl/test_odl.py @@ -33,10 +33,10 @@ class ODLTesting(unittest.TestCase): logging.disable(logging.CRITICAL) _keystone_ip = "127.0.0.1" - _neutron_url = u"https://127.0.0.1:9696" - _neutron_id = u"dummy" + _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" @@ -63,8 +63,7 @@ class ODLTesting(unittest.TestCase): 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, @@ -105,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( @@ -160,19 +159,19 @@ class ODLMainTesting(ODLTesting): 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, include=[], @@ -541,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) @@ -551,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) @@ -565,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): @@ -606,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): @@ -614,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/openstack/cinder/test_cinder.py b/functest/tests/unit/openstack/cinder/test_cinder.py index 4052408d9..d3c9cabb6 100644 --- a/functest/tests/unit/openstack/cinder/test_cinder.py +++ b/functest/tests/unit/openstack/cinder/test_cinder.py @@ -59,7 +59,7 @@ class CinderTesting(unittest.TestCase): self.cinder.prepare() args[0].assert_called_with() args[1].assert_called_once_with( - '{}-vm2_{}'.format(self.cinder.case_name, self.cinder.guid), + 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() @@ -81,13 +81,12 @@ class CinderTesting(unittest.TestCase): self.cinder.prepare() args[0].assert_called_once_with() args[1].assert_called_once_with( - '{}-vm2_{}'.format(self.cinder.case_name, self.cinder.guid), + 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='{}-volume_{}'.format( - self.cinder.case_name, self.cinder.guid), + name=f'{self.cinder.case_name}-volume_{self.cinder.guid}', size='2', timeout=self.cinder.volume_timeout, wait=True) @mock.patch('scp.SCPClient.put') @@ -101,7 +100,7 @@ class CinderTesting(unittest.TestCase): 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( - "sh ~/write_data.sh {}".format(env.get('VOLUME_DEVICE_NAME'))) + 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) @@ -138,7 +137,7 @@ class CinderTesting(unittest.TestCase): stdout.channel.recv_exit_status.return_value = 0 self.assertEqual(self.cinder._read_data(), 0) self.cinder.ssh2.exec_command.assert_called_once_with( - "sh ~/read_data.sh {}".format(env.get('VOLUME_DEVICE_NAME'))) + 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) diff --git a/functest/tests/unit/openstack/rally/test_rally.py b/functest/tests/unit/openstack/rally/test_rally.py index 5dc38a20f..f3c2e7cf6 100644 --- a/functest/tests/unit/openstack/rally/test_rally.py +++ b/functest/tests/unit/openstack/rally/test_rally.py @@ -50,7 +50,7 @@ class OSRallyTesting(unittest.TestCase): @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 @@ -64,7 +64,7 @@ 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 @@ -78,10 +78,13 @@ class OSRallyTesting(unittest.TestCase): 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(['rally', 'deployment', 'check'])] + 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') @@ -92,23 +95,27 @@ class OSRallyTesting(unittest.TestCase): 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({}) @@ -277,7 +284,7 @@ class OSRallyTesting(unittest.TestCase): mock_summary.assert_called() def test_prepare_run_testname_invalid(self): - self.rally_base.TESTS = ['test1', 'test2'] + self.rally_base.stests = ['test1', 'test2'] with self.assertRaises(Exception): self.rally_base.prepare_run(tests=['test']) @@ -287,9 +294,9 @@ class OSRallyTesting(unittest.TestCase): @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.TESTS = ['test1', 'test2'] - with mock.patch.object(self.rally_base.cloud, - 'list_hypervisors') as mock_list_hyperv, \ + 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: @@ -322,14 +329,19 @@ class OSRallyTesting(unittest.TestCase): mock_run_task.assert_any_call('test1') mock_run_task.assert_any_call('test2') - def test_clean_up_default(self): + @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.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_run') @@ -345,12 +357,17 @@ class OSRallyTesting(unittest.TestCase): func.assert_called() @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.' + 'update_rally_logs') + @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'create_rally_deployment', return_value=mock.Mock()) @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.' 'prepare_run', side_effect=Exception) @@ -358,6 +375,7 @@ class OSRallyTesting(unittest.TestCase): # 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 = { @@ -405,8 +423,8 @@ class OSRallyTesting(unittest.TestCase): @mock.patch('subprocess.check_output', side_effect=subprocess.CalledProcessError('', '')) def test_export_task_ko(self, *args): - file_name = "{}/{}.html".format( - self.rally_base.results_dir, self.rally_base.case_name) + 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", @@ -414,10 +432,10 @@ class OSRallyTesting(unittest.TestCase): "--to", file_name] args[0].assert_called_with(cmd, stderr=subprocess.STDOUT) - @mock.patch('subprocess.check_output', return_value=None) + @mock.patch('subprocess.check_output', return_value=b'') def test_export_task(self, *args): - file_name = "{}/{}.html".format( - self.rally_base.results_dir, self.rally_base.case_name) + 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')), @@ -427,18 +445,18 @@ class OSRallyTesting(unittest.TestCase): @mock.patch('subprocess.check_output', side_effect=subprocess.CalledProcessError('', '')) def test_verify_report_ko(self, *args): - file_name = "{}/{}.html".format( - self.rally_base.results_dir, self.rally_base.case_name) + 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=None) + @mock.patch('subprocess.check_output', return_value=b'') def test_verify_report(self, *args): - file_name = "{}/{}.html".format( - self.rally_base.results_dir, self.rally_base.case_name) + 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] diff --git a/functest/tests/unit/openstack/tempest/test_tempest.py b/functest/tests/unit/openstack/tempest/test_tempest.py index 119959670..efc4393c8 100644 --- a/functest/tests/unit/openstack/tempest/test_tempest.py +++ b/functest/tests/unit/openstack/tempest/test_tempest.py @@ -57,7 +57,7 @@ class OSTempestTesting(unittest.TestCase): msg = "Tempest test list file %s NOT found." self.tempestcommon.generate_test_list() self.assertTrue( - (msg % self.tempestcommon.TEMPEST_CUSTOM) in context.exception) + (msg % self.tempestcommon.tempest_custom) in context.exception) @mock.patch('subprocess.check_output') @mock.patch('os.remove') @@ -83,8 +83,8 @@ class OSTempestTesting(unittest.TestCase): testr_mode = self.tempestcommon.mode verifier_repo_dir = 'test_verifier_repo_dir' self.tempestcommon.verifier_repo_dir = verifier_repo_dir - cmd = "(cd {0}; stestr list '{1}' >{2} 2>/dev/null)".format( - verifier_repo_dir, testr_mode, self.tempestcommon.list) + 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') @@ -123,9 +123,10 @@ class OSTempestTesting(unittest.TestCase): mock.mock_open()) as mock_open, \ mock.patch.object(self.tempestcommon, 'read_file', return_value=['test1', 'test2']): - self.tempestcommon.TEMPEST_BLACKLIST = Exception + self.tempestcommon.tempest_blacklist = Exception os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario' - self.tempestcommon.apply_tempest_blacklist() + 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') @@ -147,7 +148,8 @@ class OSTempestTesting(unittest.TestCase): mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' 'yaml.safe_load', return_value=item_dict): os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario' - self.tempestcommon.apply_tempest_blacklist() + 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')) @@ -156,20 +158,17 @@ class OSTempestTesting(unittest.TestCase): args[2].assert_called_once_with( self.tempestcommon.list, self.tempestcommon.raw_list) + @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, mock_logger_info): - with mock.patch('six.moves.builtins.open', mock.mock_open()), \ - mock.patch('six.moves.builtins.iter', - return_value=[r'\} tempest\.']), \ - mock.patch('functest.opnfv_tests.openstack.tempest.tempest.' - 'subprocess.Popen'): - 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) + 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() + 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) @@ -270,10 +269,9 @@ class OSTempestTesting(unittest.TestCase): with mock.patch('functest.opnfv_tests.openstack.tempest.' 'tempest.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 + 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') @@ -282,10 +280,9 @@ class OSTempestTesting(unittest.TestCase): setattr(config.CONF, 'tempest_verifier_name', 'test_deploy_name') with mock.patch('functest.opnfv_tests.openstack.tempest.' 'tempest.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 + 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') diff --git a/functest/tests/unit/openstack/vmtp/test_vmtp.py b/functest/tests/unit/openstack/vmtp/test_vmtp.py index fcbb0c46b..850273476 100644 --- a/functest/tests/unit/openstack/vmtp/test_vmtp.py +++ b/functest/tests/unit/openstack/vmtp/test_vmtp.py @@ -66,21 +66,22 @@ class VmtpTesting(unittest.TestCase): def test_generate_keys1(self, *args): self.testcase.generate_keys() self.testcase.cloud.create_keypair.assert_called_once_with( - 'vmtp_{}'.format(self.testcase.guid)) + f'vmtp_{self.testcase.guid}') self.testcase.cloud.delete_keypair.assert_called_once_with('id') - calls = [mock.call(self.testcase.privkey_filename, 'w'), - mock.call(self.testcase.pubkey_filename, 'w')] + 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): - # pylint: disable=bad-continuation 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('vmtp_{}'.format(self.testcase.guid)) + mock_obj.assert_called_once_with(f'vmtp_{self.testcase.guid}') args[0].assert_not_called() diff --git a/functest/tests/unit/openstack/vping/test_vping_ssh.py b/functest/tests/unit/openstack/vping/test_vping_ssh.py index 05482ed6b..a07148aab 100644 --- a/functest/tests/unit/openstack/vping/test_vping_ssh.py +++ b/functest/tests/unit/openstack/vping/test_vping_ssh.py @@ -47,7 +47,7 @@ class VpingSSHTesting(unittest.TestCase): self.vping.prepare() args[0].assert_called_once_with() args[1].assert_called_once_with( - '{}-vm2_{}'.format(self.vping.case_name, self.vping.guid), + 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.' @@ -58,27 +58,43 @@ class VpingSSHTesting(unittest.TestCase): self.vping.prepare() args[0].assert_called_once_with() args[1].assert_called_once_with( - '{}-vm2_{}'.format(self.vping.case_name, self.vping.guid), + f'{self.vping.case_name}-vm2_{self.vping.guid}', security_groups=[self.vping.sec.id]) - def test_execute_exc(self): - self.vping.vm2 = munch.Munch(private_v4='127.0.0.1') + @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( - 'ping -c 1 {}'.format(self.vping.vm2.private_v4)) + 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') + 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()) - self.assertEqual(self.vping.execute(), ret) + 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( - 'ping -c 1 {}'.format(self.vping.vm2.private_v4)) + f'ping -c 1 {self.vping.vm2.private_v4}') def test_execute1(self): self._test_execute() diff --git a/functest/tests/unit/utils/test_functest_utils.py b/functest/tests/unit/utils/test_functest_utils.py index dcbbd79e5..4b642ff9d 100644 --- a/functest/tests/unit/utils/test_functest_utils.py +++ b/functest/tests/unit/utils/test_functest_utils.py @@ -15,6 +15,7 @@ import unittest import mock import pkg_resources +import six from functest.utils import functest_utils @@ -81,7 +82,7 @@ class FunctestUtilsTesting(unittest.TestCase): 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 @@ -97,27 +98,20 @@ class FunctestUtilsTesting(unittest.TestCase): 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') @@ -126,50 +120,35 @@ class FunctestUtilsTesting(unittest.TestCase): 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_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') @@ -177,22 +156,16 @@ class FunctestUtilsTesting(unittest.TestCase): # 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 test_get_param_from_yaml_failed(self): @@ -204,9 +177,9 @@ 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_param_from_yaml_def(self): with mock.patch('six.moves.builtins.open', mock.mock_open()), \ @@ -331,6 +304,54 @@ class FunctestUtilsTesting(unittest.TestCase): 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() @@ -344,7 +365,7 @@ class FunctestUtilsTesting(unittest.TestCase): 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 == "a:b,c:d" or value == "c:d,a:b") + self.assertTrue(value in ('a:b,c:d', 'c:d,a:b')) with self.assertRaises(AssertionError): functest_utils.convert_list_to_ini("") diff --git a/functest/tests/unit/vnf/ims/test_clearwater.py b/functest/tests/unit/vnf/ims/test_clearwater.py index 93f8ffe4a..f590a2857 100644 --- a/functest/tests/unit/vnf/ims/test_clearwater.py +++ b/functest/tests/unit/vnf/ims/test_clearwater.py @@ -20,7 +20,8 @@ class ClearwaterTesting(unittest.TestCase): def setUp(self): with mock.patch('functest.opnfv_tests.vnf.ims.cloudify_ims.' 'os.makedirs'): - self.ims_vnf = clearwater.ClearwaterTesting("foo", "0.0.0.0") + self.ims_vnf = clearwater.ClearwaterTesting( + "foo", "0.0.0.0", "0.0.0.0") self.mock_post = mock.Mock() attrs = {'status_code': 201, @@ -37,6 +38,7 @@ class ClearwaterTesting(unittest.TestCase): 'cookies': ""} self.mock_post_200.configure_mock(**attrs) + if __name__ == "__main__": logging.disable(logging.CRITICAL) unittest.main(verbosity=2) |