aboutsummaryrefslogtreecommitdiffstats
path: root/functest/opnfv_tests
diff options
context:
space:
mode:
Diffstat (limited to 'functest/opnfv_tests')
-rw-r--r--functest/opnfv_tests/openstack/api/connection_check.py7
-rw-r--r--functest/opnfv_tests/openstack/barbican/barbican.py8
-rw-r--r--functest/opnfv_tests/openstack/cinder/cinder_test.py14
-rw-r--r--functest/opnfv_tests/openstack/cinder/write_data.sh2
-rw-r--r--functest/opnfv_tests/openstack/patrole/patrole.py8
-rw-r--r--functest/opnfv_tests/openstack/rally/blacklist.yaml8
-rw-r--r--functest/opnfv_tests/openstack/rally/rally.py137
-rw-r--r--functest/opnfv_tests/openstack/rally/scenario/full/opnfv-cinder.yaml27
-rw-r--r--functest/opnfv_tests/openstack/rally/scenario/full/opnfv-nova.yaml30
-rw-r--r--functest/opnfv_tests/openstack/rally/scenario/sanity/opnfv-nova.yaml15
-rw-r--r--functest/opnfv_tests/openstack/rally/scenario/templates/server_with_ports.yaml.template2
-rw-r--r--functest/opnfv_tests/openstack/refstack/refstack.py18
-rw-r--r--functest/opnfv_tests/openstack/shaker/shaker.py42
-rw-r--r--functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml12
-rw-r--r--functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf_ovn.yaml10
-rw-r--r--functest/opnfv_tests/openstack/tempest/tempest.py314
-rw-r--r--functest/opnfv_tests/openstack/vmtp/vmtp.py44
-rw-r--r--functest/opnfv_tests/openstack/vping/vping_ssh.py15
-rw-r--r--functest/opnfv_tests/openstack/vping/vping_userdata.py18
-rw-r--r--functest/opnfv_tests/sdn/odl/odl.py17
-rw-r--r--functest/opnfv_tests/vnf/epc/juju_epc.py70
-rw-r--r--functest/opnfv_tests/vnf/ims/clearwater.py29
-rw-r--r--functest/opnfv_tests/vnf/ims/cloudify_ims.py12
-rw-r--r--functest/opnfv_tests/vnf/ims/heat_ims.py17
-rw-r--r--functest/opnfv_tests/vnf/router/cloudify_vrouter.py12
-rw-r--r--functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py15
-rw-r--r--functest/opnfv_tests/vnf/router/utilvnf.py39
-rw-r--r--functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py2
-rw-r--r--functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py8
-rw-r--r--functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py22
30 files changed, 475 insertions, 499 deletions
diff --git a/functest/opnfv_tests/openstack/api/connection_check.py b/functest/opnfv_tests/openstack/api/connection_check.py
index adca30ee9..eaf9767c0 100644
--- a/functest/opnfv_tests/openstack/api/connection_check.py
+++ b/functest/opnfv_tests/openstack/api/connection_check.py
@@ -16,6 +16,7 @@ import os_client_config
import shade
from xtesting.core import testcase
+from functest.utils import env
from functest.utils import functest_utils
@@ -33,7 +34,7 @@ class ConnectionCheck(testcase.TestCase):
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = 'connection_check'
- super(ConnectionCheck, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.output_log_name = 'functest.log'
self.output_debug_log_name = 'functest.debug.log'
try:
@@ -51,6 +52,10 @@ class ConnectionCheck(testcase.TestCase):
self.start_time = time.time()
self.__logger.debug(
"list_services: %s", functest_utils.list_services(self.cloud))
+ if env.get('NO_TENANT_NETWORK').lower() == 'true':
+ self.func_list.remove("list_floating_ip_pools")
+ self.func_list.remove("list_floating_ips")
+ self.func_list.remove("list_routers")
for func in self.func_list:
self.__logger.debug(
"%s: %s", func, getattr(self.cloud, func)())
diff --git a/functest/opnfv_tests/openstack/barbican/barbican.py b/functest/opnfv_tests/openstack/barbican/barbican.py
index 7b1bb24f7..706304bbf 100644
--- a/functest/opnfv_tests/openstack/barbican/barbican.py
+++ b/functest/opnfv_tests/openstack/barbican/barbican.py
@@ -9,8 +9,6 @@
# pylint: disable=missing-docstring
-import logging
-
from six.moves import configparser
from functest.opnfv_tests.openstack.tempest import tempest
@@ -18,10 +16,8 @@ from functest.opnfv_tests.openstack.tempest import tempest
class Barbican(tempest.TempestCommon):
- __logger = logging.getLogger(__name__)
-
def configure(self, **kwargs):
- super(Barbican, self).configure(**kwargs)
+ super().configure(**kwargs)
rconfig = configparser.RawConfigParser()
rconfig.read(self.conf_file)
if not rconfig.has_section('auth'):
@@ -36,6 +32,6 @@ class Barbican(tempest.TempestCommon):
if not rconfig.has_section('image-feature-enabled'):
rconfig.add_section('image-feature-enabled')
rconfig.set('image-feature-enabled', 'api_v1', False)
- with open(self.conf_file, 'w') as config_file:
+ with open(self.conf_file, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
self.backup_tempest_config(self.conf_file, self.res_dir)
diff --git a/functest/opnfv_tests/openstack/cinder/cinder_test.py b/functest/opnfv_tests/openstack/cinder/cinder_test.py
index d81bb100a..7d8c0a0bd 100644
--- a/functest/opnfv_tests/openstack/cinder/cinder_test.py
+++ b/functest/opnfv_tests/openstack/cinder/cinder_test.py
@@ -35,7 +35,7 @@ class CinderCheck(singlevm.SingleVm2):
"""Initialize testcase."""
if "case_name" not in kwargs:
kwargs["case_name"] = "cinder_test"
- super(CinderCheck, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.logger = logging.getLogger(__name__)
self.vm2 = None
self.fip2 = None
@@ -52,14 +52,14 @@ class CinderCheck(singlevm.SingleVm2):
return self._write_data() or self._read_data()
def prepare(self):
- super(CinderCheck, self).prepare()
+ super().prepare()
self.vm2 = self.boot_vm(
- '{}-vm2_{}'.format(self.case_name, self.guid),
+ f'{self.case_name}-vm2_{self.guid}',
key_name=self.keypair.id,
security_groups=[self.sec.id])
(self.fip2, self.ssh2) = self.connect(self.vm2)
self.volume = self.cloud.create_volume(
- name='{}-volume_{}'.format(self.case_name, self.guid), size='2',
+ name=f'{self.case_name}-volume_{self.guid}', size='2',
timeout=self.volume_timeout, wait=True)
def _write_data(self):
@@ -76,7 +76,7 @@ class CinderCheck(singlevm.SingleVm2):
return testcase.TestCase.EX_RUN_ERROR
self.logger.debug("ssh: %s", self.ssh)
(_, stdout, stderr) = self.ssh.exec_command(
- "sh ~/write_data.sh {}".format(env.get('VOLUME_DEVICE_NAME')))
+ f"sh ~/write_data.sh {env.get('VOLUME_DEVICE_NAME')}")
self.logger.debug(
"volume_write stdout: %s", stdout.read().decode("utf-8"))
self.logger.debug(
@@ -104,7 +104,7 @@ class CinderCheck(singlevm.SingleVm2):
return testcase.TestCase.EX_RUN_ERROR
self.logger.debug("ssh: %s", self.ssh2)
(_, stdout, stderr) = self.ssh2.exec_command(
- "sh ~/read_data.sh {}".format(env.get('VOLUME_DEVICE_NAME')))
+ f"sh ~/read_data.sh {env.get('VOLUME_DEVICE_NAME')}")
self.logger.debug(
"read volume stdout: %s", stdout.read().decode("utf-8"))
self.logger.debug(
@@ -124,4 +124,4 @@ class CinderCheck(singlevm.SingleVm2):
self.cloud.delete_floating_ip(self.fip2.id)
if self.volume:
self.cloud.delete_volume(self.volume.id)
- super(CinderCheck, self).clean()
+ super().clean()
diff --git a/functest/opnfv_tests/openstack/cinder/write_data.sh b/functest/opnfv_tests/openstack/cinder/write_data.sh
index 6689309b9..16845ba31 100644
--- a/functest/opnfv_tests/openstack/cinder/write_data.sh
+++ b/functest/opnfv_tests/openstack/cinder/write_data.sh
@@ -15,7 +15,7 @@ echo "VOL_DEV_NAME: $VOL_DEV_NAME"
echo "$(lsblk -l -o NAME)"
if [ ! -z $(lsblk -l -o NAME | grep $VOL_DEV_NAME) ]; then
- sudo /usr/sbin/mkfs.ext4 -F /dev/$VOL_DEV_NAME
+ sudo mkfs.ext4 -F /dev/$VOL_DEV_NAME
sudo mount /dev/$VOL_DEV_NAME $DEST
sudo touch $DEST/new_data
if [ -f $DEST/new_data ]; then
diff --git a/functest/opnfv_tests/openstack/patrole/patrole.py b/functest/opnfv_tests/openstack/patrole/patrole.py
index 8613d5127..88c42f269 100644
--- a/functest/opnfv_tests/openstack/patrole/patrole.py
+++ b/functest/opnfv_tests/openstack/patrole/patrole.py
@@ -9,8 +9,6 @@
# pylint: disable=missing-docstring
-import logging
-
from six.moves import configparser
from functest.opnfv_tests.openstack.tempest import tempest
@@ -18,15 +16,13 @@ from functest.opnfv_tests.openstack.tempest import tempest
class Patrole(tempest.TempestCommon):
- __logger = logging.getLogger(__name__)
-
def configure(self, **kwargs):
- super(Patrole, self).configure(**kwargs)
+ super().configure(**kwargs)
rconfig = configparser.RawConfigParser()
rconfig.read(self.conf_file)
if not rconfig.has_section('rbac'):
rconfig.add_section('rbac')
rconfig.set('rbac', 'rbac_test_roles', kwargs.get('roles', 'admin'))
- with open(self.conf_file, 'w') as config_file:
+ with open(self.conf_file, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
self.backup_tempest_config(self.conf_file, self.res_dir)
diff --git a/functest/opnfv_tests/openstack/rally/blacklist.yaml b/functest/opnfv_tests/openstack/rally/blacklist.yaml
index bc41bb695..e16b83ba6 100644
--- a/functest/opnfv_tests/openstack/rally/blacklist.yaml
+++ b/functest/opnfv_tests/openstack/rally/blacklist.yaml
@@ -26,7 +26,15 @@ functionality:
tests:
- HeatStacks.create_and_delete_stack
- NovaServers.boot_and_associate_floating_ip
+ - NovaServers.boot_server_and_list_interfaces
- NovaServers.boot_server_associate_and_dissociate_floating_ip
- NeutronNetworks.create_and_delete_floating_ips
- NeutronNetworks.create_and_list_floating_ips
- NeutronNetworks.associate_and_dissociate_floating_ips
+ - VMTasks.dd_load_test
+ - NeutronNetworks.create_and_delete_routers
+ - NeutronNetworks.create_and_list_routers
+ - NeutronNetworks.create_and_show_routers
+ - NeutronNetworks.create_and_update_routers
+ - NeutronNetworks.set_and_clear_router_gateway
+ - Quotas.neutron_update
diff --git a/functest/opnfv_tests/openstack/rally/rally.py b/functest/opnfv_tests/openstack/rally/rally.py
index 63f281b67..3d897e25d 100644
--- a/functest/opnfv_tests/openstack/rally/rally.py
+++ b/functest/opnfv_tests/openstack/rally/rally.py
@@ -69,13 +69,12 @@ class RallyBase(singlevm.VmReady2):
visibility = 'public'
shared_network = True
- allow_no_fip = True
task_timeout = 3600
username = 'cirros'
def __init__(self, **kwargs):
"""Initialize RallyBase object."""
- super(RallyBase, self).__init__(**kwargs)
+ super().__init__(**kwargs)
assert self.orig_cloud
assert self.project
if self.orig_cloud.get_role("admin"):
@@ -133,13 +132,20 @@ class RallyBase(singlevm.VmReady2):
if self.network:
task_args['netid'] = str(self.network.id)
else:
- task_args['netid'] = ''
+ LOGGER.warning(
+ 'No tenant network created. '
+ 'Trying EXTERNAL_NETWORK as a fallback')
+ if env.get("EXTERNAL_NETWORK"):
+ network = self.cloud.get_network(env.get("EXTERNAL_NETWORK"))
+ task_args['netid'] = str(network.id) if network else ''
+ else:
+ task_args['netid'] = ''
return task_args
def _prepare_test_list(self, test_name):
"""Build the list of test cases to be executed."""
- test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
+ test_yaml_file_name = f'opnfv-{test_name}.yaml'
scenario_file_name = os.path.join(self.rally_scenario_dir,
test_yaml_file_name)
@@ -148,8 +154,8 @@ class RallyBase(singlevm.VmReady2):
test_yaml_file_name)
if not os.path.exists(scenario_file_name):
- raise Exception("The scenario '%s' does not exist."
- % scenario_file_name)
+ raise Exception(
+ f"The scenario '{scenario_file_name}' does not exist.")
LOGGER.debug('Scenario fetched from : %s', scenario_file_name)
test_file_name = os.path.join(self.temp_dir, test_yaml_file_name)
@@ -168,10 +174,10 @@ class RallyBase(singlevm.VmReady2):
cmd = ("rally deployment list | awk '/" +
getattr(config.CONF, 'rally_deployment_name') +
"/ {print $2}'")
- proc = subprocess.Popen(cmd, shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
- deployment_uuid = proc.stdout.readline().rstrip()
+ with subprocess.Popen(
+ cmd, shell=True, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT) as proc:
+ deployment_uuid = proc.stdout.readline().rstrip()
return deployment_uuid.decode("utf-8")
@staticmethod
@@ -184,7 +190,9 @@ class RallyBase(singlevm.VmReady2):
if pod_arch and pod_arch in arch_filter:
LOGGER.info("Apply aarch64 specific to rally config...")
- with open(RallyBase.rally_aar4_patch_path, "r") as pfile:
+ with open(
+ RallyBase.rally_aar4_patch_path, "r",
+ encoding='utf-8') as pfile:
rally_patch_conf = pfile.read()
for line in fileinput.input(RallyBase.rally_conf_path):
@@ -222,7 +230,7 @@ class RallyBase(singlevm.VmReady2):
rconfig.add_section('openstack')
rconfig.set(
'openstack', 'keystone_default_role', env.get("NEW_USER_ROLE"))
- with open(rally_conf, 'w') as config_file:
+ with open(rally_conf, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
@staticmethod
@@ -233,7 +241,7 @@ class RallyBase(singlevm.VmReady2):
rconfig.read(rally_conf)
if rconfig.has_option('openstack', 'keystone_default_role'):
rconfig.remove_option('openstack', 'keystone_default_role')
- with open(rally_conf, 'w') as config_file:
+ with open(rally_conf, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
@staticmethod
@@ -285,7 +293,9 @@ class RallyBase(singlevm.VmReady2):
"""Exclude scenario."""
black_tests = []
try:
- with open(RallyBase.blacklist_file, 'r') as black_list_file:
+ with open(
+ RallyBase.blacklist_file, 'r',
+ encoding='utf-8') as black_list_file:
black_list_yaml = yaml.safe_load(black_list_file)
deploy_scenario = env.get('DEPLOY_SCENARIO')
@@ -329,7 +339,9 @@ class RallyBase(singlevm.VmReady2):
func_list = []
try:
- with open(RallyBase.blacklist_file, 'r') as black_list_file:
+ with open(
+ RallyBase.blacklist_file, 'r',
+ encoding='utf-8') as black_list_file:
black_list_yaml = yaml.safe_load(black_list_file)
if env.get('BLOCK_MIGRATION').lower() == 'true':
@@ -356,31 +368,25 @@ class RallyBase(singlevm.VmReady2):
def apply_blacklist(self, case_file_name, result_file_name):
"""Apply blacklist."""
LOGGER.debug("Applying blacklist...")
- cases_file = open(case_file_name, 'r')
- result_file = open(result_file_name, 'w')
-
- black_tests = list(set(self.excl_func() +
- self.excl_scenario()))
-
- if black_tests:
- LOGGER.debug("Blacklisted tests: %s", str(black_tests))
-
- include = True
- for cases_line in cases_file:
- if include:
- for black_tests_line in black_tests:
- if re.search(black_tests_line,
- cases_line.strip().rstrip(':')):
- include = False
- break
+ with open(case_file_name, 'r', encoding='utf-8') as cases_file, open(
+ result_file_name, 'w', encoding='utf-8') as result_file:
+ black_tests = list(set(self.excl_func() + self.excl_scenario()))
+ if black_tests:
+ LOGGER.debug("Blacklisted tests: %s", str(black_tests))
+
+ include = True
+ for cases_line in cases_file:
+ if include:
+ for black_tests_line in black_tests:
+ if re.search(black_tests_line,
+ cases_line.strip().rstrip(':')):
+ include = False
+ break
+ else:
+ result_file.write(str(cases_line))
else:
- result_file.write(str(cases_line))
- else:
- if cases_line.isspace():
- include = True
-
- cases_file.close()
- result_file.close()
+ if cases_line.isspace():
+ include = True
@staticmethod
def file_is_empty(file_name):
@@ -408,7 +414,7 @@ class RallyBase(singlevm.VmReady2):
LOGGER.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
# save report as JSON
- report_json_name = '{}.json'.format(test_name)
+ report_json_name = f'{test_name}.json'
report_json_dir = os.path.join(self.results_dir, report_json_name)
cmd = (["rally", "task", "report", "--json", "--uuid", task_id,
"--out", report_json_dir])
@@ -416,7 +422,8 @@ class RallyBase(singlevm.VmReady2):
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
LOGGER.info("%s\n%s", " ".join(cmd), output.decode("utf-8"))
- json_results = open(report_json_dir).read()
+ with open(report_json_dir, encoding='utf-8') as json_file:
+ json_results = json_file.read()
self._append_summary(json_results, test_name)
# parse JSON operation result
@@ -491,7 +498,7 @@ class RallyBase(singlevm.VmReady2):
if test in self.stests:
self.tests.append(test)
else:
- raise Exception("Test name '%s' is invalid" % test)
+ raise Exception(f"Test name '{test}' is invalid")
if not os.path.exists(self.task_dir):
os.makedirs(self.task_dir)
@@ -499,16 +506,14 @@ class RallyBase(singlevm.VmReady2):
task = os.path.join(self.rally_dir, 'task.yaml')
if not os.path.exists(task):
LOGGER.error("Task file '%s' does not exist.", task)
- raise Exception("Task file '{}' does not exist.".
- format(task))
+ raise Exception(f"Task file '{task}' does not exist.")
self.task_file = os.path.join(self.task_dir, 'task.yaml')
shutil.copyfile(task, self.task_file)
task_macro = os.path.join(self.rally_dir, 'macro')
if not os.path.exists(task_macro):
LOGGER.error("Task macro dir '%s' does not exist.", task_macro)
- raise Exception("Task macro dir '{}' does not exist.".
- format(task_macro))
+ raise Exception(f"Task macro dir '{task_macro}' does not exist.")
macro_dir = os.path.join(self.task_dir, 'macro')
if os.path.exists(macro_dir):
shutil.rmtree(macro_dir)
@@ -569,7 +574,7 @@ class RallyBase(singlevm.VmReady2):
success_avg = 100 * item['nb_success'] / item['nb_tests']
except ZeroDivisionError:
success_avg = 0
- success_str = str("{:0.2f}".format(success_avg)) + '%'
+ success_str = f"{success_avg:0.2f}%"
duration_str = time.strftime("%H:%M:%S",
time.gmtime(item['overall_duration']))
res_table.add_row([item['test_name'], duration_str,
@@ -587,7 +592,7 @@ class RallyBase(singlevm.VmReady2):
self.result = 100 * total_nb_success / total_nb_tests
except ZeroDivisionError:
self.result = 100
- success_rate = "{:0.2f}".format(self.result)
+ success_rate = f"{self.result:0.2f}"
success_rate_str = str(success_rate) + '%'
res_table.add_row(["", "", "", ""])
res_table.add_row(["TOTAL:", total_duration_str, total_nb_tests,
@@ -642,7 +647,7 @@ class RallyBase(singlevm.VmReady2):
self.clean_rally_logs()
if self.flavor_alt:
self.orig_cloud.delete_flavor(self.flavor_alt.id)
- super(RallyBase, self).clean()
+ super().clean()
def is_successful(self):
"""The overall result of the test."""
@@ -650,7 +655,7 @@ class RallyBase(singlevm.VmReady2):
if item['task_status'] is False:
return testcase.TestCase.EX_TESTCASE_FAILED
- return super(RallyBase, self).is_successful()
+ return super().is_successful()
@staticmethod
def update_rally_logs(res_dir, rally_conf='/etc/rally/rally.conf'):
@@ -663,7 +668,7 @@ class RallyBase(singlevm.VmReady2):
rconfig.set('DEFAULT', 'use_stderr', False)
rconfig.set('DEFAULT', 'log-file', 'rally.log')
rconfig.set('DEFAULT', 'log_dir', res_dir)
- with open(rally_conf, 'w') as config_file:
+ with open(rally_conf, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
@staticmethod
@@ -679,14 +684,14 @@ class RallyBase(singlevm.VmReady2):
rconfig.remove_option('DEFAULT', 'log-file')
if rconfig.has_option('DEFAULT', 'log_dir'):
rconfig.remove_option('DEFAULT', 'log_dir')
- with open(rally_conf, 'w') as config_file:
+ with open(rally_conf, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
def run(self, **kwargs):
"""Run testcase."""
self.start_time = time.time()
try:
- assert super(RallyBase, self).run(
+ assert super().run(
**kwargs) == testcase.TestCase.EX_OK
self.update_rally_logs(self.res_dir)
self.create_rally_deployment(environ=self.project.get_environ())
@@ -694,9 +699,9 @@ class RallyBase(singlevm.VmReady2):
self.run_tests(**kwargs)
self._generate_report()
self.export_task(
- "{}/{}.html".format(self.results_dir, self.case_name))
+ f"{self.results_dir}/{self.case_name}.html")
self.export_task(
- "{}/{}.xml".format(self.results_dir, self.case_name),
+ f"{self.results_dir}/{self.case_name}.xml",
export_type="junit-xml")
res = testcase.TestCase.EX_OK
except Exception: # pylint: disable=broad-except
@@ -714,7 +719,7 @@ class RallySanity(RallyBase):
"""Initialize RallySanity object."""
if "case_name" not in kwargs:
kwargs["case_name"] = "rally_sanity"
- super(RallySanity, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.smoke = True
self.scenario_dir = os.path.join(self.rally_scenario_dir, 'sanity')
@@ -728,7 +733,7 @@ class RallyFull(RallyBase):
"""Initialize RallyFull object."""
if "case_name" not in kwargs:
kwargs["case_name"] = "rally_full"
- super(RallyFull, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.smoke = False
self.scenario_dir = os.path.join(self.rally_scenario_dir, 'full')
@@ -743,21 +748,21 @@ class RallyJobs(RallyBase):
"""Initialize RallyJobs object."""
if "case_name" not in kwargs:
kwargs["case_name"] = "rally_jobs"
- super(RallyJobs, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.task_file = os.path.join(self.rally_dir, 'rally_jobs.yaml')
self.task_yaml = None
def prepare_run(self, **kwargs):
"""Create resources needed by test scenarios."""
- super(RallyJobs, self).prepare_run(**kwargs)
- with open(os.path.join(self.rally_dir,
- 'rally_jobs.yaml'), 'r') as task_file:
+ super().prepare_run(**kwargs)
+ with open(
+ os.path.join(self.rally_dir, 'rally_jobs.yaml'),
+ 'r', encoding='utf-8') as task_file:
self.task_yaml = yaml.safe_load(task_file)
for task in self.task_yaml:
if task not in self.tests:
- raise Exception("Test '%s' not in '%s'" %
- (task, self.tests))
+ raise Exception(f"Test '{task}' not in '{self.tests}'")
def apply_blacklist(self, case_file_name, result_file_name):
# pylint: disable=too-many-branches
@@ -769,7 +774,7 @@ class RallyJobs(RallyBase):
LOGGER.debug("Blacklisted tests: %s", str(black_tests))
template = YAML(typ='jinja2')
- with open(case_file_name, 'r') as fname:
+ with open(case_file_name, 'r', encoding='utf-8') as fname:
cases = template.load(fname)
if cases.get("version", 1) == 1:
# scenarios in dictionary
@@ -799,7 +804,7 @@ class RallyJobs(RallyBase):
cases['subtasks'].pop(sind)
break
- with open(result_file_name, 'w') as fname:
+ with open(result_file_name, 'w', encoding='utf-8') as fname:
template.dump(cases, fname)
def build_task_args(self, test_name):
@@ -820,7 +825,7 @@ class RallyJobs(RallyBase):
task_name = self.task_yaml.get(test_name).get("task")
task = os.path.join(jobs_dir, task_name)
if not os.path.exists(task):
- raise Exception("The scenario '%s' does not exist." % task)
+ raise Exception(f"The scenario '{task}' does not exist.")
LOGGER.debug('Scenario fetched from : %s', task)
if not os.path.exists(self.temp_dir):
diff --git a/functest/opnfv_tests/openstack/rally/scenario/full/opnfv-cinder.yaml b/functest/opnfv_tests/openstack/rally/scenario/full/opnfv-cinder.yaml
index 4b3c22ebd..7abeeac68 100644
--- a/functest/opnfv_tests/openstack/rally/scenario/full/opnfv-cinder.yaml
+++ b/functest/opnfv_tests/openstack/rally/scenario/full/opnfv-cinder.yaml
@@ -348,20 +348,6 @@
sla:
{{ no_failures_sla() }}
- CinderVolumeTypes.create_and_update_volume_type:
- -
- args:
- description: "test"
- update_description: "test update"
- context:
- {{ user_context(tenants_amount, users_amount, use_existing_users) }}
- api_versions:
- {{ volume_service(version=volume_version, service_type=volume_service_type) }}
- runner:
- {{ constant_runner(concurrency=concurrency, times=iterations, is_smoke=smoke) }}
- sla:
- {{ no_failures_sla() }}
-
CinderVolumeTypes.create_volume_type_and_encryption_type:
-
args:
@@ -378,16 +364,3 @@
{{ constant_runner(concurrency=concurrency, times=iterations, is_smoke=smoke) }}
sla:
{{ no_failures_sla() }}
-
- CinderVolumeTypes.create_volume_type_add_and_list_type_access:
- -
- args:
- description: "rally tests creating types"
- context:
- {{ user_context(tenants_amount, users_amount, use_existing_users) }}
- api_versions:
- {{ volume_service(version=volume_version, service_type=volume_service_type) }}
- runner:
- {{ constant_runner(concurrency=concurrency, times=iterations, is_smoke=smoke) }}
- sla:
- {{ no_failures_sla() }}
diff --git a/functest/opnfv_tests/openstack/rally/scenario/full/opnfv-nova.yaml b/functest/opnfv_tests/openstack/rally/scenario/full/opnfv-nova.yaml
index 71a159963..210591f9b 100644
--- a/functest/opnfv_tests/openstack/rally/scenario/full/opnfv-nova.yaml
+++ b/functest/opnfv_tests/openstack/rally/scenario/full/opnfv-nova.yaml
@@ -39,9 +39,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_neutron() }}
{{ unlimited_nova() }}
@@ -59,9 +56,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_neutron() }}
{{ unlimited_nova() }}
@@ -80,9 +74,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_neutron() }}
{{ unlimited_nova() }}
@@ -104,9 +95,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_neutron() }}
{{ unlimited_nova() }}
@@ -124,9 +112,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_neutron() }}
{{ unlimited_nova() }}
@@ -256,9 +241,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_neutron() }}
{{ unlimited_nova(keypairs=true) }}
@@ -277,9 +259,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_volumes() }}
{{ unlimited_neutron() }}
@@ -301,9 +280,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_neutron() }}
{{ unlimited_nova() }}
@@ -395,8 +371,7 @@
-
args:
{{ vm_params(image_name, flavor_name) }}
- create_floating_ip_args:
- floating_network: {{ floating_network }}
+ floating_network: {{ floating_network }}
nics:
- net-id: {{ netid }}
context:
@@ -412,8 +387,7 @@
-
args:
{{ vm_params(image_name, flavor_name) }}
- create_floating_ip_args:
- floating_network: {{ floating_network }}
+ floating_network: {{ floating_network }}
nics:
- net-id: {{ netid }}
context:
diff --git a/functest/opnfv_tests/openstack/rally/scenario/sanity/opnfv-nova.yaml b/functest/opnfv_tests/openstack/rally/scenario/sanity/opnfv-nova.yaml
index 138e53b00..1fbfccb5a 100644
--- a/functest/opnfv_tests/openstack/rally/scenario/sanity/opnfv-nova.yaml
+++ b/functest/opnfv_tests/openstack/rally/scenario/sanity/opnfv-nova.yaml
@@ -55,9 +55,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_neutron() }}
{{ unlimited_nova(keypairs=true) }}
@@ -76,9 +73,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_volumes() }}
{{ unlimited_neutron() }}
@@ -100,9 +94,6 @@
- net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
- network:
- networks_per_tenant: 1
- start_cidr: "100.1.0.0/25"
quotas:
{{ unlimited_neutron() }}
{{ unlimited_nova() }}
@@ -128,7 +119,8 @@
-
args:
{{ vm_params(image_name, flavor_name) }}
- auto_assign_nic: true
+ nics:
+ - net-id: {{ netid }}
context:
{% call user_context(tenants_amount, users_amount, use_existing_users) %}
network: {}
@@ -142,8 +134,7 @@
-
args:
{{ vm_params(image_name, flavor_name) }}
- create_floating_ip_args:
- floating_network: {{ floating_network }}
+ floating_network: {{ floating_network }}
nics:
- net-id: {{ netid }}
context:
diff --git a/functest/opnfv_tests/openstack/rally/scenario/templates/server_with_ports.yaml.template b/functest/opnfv_tests/openstack/rally/scenario/templates/server_with_ports.yaml.template
index f1a12c178..75afb2dbe 100644
--- a/functest/opnfv_tests/openstack/rally/scenario/templates/server_with_ports.yaml.template
+++ b/functest/opnfv_tests/openstack/rally/scenario/templates/server_with_ports.yaml.template
@@ -7,7 +7,7 @@ parameters:
default: public
image:
type: string
- default: cirros-0.5.1-x86_64-uec
+ default: cirros-0.6.1-x86_64-uec
flavor:
type: string
default: m1.tiny
diff --git a/functest/opnfv_tests/openstack/refstack/refstack.py b/functest/opnfv_tests/openstack/refstack/refstack.py
index faf183f76..87932020b 100644
--- a/functest/opnfv_tests/openstack/refstack/refstack.py
+++ b/functest/opnfv_tests/openstack/refstack/refstack.py
@@ -26,12 +26,11 @@ class Refstack(tempest.TempestCommon):
def _extract_refstack_data(self, refstack_list):
yaml_data = ""
- with open(refstack_list) as def_file:
+ with open(refstack_list, encoding='utf-8') as def_file:
for line in def_file:
try:
grp = re.search(r'^([^\[]*)(\[.*\])\n*$', line)
- yaml_data = "{}\n{}: {}".format(
- yaml_data, grp.group(1), grp.group(2))
+ yaml_data = f"{yaml_data}\n{grp.group(1)}: {grp.group(2)}"
except Exception: # pylint: disable=broad-except
self.__logger.warning("Cannot parse %s", line)
return yaml.full_load(yaml_data)
@@ -53,8 +52,7 @@ class Refstack(tempest.TempestCommon):
for line in output.splitlines():
try:
grp = re.search(r'^([^\[]*)(\[.*\])\n*$', line.decode("utf-8"))
- yaml_data2 = "{}\n{}: {}".format(
- yaml_data2, grp.group(1), grp.group(2))
+ yaml_data2 = f"{yaml_data2}\n{grp.group(1)}: {grp.group(2)}"
except Exception: # pylint: disable=broad-except
self.__logger.warning("Cannot parse %s. skipping it", line)
return yaml.full_load(yaml_data2)
@@ -62,11 +60,11 @@ class Refstack(tempest.TempestCommon):
def generate_test_list(self, **kwargs):
refstack_list = os.path.join(
getattr(config.CONF, 'dir_refstack_data'),
- "{}.txt".format(kwargs.get('target', 'compute')))
+ f"{kwargs.get('target', 'compute')}.txt")
self.backup_tempest_config(self.conf_file, '/etc')
refstack_data = self._extract_refstack_data(refstack_list)
tempest_data = self._extract_tempest_data()
- with open(self.list, 'w') as ref_file:
+ with open(self.list, 'w', encoding='utf-8') as ref_file:
for key in refstack_data.keys():
try:
for data in tempest_data[key]:
@@ -75,9 +73,9 @@ class Refstack(tempest.TempestCommon):
else:
self.__logger.info("%s: ids differ. skipping it", key)
continue
- ref_file.write("{}{}\n".format(
- key, str(tempest_data[key]).replace(
- "'", "").replace(", ", ",")))
+ value = str(tempest_data[key]).replace(
+ "'", "").replace(", ", ",")
+ ref_file.write(f"{key}{value}\n")
except Exception: # pylint: disable=broad-except
self.__logger.info("%s: not found. skipping it", key)
continue
diff --git a/functest/opnfv_tests/openstack/shaker/shaker.py b/functest/opnfv_tests/openstack/shaker/shaker.py
index 917c65980..275cc3077 100644
--- a/functest/opnfv_tests/openstack/shaker/shaker.py
+++ b/functest/opnfv_tests/openstack/shaker/shaker.py
@@ -32,7 +32,7 @@ class Shaker(singlevm.SingleVm2):
__logger = logging.getLogger(__name__)
- filename = '/home/opnfv/functest/images/shaker-image-1.3.0+stretch.qcow2'
+ filename = '/home/opnfv/functest/images/shaker-image-1.3.4+stretch.qcow2'
flavor_ram = 512
flavor_vcpus = 1
flavor_disk = 3
@@ -47,7 +47,7 @@ class Shaker(singlevm.SingleVm2):
check_console_loop = 12
def __init__(self, **kwargs):
- super(Shaker, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.role = None
def check_requirements(self):
@@ -57,7 +57,7 @@ class Shaker(singlevm.SingleVm2):
self.project.clean()
def prepare(self):
- super(Shaker, self).prepare()
+ super().prepare()
self.cloud.create_security_group_rule(
self.sec.id, port_range_min=self.port, port_range_max=self.port,
protocol='tcp', direction='ingress')
@@ -95,33 +95,31 @@ class Shaker(singlevm.SingleVm2):
scpc.put('/home/opnfv/functest/conf/env_file', remote_path='~/')
if os.environ.get('OS_CACERT'):
scpc.put(os.environ.get('OS_CACERT'), remote_path='~/os_cacert')
+ opt = 'export OS_CACERT=~/os_cacert && ' if os.environ.get(
+ 'OS_CACERT') else ''
(_, stdout, stderr) = self.ssh.exec_command(
'source ~/env_file && '
'export OS_INTERFACE=public && '
- 'export OS_AUTH_URL={} && '
- 'export OS_USERNAME={} && '
- 'export OS_PROJECT_NAME={} && '
- 'export OS_PROJECT_ID={} && '
+ f'export OS_AUTH_URL={endpoint} && '
+ f'export OS_USERNAME={self.project.user.name} && '
+ f'export OS_PROJECT_NAME={self.project.project.name} && '
+ f'export OS_PROJECT_ID={self.project.project.id} && '
'unset OS_TENANT_NAME && '
'unset OS_TENANT_ID && '
'unset OS_ENDPOINT_TYPE && '
- 'export OS_PASSWORD="{}" && '
- '{}'
+ f'export OS_PASSWORD="{self.project.password}" && '
+ f'{opt}'
'env && '
- 'timeout {} shaker --debug --image-name {} --flavor-name {} '
- '--server-endpoint {}:9000 --external-net {} --dns-nameservers {} '
+ f'timeout {self.shaker_timeout} shaker --debug '
+ f'--image-name {self.image.name} --flavor-name {self.flavor.name} '
+ f'--server-endpoint {self.fip.floating_ip_address}:9000 '
+ f'--external-net {self.ext_net.id} '
+ f"--dns-nameservers {env.get('NAMESERVER')} "
'--scenario openstack/full_l2,'
'openstack/full_l3_east_west,'
'openstack/full_l3_north_south,'
'openstack/perf_l3_north_south '
- '--report report.html --output report.json'.format(
- endpoint, self.project.user.name, self.project.project.name,
- self.project.project.id, self.project.password,
- 'export OS_CACERT=~/os_cacert && ' if os.environ.get(
- 'OS_CACERT') else '',
- self.shaker_timeout, self.image.name, self.flavor.name,
- self.fip.floating_ip_address, self.ext_net.id,
- env.get('NAMESERVER')))
+ '--report report.html --output report.json')
self.__logger.info("output:\n%s", stdout.read().decode("utf-8"))
self.__logger.info("error:\n%s", stderr.read().decode("utf-8"))
if not os.path.exists(self.res_dir):
@@ -132,7 +130,9 @@ class Shaker(singlevm.SingleVm2):
except scp.SCPException:
self.__logger.exception("cannot get report files")
return 1
- with open(os.path.join(self.res_dir, 'report.json')) as json_file:
+ with open(
+ os.path.join(self.res_dir, 'report.json'),
+ encoding='utf-8') as json_file:
data = json.load(json_file)
for value in data["records"].values():
if value["status"] != "ok":
@@ -142,6 +142,6 @@ class Shaker(singlevm.SingleVm2):
return stdout.channel.recv_exit_status()
def clean(self):
- super(Shaker, self).clean()
+ super().clean()
if self.role:
self.orig_cloud.delete_role(self.role.id)
diff --git a/functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml b/functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml
index a444a54f5..0ee4ab613 100644
--- a/functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml
+++ b/functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf.yaml
@@ -1,5 +1,6 @@
---
compute:
+ min_microversion: '2.44'
max_microversion: latest
compute-feature-enabled:
attach_encrypted_volume: false
@@ -11,6 +12,7 @@ compute-feature-enabled:
console_output: true
disk_config: true
enable_instance_password: true
+ hostname_fqdn_sanitization: true
interface_attach: true
live_migration: true
live_migrate_back_and_forth: false
@@ -46,13 +48,14 @@ identity-feature-enabled:
external_idp: false
project_tags: true
application_credentials: true
+ access_rules: true
image-feature-enabled:
api_v2: true
api_v1: false
+ import_image: false
network-feature-enabled:
port_admin_state_change: true
port_security: true
- floating_ips: true
placement:
max_microversion: latest
validation:
@@ -60,7 +63,6 @@ validation:
ssh_timeout: 196
ip_version_for_ssh: 4
run_validation: true
- connect_method: floating
volume:
max_microversion: latest
storage_protocol: ceph
@@ -73,7 +75,8 @@ volume-feature-enabled:
clone: true
manage_snapshot: true
manage_volume: true
- extend_attached_volume: false
+ extend_attached_volume: true
+ extend_attached_encrypted_volume: false
consistency_group: false
volume_revert: true
load_balancer:
@@ -81,13 +84,14 @@ load_balancer:
neutron_plugin_options:
agent_availability_zone: nova
available_type_drivers: flat,geneve,vlan,gre,local,vxlan
- provider_vlans: foo,
+ provider_vlans: public,
create_shared_resources: true
object-storage-feature-enabled:
discoverable_apis: "account_quotas,formpost,bulk_upload,bulk_delete,\
tempurl,crossdomain,container_quotas,staticweb,account_quotas,slo"
object_versioning: true
discoverability: true
+ tempurl_digest_hashlib: sha1
heat_plugin:
skip_functional_test_list: EncryptionVolTypeTest
skip_scenario_test_list: "AodhAlarmTest,SoftwareConfigIntegrationTest,\
diff --git a/functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf_ovn.yaml b/functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf_ovn.yaml
index 141f295b4..6b09d8e5a 100644
--- a/functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf_ovn.yaml
+++ b/functest/opnfv_tests/openstack/tempest/custom_tests/tempest_conf_ovn.yaml
@@ -1,5 +1,6 @@
---
compute:
+ min_microversion: '2.44'
max_microversion: latest
compute-feature-enabled:
attach_encrypted_volume: false
@@ -11,6 +12,7 @@ compute-feature-enabled:
console_output: true
disk_config: true
enable_instance_password: true
+ hostname_fqdn_sanitization: true
interface_attach: true
live_migration: true
live_migrate_back_and_forth: false
@@ -46,13 +48,14 @@ identity-feature-enabled:
external_idp: false
project_tags: true
application_credentials: true
+ access_rules: true
image-feature-enabled:
api_v2: true
api_v1: false
+ import_image: false
network-feature-enabled:
port_admin_state_change: true
port_security: true
- floating_ips: true
placement:
max_microversion: latest
validation:
@@ -60,7 +63,6 @@ validation:
ssh_timeout: 196
ip_version_for_ssh: 4
run_validation: true
- connect_method: floating
volume:
max_microversion: latest
storage_protocol: ceph
@@ -73,7 +75,8 @@ volume-feature-enabled:
clone: true
manage_snapshot: true
manage_volume: true
- extend_attached_volume: false
+ extend_attached_volume: true
+ extend_attached_encrypted_volume: false
consistency_group: false
volume_revert: true
load_balancer:
@@ -88,6 +91,7 @@ object-storage-feature-enabled:
tempurl,crossdomain,container_quotas,staticweb,account_quotas,slo"
object_versioning: true
discoverability: true
+ tempurl_digest_hashlib: sha1
heat_plugin:
skip_functional_test_list: EncryptionVolTypeTest
skip_scenario_test_list: "AodhAlarmTest,SoftwareConfigIntegrationTest,\
diff --git a/functest/opnfv_tests/openstack/tempest/tempest.py b/functest/opnfv_tests/openstack/tempest/tempest.py
index d2c54262a..7233ffd60 100644
--- a/functest/opnfv_tests/openstack/tempest/tempest.py
+++ b/functest/opnfv_tests/openstack/tempest/tempest.py
@@ -39,7 +39,7 @@ class TempestCommon(singlevm.VmReady2):
"""TempestCommon testcases implementation class."""
visibility = 'public'
- filename_alt = '/home/opnfv/functest/images/cirros-0.4.0-x86_64-disk.img'
+ filename_alt = '/home/opnfv/functest/images/cirros-0.6.1-x86_64-disk.img'
shared_network = True
tempest_conf_yaml = pkg_resources.resource_filename(
'functest',
@@ -57,7 +57,7 @@ class TempestCommon(singlevm.VmReady2):
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = 'tempest'
- super(TempestCommon, self).__init__(**kwargs)
+ super().__init__(**kwargs)
assert self.orig_cloud
assert self.cloud
assert self.project
@@ -128,7 +128,7 @@ class TempestCommon(singlevm.VmReady2):
@staticmethod
def read_file(filename):
"""Read file and return content as a stripped list."""
- with open(filename) as src:
+ with open(filename, encoding='utf-8') as src:
return [line.strip() for line in src.readlines()]
@staticmethod
@@ -142,22 +142,22 @@ class TempestCommon(singlevm.VmReady2):
}
cmd = ["rally", "verify", "show", "--uuid", verif_id]
LOGGER.info("Showing result for a verification: '%s'.", cmd)
- proc = subprocess.Popen(cmd,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
- for line in proc.stdout:
- LOGGER.info(line.decode("utf-8").rstrip())
- new_line = line.decode("utf-8").replace(' ', '').split('|')
- if 'Tests' in new_line:
- break
- if 'Testscount' in new_line:
- result['num_tests'] = int(new_line[2])
- elif 'Success' in new_line:
- result['num_success'] = int(new_line[2])
- elif 'Skipped' in new_line:
- result['num_skipped'] = int(new_line[2])
- elif 'Failures' in new_line:
- result['num_failures'] = int(new_line[2])
+ with subprocess.Popen(
+ cmd, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT) as proc:
+ for line in proc.stdout:
+ LOGGER.info(line.decode("utf-8").rstrip())
+ new_line = line.decode("utf-8").replace(' ', '').split('|')
+ if 'Tests' in new_line:
+ break
+ if 'Testscount' in new_line:
+ result['num_tests'] = int(new_line[2])
+ elif 'Success' in new_line:
+ result['num_success'] = int(new_line[2])
+ elif 'Skipped' in new_line:
+ result['num_skipped'] = int(new_line[2])
+ elif 'Failures' in new_line:
+ result['num_failures'] = int(new_line[2])
return result
@staticmethod
@@ -199,10 +199,10 @@ class TempestCommon(singlevm.VmReady2):
cmd = ("rally verify list-verifiers | awk '/" +
getattr(config.CONF, 'tempest_verifier_name') +
"/ {print $2}'")
- proc = subprocess.Popen(cmd, shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.DEVNULL)
- verifier_uuid = proc.stdout.readline().rstrip()
+ with subprocess.Popen(
+ cmd, shell=True, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL) as proc:
+ verifier_uuid = proc.stdout.readline().rstrip()
return verifier_uuid.decode("utf-8")
@staticmethod
@@ -212,7 +212,7 @@ class TempestCommon(singlevm.VmReady2):
"""
return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
'verification',
- 'verifier-{}'.format(verifier_id),
+ f'verifier-{verifier_id}',
'repo')
@staticmethod
@@ -222,13 +222,13 @@ class TempestCommon(singlevm.VmReady2):
"""
return os.path.join(getattr(config.CONF, 'dir_rally_inst'),
'verification',
- 'verifier-{}'.format(verifier_id),
- 'for-deployment-{}'.format(deployment_id))
+ f'verifier-{verifier_id}',
+ f'for-deployment-{deployment_id}')
@staticmethod
def update_tempest_conf_file(conf_file, rconfig):
"""Update defined paramters into tempest config file"""
- with open(TempestCommon.tempest_conf_yaml) as yfile:
+ with open(TempestCommon.tempest_conf_yaml, encoding='utf-8') as yfile:
conf_yaml = yaml.safe_load(yfile)
if conf_yaml:
sections = rconfig.sections()
@@ -239,7 +239,7 @@ class TempestCommon(singlevm.VmReady2):
for key, value in sub_conf.items():
rconfig.set(section, key, value)
- with open(conf_file, 'w') as config_file:
+ with open(conf_file, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
@staticmethod
@@ -272,17 +272,6 @@ class TempestCommon(singlevm.VmReady2):
rconfig.set('compute-feature-enabled', 'live_migration', True)
if os.environ.get('OS_REGION_NAME'):
rconfig.set('identity', 'region', os.environ.get('OS_REGION_NAME'))
- if env.get("NEW_USER_ROLE").lower() != "member":
- rconfig.set(
- 'auth', 'tempest_roles',
- functest_utils.convert_list_to_ini([env.get("NEW_USER_ROLE")]))
- if not json.loads(env.get("USE_DYNAMIC_CREDENTIALS").lower()):
- rconfig.set('auth', 'use_dynamic_credentials', False)
- account_file = os.path.join(
- getattr(config.CONF, 'dir_functest_data'), 'accounts.yaml')
- assert os.path.exists(
- account_file), "{} doesn't exist".format(account_file)
- rconfig.set('auth', 'test_accounts_file', account_file)
rconfig.set('identity', 'admin_role', admin_role_name)
rconfig.set('identity', 'default_domain_id', domain_id)
if not rconfig.has_section('network'):
@@ -335,13 +324,13 @@ class TempestCommon(singlevm.VmReady2):
shutil.copyfile(
self.tempest_custom, self.list)
else:
- raise Exception("Tempest test list file %s NOT found."
- % self.tempest_custom)
+ raise Exception(
+ f"Tempest test list file {self.tempest_custom} NOT found.")
else:
testr_mode = kwargs.get(
'mode', r'^tempest\.(api|scenario).*\[.*\bsmoke\b.*\]$')
- cmd = "(cd {0}; stestr list '{1}' >{2} 2>/dev/null)".format(
- self.verifier_repo_dir, testr_mode, self.list)
+ cmd = (f"(cd {self.verifier_repo_dir}; "
+ f"stestr list '{testr_mode}' > {self.list} 2>/dev/null)")
output = subprocess.check_output(cmd, shell=True)
LOGGER.info("%s\n%s", cmd, output.decode("utf-8"))
os.remove('/etc/tempest.conf')
@@ -353,32 +342,31 @@ class TempestCommon(singlevm.VmReady2):
os.remove(self.raw_list)
os.rename(self.list, self.raw_list)
cases_file = self.read_file(self.raw_list)
- result_file = open(self.list, 'w')
- black_tests = []
- try:
- deploy_scenario = env.get('DEPLOY_SCENARIO')
- if bool(deploy_scenario):
- # if DEPLOY_SCENARIO is set we read the file
- black_list_file = open(black_list)
- black_list_yaml = yaml.safe_load(black_list_file)
- black_list_file.close()
- for item in black_list_yaml:
- scenarios = item['scenarios']
- in_it = rally.RallyBase.in_iterable_re
- if in_it(deploy_scenario, scenarios):
- tests = item['tests']
- black_tests.extend(tests)
- except Exception: # pylint: disable=broad-except
+ with open(self.list, 'w', encoding='utf-8') as result_file:
black_tests = []
- LOGGER.debug("Tempest blacklist file does not exist.")
+ try:
+ deploy_scenario = env.get('DEPLOY_SCENARIO')
+ if bool(deploy_scenario):
+ # if DEPLOY_SCENARIO is set we read the file
+ with open(black_list, encoding='utf-8') as black_list_file:
+ black_list_yaml = yaml.safe_load(black_list_file)
+ black_list_file.close()
+ for item in black_list_yaml:
+ scenarios = item['scenarios']
+ in_it = rally.RallyBase.in_iterable_re
+ if in_it(deploy_scenario, scenarios):
+ tests = item['tests']
+ black_tests.extend(tests)
+ except Exception: # pylint: disable=broad-except
+ black_tests = []
+ LOGGER.debug("Tempest blacklist file does not exist.")
- for cases_line in cases_file:
- for black_tests_line in black_tests:
- if re.search(black_tests_line, cases_line):
- break
- else:
- result_file.write(str(cases_line) + '\n')
- result_file.close()
+ for cases_line in cases_file:
+ for black_tests_line in black_tests:
+ if re.search(black_tests_line, cases_line):
+ break
+ else:
+ result_file.write(str(cases_line) + '\n')
def run_verifier_tests(self, **kwargs):
"""Execute tempest test cases."""
@@ -387,33 +375,31 @@ class TempestCommon(singlevm.VmReady2):
cmd.extend(kwargs.get('option', []))
LOGGER.info("Starting Tempest test suite: '%s'.", cmd)
- f_stdout = open(
- os.path.join(self.res_dir, "tempest.log"), 'w+')
-
- proc = subprocess.Popen(
- cmd,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- bufsize=1)
-
- with proc.stdout:
- for line in iter(proc.stdout.readline, b''):
- if re.search(r"\} tempest\.", line.decode("utf-8")):
- LOGGER.info(line.rstrip())
- elif re.search(r'(?=\(UUID=(.*)\))', line.decode("utf-8")):
- self.verification_id = re.search(
- r'(?=\(UUID=(.*)\))', line.decode("utf-8")).group(1)
- f_stdout.write(line.decode("utf-8"))
- proc.wait()
- f_stdout.close()
+ with open(
+ os.path.join(self.res_dir, "tempest.log"), 'w+',
+ encoding='utf-8') as f_stdout:
+ with subprocess.Popen(
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+ bufsize=1) as proc:
+ with proc.stdout:
+ for line in iter(proc.stdout.readline, b''):
+ if re.search(r"\} tempest\.", line.decode("utf-8")):
+ LOGGER.info(line.rstrip())
+ elif re.search(r'(?=\(UUID=(.*)\))',
+ line.decode("utf-8")):
+ self.verification_id = re.search(
+ r'(?=\(UUID=(.*)\))',
+ line.decode("utf-8")).group(1)
+ f_stdout.write(line.decode("utf-8"))
+ proc.wait()
if self.verification_id is None:
raise Exception('Verification UUID not found')
LOGGER.info('Verification UUID: %s', self.verification_id)
shutil.copy(
- "{}/tempest.log".format(self.deployment_dir),
- "{}/tempest.debug.log".format(self.res_dir))
+ f"{self.deployment_dir}/tempest.log",
+ f"{self.res_dir}/tempest.debug.log")
def parse_verifier_result(self):
"""Parse and save test results."""
@@ -430,8 +416,8 @@ class TempestCommon(singlevm.VmReady2):
LOGGER.error("No test has been executed")
return
- with open(os.path.join(self.res_dir,
- "rally.log"), 'r') as logfile:
+ with open(os.path.join(self.res_dir, "rally.log"),
+ 'r', encoding='utf-8') as logfile:
output = logfile.read()
success_testcases = []
@@ -466,9 +452,8 @@ class TempestCommon(singlevm.VmReady2):
rconfig.read(rally_conf)
if not rconfig.has_section('openstack'):
rconfig.add_section('openstack')
- rconfig.set('openstack', 'img_name_regex', '^{}$'.format(
- self.image.name))
- with open(rally_conf, 'w') as config_file:
+ rconfig.set('openstack', 'img_name_regex', f'^{self.image.name}$')
+ with open(rally_conf, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
def update_default_role(self, rally_conf='/etc/rally/rally.conf'):
@@ -481,7 +466,7 @@ class TempestCommon(singlevm.VmReady2):
if not rconfig.has_section('openstack'):
rconfig.add_section('openstack')
rconfig.set('openstack', 'swift_operator_role', role.name)
- with open(rally_conf, 'w') as config_file:
+ with open(rally_conf, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
@staticmethod
@@ -493,18 +478,51 @@ class TempestCommon(singlevm.VmReady2):
rconfig.remove_option('openstack', 'img_name_regex')
if rconfig.has_option('openstack', 'swift_operator_role'):
rconfig.remove_option('openstack', 'swift_operator_role')
- with open(rally_conf, 'w') as config_file:
+ with open(rally_conf, 'w', encoding='utf-8') as config_file:
+ rconfig.write(config_file)
+
+ def update_auth_section(self):
+ """Update auth section in tempest.conf"""
+ rconfig = configparser.RawConfigParser()
+ rconfig.read(self.conf_file)
+ if not rconfig.has_section("auth"):
+ rconfig.add_section("auth")
+ if env.get("NEW_USER_ROLE").lower() != "member":
+ tempest_roles = []
+ if rconfig.has_option("auth", "tempest_roles"):
+ tempest_roles = functest_utils.convert_ini_to_list(
+ rconfig.get("auth", "tempest_roles"))
+ rconfig.set(
+ 'auth', 'tempest_roles',
+ functest_utils.convert_list_to_ini(
+ [env.get("NEW_USER_ROLE")] + tempest_roles))
+ if not json.loads(env.get("USE_DYNAMIC_CREDENTIALS").lower()):
+ rconfig.set('auth', 'use_dynamic_credentials', False)
+ account_file = os.path.join(
+ getattr(config.CONF, 'dir_functest_data'), 'accounts.yaml')
+ assert os.path.exists(
+ account_file), f"{account_file} doesn't exist"
+ rconfig.set('auth', 'test_accounts_file', account_file)
+ if env.get('NO_TENANT_NETWORK').lower() == 'true':
+ rconfig.set('auth', 'create_isolated_networks', False)
+ with open(self.conf_file, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
def update_network_section(self):
"""Update network section in tempest.conf"""
rconfig = configparser.RawConfigParser()
rconfig.read(self.conf_file)
- if not rconfig.has_section('network'):
- rconfig.add_section('network')
- rconfig.set('network', 'public_network_id', self.ext_net.id)
- rconfig.set('network', 'floating_network_name', self.ext_net.name)
- with open(self.conf_file, 'w') as config_file:
+ if self.ext_net:
+ if not rconfig.has_section('network'):
+ rconfig.add_section('network')
+ rconfig.set('network', 'public_network_id', self.ext_net.id)
+ rconfig.set('network', 'floating_network_name', self.ext_net.name)
+ rconfig.set('network-feature-enabled', 'floating_ips', True)
+ else:
+ if not rconfig.has_section('network-feature-enabled'):
+ rconfig.add_section('network-feature-enabled')
+ rconfig.set('network-feature-enabled', 'floating_ips', False)
+ with open(self.conf_file, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
def update_compute_section(self):
@@ -513,8 +531,10 @@ class TempestCommon(singlevm.VmReady2):
rconfig.read(self.conf_file)
if not rconfig.has_section('compute'):
rconfig.add_section('compute')
- rconfig.set('compute', 'fixed_network_name', self.network.name)
- with open(self.conf_file, 'w') as config_file:
+ rconfig.set(
+ 'compute', 'fixed_network_name',
+ self.network.name if self.network else env.get("EXTERNAL_NETWORK"))
+ with open(self.conf_file, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
def update_validation_section(self):
@@ -523,8 +543,13 @@ class TempestCommon(singlevm.VmReady2):
rconfig.read(self.conf_file)
if not rconfig.has_section('validation'):
rconfig.add_section('validation')
- rconfig.set('validation', 'network_for_ssh', self.network.name)
- with open(self.conf_file, 'w') as config_file:
+ rconfig.set(
+ 'validation', 'connect_method',
+ 'floating' if self.ext_net else 'fixed')
+ rconfig.set(
+ 'validation', 'network_for_ssh',
+ self.network.name if self.network else env.get("EXTERNAL_NETWORK"))
+ with open(self.conf_file, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
def update_scenario_section(self):
@@ -532,13 +557,12 @@ class TempestCommon(singlevm.VmReady2):
rconfig = configparser.RawConfigParser()
rconfig.read(self.conf_file)
filename = getattr(
- config.CONF, '{}_image'.format(self.case_name), self.filename)
+ config.CONF, f'{self.case_name}_image', self.filename)
if not rconfig.has_section('scenario'):
rconfig.add_section('scenario')
- rconfig.set('scenario', 'img_file', os.path.basename(filename))
- rconfig.set('scenario', 'img_dir', os.path.dirname(filename))
+ rconfig.set('scenario', 'img_file', filename)
rconfig.set('scenario', 'img_disk_format', getattr(
- config.CONF, '{}_image_format'.format(self.case_name),
+ config.CONF, f'{self.case_name}_image_format',
self.image_format))
extra_properties = self.extra_properties.copy()
if env.get('IMAGE_PROPERTIES'):
@@ -546,12 +570,24 @@ class TempestCommon(singlevm.VmReady2):
functest_utils.convert_ini_to_dict(
env.get('IMAGE_PROPERTIES')))
extra_properties.update(
- getattr(config.CONF, '{}_extra_properties'.format(
- self.case_name), {}))
+ getattr(config.CONF, f'{self.case_name}_extra_properties', {}))
rconfig.set(
'scenario', 'img_properties',
functest_utils.convert_dict_to_ini(extra_properties))
- with open(self.conf_file, 'w') as config_file:
+ with open(self.conf_file, 'w', encoding='utf-8') as config_file:
+ rconfig.write(config_file)
+
+ def update_dashboard_section(self):
+ """Update dashboard section in tempest.conf"""
+ rconfig = configparser.RawConfigParser()
+ rconfig.read(self.conf_file)
+ if env.get('DASHBOARD_URL'):
+ if not rconfig.has_section('dashboard'):
+ rconfig.add_section('dashboard')
+ rconfig.set('dashboard', 'dashboard_url', env.get('DASHBOARD_URL'))
+ else:
+ rconfig.set('service_available', 'horizon', False)
+ with open(self.conf_file, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
def configure(self, **kwargs): # pylint: disable=unused-argument
@@ -591,16 +627,18 @@ class TempestCommon(singlevm.VmReady2):
flavor_alt_id=self.flavor_alt.id,
admin_role_name=self.role_name, cidr=self.cidr,
domain_id=self.project.domain.id)
+ self.update_auth_section()
self.update_network_section()
self.update_compute_section()
self.update_validation_section()
self.update_scenario_section()
+ self.update_dashboard_section()
self.backup_tempest_config(self.conf_file, self.res_dir)
def run(self, **kwargs):
self.start_time = time.time()
try:
- assert super(TempestCommon, self).run(
+ assert super().run(
**kwargs) == testcase.TestCase.EX_OK
if not os.path.exists(self.res_dir):
os.makedirs(self.res_dir)
@@ -640,7 +678,7 @@ class TempestCommon(singlevm.VmReady2):
self.cloud.delete_image(self.image_alt)
if self.flavor_alt:
self.orig_cloud.delete_flavor(self.flavor_alt.id)
- super(TempestCommon, self).clean()
+ super().clean()
def is_successful(self):
"""The overall result of the test."""
@@ -650,22 +688,7 @@ class TempestCommon(singlevm.VmReady2):
if self.tests_count and (
self.details.get("tests_number", 0) != self.tests_count):
return testcase.TestCase.EX_TESTCASE_FAILED
- return super(TempestCommon, self).is_successful()
-
-
-class TempestHorizon(TempestCommon):
- """Tempest Horizon testcase implementation class."""
-
- def configure(self, **kwargs):
- super(TempestHorizon, self).configure(**kwargs)
- rconfig = configparser.RawConfigParser()
- rconfig.read(self.conf_file)
- if not rconfig.has_section('dashboard'):
- rconfig.add_section('dashboard')
- rconfig.set('dashboard', 'dashboard_url', env.get('DASHBOARD_URL'))
- with open(self.conf_file, 'w') as config_file:
- rconfig.write(config_file)
- self.backup_tempest_config(self.conf_file, self.res_dir)
+ return super().is_successful()
class TempestHeat(TempestCommon):
@@ -678,11 +701,14 @@ class TempestHeat(TempestCommon):
flavor_alt_disk = 4
def __init__(self, **kwargs):
- super(TempestHeat, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.user2 = self.orig_cloud.create_user(
- name='{}-user2_{}'.format(self.case_name, self.project.guid),
+ name=f'{self.case_name}-user2_{self.project.guid}',
password=self.project.password,
domain_id=self.project.domain.id)
+ self.orig_cloud.grant_role(
+ self.role_name, user=self.user2.id,
+ project=self.project.project.id, domain=self.project.domain.id)
if not self.orig_cloud.get_role("heat_stack_owner"):
self.role = self.orig_cloud.create_role("heat_stack_owner")
self.orig_cloud.grant_role(
@@ -692,7 +718,7 @@ class TempestHeat(TempestCommon):
def configure(self, **kwargs):
assert self.user2
- super(TempestHeat, self).configure(**kwargs)
+ super().configure(**kwargs)
rconfig = configparser.RawConfigParser()
rconfig.read(self.conf_file)
if not rconfig.has_section('heat_plugin'):
@@ -719,11 +745,23 @@ class TempestHeat(TempestCommon):
rconfig.set('heat_plugin', 'instance_type', self.flavor_alt.id)
rconfig.set('heat_plugin', 'minimal_image_ref', self.image.id)
rconfig.set('heat_plugin', 'minimal_instance_type', self.flavor.id)
- rconfig.set('heat_plugin', 'floating_network_name', self.ext_net.name)
- rconfig.set('heat_plugin', 'fixed_network_name', self.network.name)
- rconfig.set('heat_plugin', 'fixed_subnet_name', self.subnet.name)
- rconfig.set('heat_plugin', 'network_for_ssh', self.network.name)
- with open(self.conf_file, 'w') as config_file:
+ if self.ext_net:
+ rconfig.set(
+ 'heat_plugin', 'floating_network_name', self.ext_net.name)
+ if self.network:
+ rconfig.set('heat_plugin', 'fixed_network_name', self.network.name)
+ rconfig.set('heat_plugin', 'fixed_subnet_name', self.subnet.name)
+ rconfig.set('heat_plugin', 'network_for_ssh', self.network.name)
+ else:
+ LOGGER.warning(
+ 'No tenant network created. '
+ 'Trying EXTERNAL_NETWORK as a fallback')
+ rconfig.set(
+ 'heat_plugin', 'fixed_network_name',
+ env.get("EXTERNAL_NETWORK"))
+ rconfig.set(
+ 'heat_plugin', 'network_for_ssh', env.get("EXTERNAL_NETWORK"))
+ with open(self.conf_file, 'w', encoding='utf-8') as config_file:
rconfig.write(config_file)
self.backup_tempest_config(self.conf_file, self.res_dir)
@@ -731,6 +769,6 @@ class TempestHeat(TempestCommon):
"""
Cleanup all OpenStack objects. Should be called on completion.
"""
- super(TempestHeat, self).clean()
+ super().clean()
if self.user2:
self.orig_cloud.delete_user(self.user2.id)
diff --git a/functest/opnfv_tests/openstack/vmtp/vmtp.py b/functest/opnfv_tests/openstack/vmtp/vmtp.py
index 1686489b8..9833cc72a 100644
--- a/functest/opnfv_tests/openstack/vmtp/vmtp.py
+++ b/functest/opnfv_tests/openstack/vmtp/vmtp.py
@@ -56,8 +56,8 @@ class Vmtp(singlevm.VmReady2):
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = 'vmtp'
- super(Vmtp, self).__init__(**kwargs)
- self.config = "{}/vmtp.conf".format(self.res_dir)
+ super().__init__(**kwargs)
+ self.config = f"{self.res_dir}/vmtp.conf"
(_, self.privkey_filename) = tempfile.mkstemp()
(_, self.pubkey_filename) = tempfile.mkstemp()
@@ -77,7 +77,7 @@ class Vmtp(singlevm.VmReady2):
assert self.cloud
assert self.ext_net
self.router = self.cloud.create_router(
- name='{}-router_{}'.format(self.case_name, self.guid),
+ name=f'{self.case_name}-router_{self.guid}',
ext_gateway_net_id=self.ext_net.id)
self.__logger.debug("router: %s", self.router)
@@ -87,13 +87,13 @@ class Vmtp(singlevm.VmReady2):
Raises: Exception on error
"""
assert self.cloud
- name = "vmtp_{}".format(self.guid)
+ name = f"vmtp_{self.guid}"
self.__logger.info("Creating keypair with name: '%s'", name)
keypair = self.cloud.create_keypair(name)
self.__logger.debug("keypair: %s", keypair)
- with open(self.privkey_filename, 'w') as key_file:
+ with open(self.privkey_filename, 'w', encoding='utf-8') as key_file:
key_file.write(keypair.private_key)
- with open(self.pubkey_filename, 'w') as key_file:
+ with open(self.pubkey_filename, 'w', encoding='utf-8') as key_file:
key_file.write(keypair.public_key)
self.cloud.delete_keypair(keypair.id)
@@ -108,7 +108,7 @@ class Vmtp(singlevm.VmReady2):
cmd = ['vmtp', '-sc']
output = subprocess.check_output(cmd).decode("utf-8")
self.__logger.info("%s\n%s", " ".join(cmd), output)
- with open(self.config, "w+") as conf:
+ with open(self.config, "w+", encoding='utf-8') as conf:
vmtp_conf = yaml.full_load(output)
vmtp_conf["private_key_file"] = self.privkey_filename
vmtp_conf["public_key_file"] = self.pubkey_filename
@@ -116,12 +116,11 @@ class Vmtp(singlevm.VmReady2):
vmtp_conf["router_name"] = str(self.router.name)
vmtp_conf["flavor_type"] = str(self.flavor.name)
vmtp_conf["internal_network_name"] = [
- "pns-internal-net_{}".format(self.guid),
- "pns-internal-net2_{}".format(self.guid)]
- vmtp_conf["vm_name_client"] = "TestClient_{}".format(self.guid)
- vmtp_conf["vm_name_server"] = "TestServer_{}".format(self.guid)
- vmtp_conf["security_group_name"] = "pns-security{}".format(
- self.guid)
+ f"pns-internal-net_{self.guid}",
+ f"pns-internal-net2_{self.guid}"]
+ vmtp_conf["vm_name_client"] = f"TestClient_{self.guid}"
+ vmtp_conf["vm_name_server"] = f"TestServer_{self.guid}"
+ vmtp_conf["security_group_name"] = f"pns-security{self.guid}"
vmtp_conf["dns_nameservers"] = [env.get('NAMESERVER')]
vmtp_conf["generic_retry_count"] = self.create_server_timeout // 2
vmtp_conf["ssh_retry_count"] = self.ssh_retry_timeout // 2
@@ -143,13 +142,13 @@ class Vmtp(singlevm.VmReady2):
OS_USER_DOMAIN_NAME=self.project.domain.name,
OS_PASSWORD=self.project.password)
if not new_env["OS_AUTH_URL"].endswith(('v3', 'v3/')):
- new_env["OS_AUTH_URL"] = "{}/v3".format(new_env["OS_AUTH_URL"])
+ new_env["OS_AUTH_URL"] = f'{new_env["OS_AUTH_URL"]}/v3'
try:
del new_env['OS_TENANT_NAME']
del new_env['OS_TENANT_ID']
except Exception: # pylint: disable=broad-except
pass
- cmd = ['vmtp', '-d', '--json', '{}/vmtp.json'.format(self.res_dir),
+ cmd = ['vmtp', '-d', '--json', f'{self.res_dir}/vmtp.json',
'-c', self.config]
if env.get("VMTP_HYPERVISORS"):
hypervisors = functest_utils.convert_ini_to_list(
@@ -160,12 +159,13 @@ class Vmtp(singlevm.VmReady2):
output = subprocess.check_output(
cmd, stderr=subprocess.STDOUT, env=new_env).decode("utf-8")
self.__logger.info("%s\n%s", " ".join(cmd), output)
- cmd = ['vmtp_genchart', '-c', '{}/vmtp.html'.format(self.res_dir),
- '{}/vmtp.json'.format(self.res_dir)]
+ cmd = ['vmtp_genchart', '-c', f'{self.res_dir}/vmtp.html',
+ f'{self.res_dir}/vmtp.json']
output = subprocess.check_output(
cmd, stderr=subprocess.STDOUT).decode("utf-8")
self.__logger.info("%s\n%s", " ".join(cmd), output)
- with open('{}/vmtp.json'.format(self.res_dir), 'r') as res_file:
+ with open(f'{self.res_dir}/vmtp.json', 'r',
+ encoding='utf-8') as res_file:
self.details = json.load(res_file)
def run(self, **kwargs):
@@ -173,7 +173,7 @@ class Vmtp(singlevm.VmReady2):
status = testcase.TestCase.EX_RUN_ERROR
try:
assert self.cloud
- assert super(Vmtp, self).run(**kwargs) == self.EX_OK
+ assert super().run(**kwargs) == self.EX_OK
status = testcase.TestCase.EX_RUN_ERROR
if self.orig_cloud.get_role("admin"):
role_name = "admin"
@@ -204,10 +204,10 @@ class Vmtp(singlevm.VmReady2):
def clean(self):
try:
assert self.cloud
- super(Vmtp, self).clean()
+ super().clean()
os.remove(self.privkey_filename)
os.remove(self.pubkey_filename)
- self.cloud.delete_network("pns-internal-net_{}".format(self.guid))
- self.cloud.delete_network("pns-internal-net2_{}".format(self.guid))
+ self.cloud.delete_network(f"pns-internal-net_{self.guid}")
+ self.cloud.delete_network(f"pns-internal-net2_{self.guid}")
except Exception: # pylint: disable=broad-except
pass
diff --git a/functest/opnfv_tests/openstack/vping/vping_ssh.py b/functest/opnfv_tests/openstack/vping/vping_ssh.py
index a7bbfc23c..ad64348c4 100644
--- a/functest/opnfv_tests/openstack/vping/vping_ssh.py
+++ b/functest/opnfv_tests/openstack/vping/vping_ssh.py
@@ -29,13 +29,13 @@ class VPingSSH(singlevm.SingleVm2):
"""Initialize testcase."""
if "case_name" not in kwargs:
kwargs["case_name"] = "vping_ssh"
- super(VPingSSH, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.vm2 = None
def prepare(self):
- super(VPingSSH, self).prepare()
+ super().prepare()
self.vm2 = self.boot_vm(
- '{}-vm2_{}'.format(self.case_name, self.guid),
+ f'{self.case_name}-vm2_{self.guid}',
security_groups=[self.sec.id])
def execute(self):
@@ -46,10 +46,9 @@ class VPingSSH(singlevm.SingleVm2):
assert self.ssh
if not self.check_regex_in_console(self.vm2.name):
return 1
- (_, stdout, stderr) = self.ssh.exec_command(
- 'ping -c 1 {}'.format(
- self.vm2.private_v4 or self.vm2.addresses[
- self.network.name][0].addr))
+ ip4 = self.vm2.private_v4 or self.vm2.addresses[
+ self.network.name][0].addr
+ (_, stdout, stderr) = self.ssh.exec_command(f'ping -c 1 {ip4}')
self.__logger.info("output:\n%s", stdout.read().decode("utf-8"))
self.__logger.info("error:\n%s", stderr.read().decode("utf-8"))
return stdout.channel.recv_exit_status()
@@ -60,4 +59,4 @@ class VPingSSH(singlevm.SingleVm2):
self.cloud.delete_server(
self.vm2, wait=True,
timeout=getattr(config.CONF, 'vping_vm_delete_timeout'))
- super(VPingSSH, self).clean()
+ super().clean()
diff --git a/functest/opnfv_tests/openstack/vping/vping_userdata.py b/functest/opnfv_tests/openstack/vping/vping_userdata.py
index 9010895cb..8a8f26f37 100644
--- a/functest/opnfv_tests/openstack/vping/vping_userdata.py
+++ b/functest/opnfv_tests/openstack/vping/vping_userdata.py
@@ -26,7 +26,7 @@ class VPingUserdata(singlevm.VmReady2):
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = "vping_userdata"
- super(VPingUserdata, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.logger = logging.getLogger(__name__)
self.vm1 = None
self.vm2 = None
@@ -39,12 +39,12 @@ class VPingUserdata(singlevm.VmReady2):
"""
try:
assert self.cloud
- assert super(VPingUserdata, self).run(
+ assert super().run(
**kwargs) == testcase.TestCase.EX_OK
self.result = 0
self.vm1 = self.boot_vm()
self.vm2 = self.boot_vm(
- '{}-vm2_{}'.format(self.case_name, self.guid),
+ f'{self.case_name}-vm2_{self.guid}',
userdata=self._get_userdata())
result = self._do_vping()
@@ -104,13 +104,15 @@ class VPingUserdata(singlevm.VmReady2):
"""
Returns the post VM creation script to be added into the VM's userdata
:param test_ip: the IP value to substitute into the script
- :return: the bash script contents
+ :return: the shell script contents
"""
+ ip4 = self.vm1.private_v4 or self.vm1.addresses[
+ self.network.name][0].addr
if self.vm1.private_v4 or self.vm1.addresses[
self.network.name][0].addr:
return ("#!/bin/sh\n\n"
"while true; do\n"
- " ping -c 1 %s 2>&1 >/dev/null\n"
+ f" ping -c 1 {ip4} 2>&1 >/dev/null\n"
" RES=$?\n"
" if [ \"Z$RES\" = \"Z0\" ] ; then\n"
" echo 'vPing OK'\n"
@@ -119,9 +121,7 @@ class VPingUserdata(singlevm.VmReady2):
" echo 'vPing KO'\n"
" fi\n"
" sleep 1\n"
- "done\n" % str(
- self.vm1.private_v4 or self.vm1.addresses[
- self.network.name][0].addr))
+ "done\n")
return None
def clean(self):
@@ -134,4 +134,4 @@ class VPingUserdata(singlevm.VmReady2):
self.cloud.delete_server(
self.vm2, wait=True,
timeout=getattr(config.CONF, 'vping_vm_delete_timeout'))
- super(VPingUserdata, self).clean()
+ super().clean()
diff --git a/functest/opnfv_tests/sdn/odl/odl.py b/functest/opnfv_tests/sdn/odl/odl.py
index b54f0f54b..72c38ce2c 100644
--- a/functest/opnfv_tests/sdn/odl/odl.py
+++ b/functest/opnfv_tests/sdn/odl/odl.py
@@ -49,7 +49,7 @@ class ODLTests(robotframework.RobotFramework):
__logger = logging.getLogger(__name__)
def __init__(self, **kwargs):
- super(ODLTests, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.res_dir = os.path.join(
getattr(config.CONF, 'dir_results'), 'odl')
self.xml_file = os.path.join(self.res_dir, 'output.xml')
@@ -66,10 +66,10 @@ class ODLTests(robotframework.RobotFramework):
try:
for line in fileinput.input(cls.odl_variables_file,
inplace=True):
- print(re.sub("@{AUTH}.*",
- "@{{AUTH}} {} {}".format(
- odlusername, odlpassword),
- line.rstrip()))
+ print(re.sub(
+ "@{AUTH}.*",
+ f"@{{AUTH}} {odlusername} {odlpassword}",
+ line.rstrip()))
return True
except Exception: # pylint: disable=broad-except
cls.__logger.exception("Cannot set ODL creds:")
@@ -111,9 +111,8 @@ class ODLTests(robotframework.RobotFramework):
odlusername = kwargs['odlusername']
odlpassword = kwargs['odlpassword']
osauthurl = kwargs['osauthurl']
- keystoneurl = "{}://{}".format(
- urllib.parse.urlparse(osauthurl).scheme,
- urllib.parse.urlparse(osauthurl).netloc)
+ keystoneurl = (f"{urllib.parse.urlparse(osauthurl).scheme}://"
+ f"{urllib.parse.urlparse(osauthurl).netloc}")
variable = ['KEYSTONEURL:' + keystoneurl,
'NEUTRONURL:' + kwargs['neutronurl'],
'OS_AUTH_URL:"' + osauthurl + '"',
@@ -135,7 +134,7 @@ class ODLTests(robotframework.RobotFramework):
else:
if not self.set_robotframework_vars(odlusername, odlpassword):
return self.EX_RUN_ERROR
- return super(ODLTests, self).run(variable=variable, suites=suites)
+ return super().run(variable=variable, suites=suites)
def run(self, **kwargs):
"""Run suites in OPNFV environment
diff --git a/functest/opnfv_tests/vnf/epc/juju_epc.py b/functest/opnfv_tests/vnf/epc/juju_epc.py
index 5049bd0bb..1cf240b80 100644
--- a/functest/opnfv_tests/vnf/epc/juju_epc.py
+++ b/functest/opnfv_tests/vnf/epc/juju_epc.py
@@ -83,16 +83,16 @@ class JujuEpc(singlevm.SingleVm2):
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = "juju_epc"
- super(JujuEpc, self).__init__(**kwargs)
+ super().__init__(**kwargs)
# Retrieve the configuration
self.case_dir = pkg_resources.resource_filename(
'functest', 'opnfv_tests/vnf/epc')
try:
self.config = getattr(
- config.CONF, 'vnf_{}_config'.format(self.case_name))
- except Exception:
- raise Exception("VNF config file not found")
+ config.CONF, f'vnf_{self.case_name}_config')
+ except Exception as exc:
+ raise Exception("VNF config file not found") from exc
self.config_file = os.path.join(self.case_dir, self.config)
self.orchestrator = dict(
requirements=functest_utils.get_parameter_from_yaml(
@@ -138,7 +138,7 @@ class JujuEpc(singlevm.SingleVm2):
try:
self.public_auth_url = self.get_public_auth_url(self.orig_cloud)
if not self.public_auth_url.endswith(('v3', 'v3/')):
- self.public_auth_url = "{}/v3".format(self.public_auth_url)
+ self.public_auth_url = f"{self.public_auth_url}/v3"
except Exception: # pylint: disable=broad-except
self.public_auth_url = None
self.sec = None
@@ -168,7 +168,7 @@ class JujuEpc(singlevm.SingleVm2):
'url': self.public_auth_url,
'region': self.cloud.region_name if self.cloud.region_name else (
'RegionOne')}
- with open(clouds_yaml, 'w') as yfile:
+ with open(clouds_yaml, 'w', encoding='utf-8') as yfile:
yfile.write(CLOUD_TEMPLATE.format(**cloud_data))
scpc = scp.SCPClient(self.ssh.get_transport())
scpc.put(clouds_yaml, remote_path='~/')
@@ -189,7 +189,7 @@ class JujuEpc(singlevm.SingleVm2):
"project_domain_name", "Default"),
'user_domain_n': self.cloud.auth.get(
"user_domain_name", "Default")}
- with open(credentials_yaml, 'w') as yfile:
+ with open(credentials_yaml, 'w', encoding='utf-8') as yfile:
yfile.write(CREDS_TEMPLATE.format(**creds_data))
scpc = scp.SCPClient(self.ssh.get_transport())
scpc.put(credentials_yaml, remote_path='~/')
@@ -205,20 +205,20 @@ class JujuEpc(singlevm.SingleVm2):
'RegionOne')
(_, stdout, stderr) = self.ssh.exec_command(
'/snap/bin/juju metadata generate-image -d /home/ubuntu '
- '-i {} -s xenial -r {} -u {}'.format(
- self.image.id, region_name, self.public_auth_url))
+ f'-i {self.image.id} -s xenial -r {region_name} '
+ f'-u {self.public_auth_url}')
self.__logger.debug("stdout:\n%s", stdout.read().decode("utf-8"))
self.__logger.debug("stderr:\n%s", stderr.read().decode("utf-8"))
return not stdout.channel.recv_exit_status()
def publish_image_alt(self, name=None):
- image_alt = super(JujuEpc, self).publish_image_alt(name)
+ image_alt = super().publish_image_alt(name)
region_name = self.cloud.region_name if self.cloud.region_name else (
'RegionOne')
(_, stdout, stderr) = self.ssh.exec_command(
'/snap/bin/juju metadata generate-image -d /home/ubuntu '
- '-i {} -s trusty -r {} -u {}'.format(
- image_alt.id, region_name, self.public_auth_url))
+ f'-i {image_alt.id} -s trusty -r {region_name} '
+ f'-u {self.public_auth_url}')
self.__logger.debug("stdout:\n%s", stdout.read().decode("utf-8"))
self.__logger.debug("stderr:\n%s", stderr.read().decode("utf-8"))
return image_alt
@@ -236,18 +236,16 @@ class JujuEpc(singlevm.SingleVm2):
region_name = self.cloud.region_name if self.cloud.region_name else (
'RegionOne')
(_, stdout, stderr) = self.ssh.exec_command(
- 'timeout {} '
- '/snap/bin/juju bootstrap abot-epc/{} abot-controller '
+ f'timeout {JujuEpc.juju_timeout} '
+ f'/snap/bin/juju bootstrap abot-epc/{region_name} abot-controller '
'--agent-version 2.3.9 --metadata-source /home/ubuntu '
'--constraints mem=2G --bootstrap-series xenial '
- '--config network={} '
+ f'--config network={self.network.id} '
'--config ssl-hostname-verification=false '
- '--config external-network={} '
+ f'--config external-network={self.ext_net.id} '
'--config use-floating-ip=true '
'--config use-default-secgroup=true '
- '--debug'.format(
- JujuEpc.juju_timeout, region_name, self.network.id,
- self.ext_net.id))
+ '--debug')
self.__logger.debug("stdout:\n%s", stdout.read().decode("utf-8"))
self.__logger.debug("stderr:\n%s", stderr.read().decode("utf-8"))
return not stdout.channel.recv_exit_status()
@@ -256,14 +254,14 @@ class JujuEpc(singlevm.SingleVm2):
"""Check application status."""
for i in range(10):
(_, stdout, stderr) = self.ssh.exec_command(
- '/snap/bin/juju status --format short {}'.format(name))
+ f'/snap/bin/juju status --format short {name}')
output = stdout.read().decode("utf-8")
self.__logger.debug("stdout:\n%s", output)
self.__logger.debug("stderr:\n%s", stderr.read().decode("utf-8"))
if stdout.channel.recv_exit_status():
continue
ret = re.search(
- r'(?=workload:({})\))'.format(status), output)
+ rf'(?=workload:({status})\))', output)
if ret:
self.__logger.info("%s workload is %s", name, status)
break
@@ -295,7 +293,7 @@ class JujuEpc(singlevm.SingleVm2):
return not stdout.channel.recv_exit_status()
(_, stdout, stderr) = self.ssh.exec_command(
'PATH=/snap/bin/:$PATH '
- 'timeout {} juju-wait'.format(JujuEpc.juju_timeout))
+ f'timeout {JujuEpc.juju_timeout} juju-wait')
self.__logger.debug("stdout:\n%s", stdout.read().decode("utf-8"))
self.__logger.debug("stderr:\n%s", stderr.read().decode("utf-8"))
if stdout.channel.recv_exit_status():
@@ -312,12 +310,11 @@ class JujuEpc(singlevm.SingleVm2):
return False
scpc = scp.SCPClient(self.ssh.get_transport())
scpc.put(
- '{}/featureFiles'.format(self.case_dir), remote_path='~/',
+ f'{self.case_dir}/featureFiles', remote_path='~/',
recursive=True)
(_, stdout, stderr) = self.ssh.exec_command(
- 'timeout {} /snap/bin/juju scp -- -r -v ~/featureFiles '
- 'abot-epc-basic/0:/etc/rebaca-test-suite/'.format(
- JujuEpc.juju_timeout))
+ f'timeout {JujuEpc.juju_timeout} /snap/bin/juju scp -- -r -v '
+ '~/featureFiles abot-epc-basic/0:/etc/rebaca-test-suite/')
output = stdout.read().decode("utf-8")
self.__logger.debug("stdout:\n%s", output)
self.__logger.debug("stderr:\n%s", stderr.read().decode("utf-8"))
@@ -327,15 +324,15 @@ class JujuEpc(singlevm.SingleVm2):
"""Run test on ABoT."""
start_time = time.time()
(_, stdout, stderr) = self.ssh.exec_command(
- '/snap/bin/juju run-action abot-epc-basic/0 '
- 'run tagnames={}'.format(self.details['test_vnf']['tag_name']))
+ "/snap/bin/juju run-action abot-epc-basic/0 "
+ f"run tagnames={self.details['test_vnf']['tag_name']}")
self.__logger.debug("stdout:\n%s", stdout.read().decode("utf-8"))
self.__logger.debug("stderr:\n%s", stderr.read().decode("utf-8"))
if stdout.channel.recv_exit_status():
return not stdout.channel.recv_exit_status()
(_, stdout, stderr) = self.ssh.exec_command(
'PATH=/snap/bin/:$PATH '
- 'timeout {} juju-wait'.format(JujuEpc.juju_timeout))
+ f'timeout {JujuEpc.juju_timeout} juju-wait')
self.__logger.debug("stdout:\n%s", stdout.read().decode("utf-8"))
self.__logger.debug("stderr:\n%s", stderr.read().decode("utf-8"))
if stdout.channel.recv_exit_status():
@@ -343,9 +340,9 @@ class JujuEpc(singlevm.SingleVm2):
duration = time.time() - start_time
self.__logger.info("Getting results from Abot node....")
(_, stdout, stderr) = self.ssh.exec_command(
- 'timeout {} /snap/bin/juju scp -- -v abot-epc-basic/0:'
- '/var/lib/abot-epc-basic/artifacts/TestResults.json .'.format(
- JujuEpc.juju_timeout))
+ f'timeout {JujuEpc.juju_timeout} /snap/bin/juju scp '
+ '-- -v abot-epc-basic/0:'
+ '/var/lib/abot-epc-basic/artifacts/TestResults.json .')
self.__logger.debug("stdout:\n%s", stdout.read().decode("utf-8"))
self.__logger.debug("stderr:\n%s", stderr.read().decode("utf-8"))
if stdout.channel.recv_exit_status():
@@ -353,8 +350,7 @@ class JujuEpc(singlevm.SingleVm2):
scpc = scp.SCPClient(self.ssh.get_transport())
scpc.get('TestResults.json', self.res_dir)
self.__logger.info("Parsing the Test results...")
- res = (process_abot_test_result('{}/TestResults.json'.format(
- self.res_dir)))
+ res = process_abot_test_result(f'{self.res_dir}/TestResults.json')
short_result = sig_test_format(res)
self.__logger.info(short_result)
self.details['test_vnf'].update(
@@ -375,7 +371,7 @@ class JujuEpc(singlevm.SingleVm2):
except OSError as ex:
if ex.errno != errno.EEXIST:
self.__logger.exception("Cannot create %s", self.res_dir)
- raise Exception
+ raise Exception from ex
self.__logger.info("ENV:\n%s", env.string())
try:
assert self._install_juju()
@@ -407,7 +403,7 @@ class JujuEpc(singlevm.SingleVm2):
self.cloud.delete_image(self.image_alt)
if self.flavor_alt:
self.orig_cloud.delete_flavor(self.flavor_alt.id)
- super(JujuEpc, self).clean()
+ super().clean()
def sig_test_format(sig_test):
@@ -433,7 +429,7 @@ def sig_test_format(sig_test):
def process_abot_test_result(file_path):
""" Process ABoT Result """
- with open(file_path) as test_result:
+ with open(file_path, encoding='utf-8') as test_result:
data = json.load(test_result)
res = []
for tests in data:
diff --git a/functest/opnfv_tests/vnf/ims/clearwater.py b/functest/opnfv_tests/vnf/ims/clearwater.py
index 67128b11c..4c143fd70 100644
--- a/functest/opnfv_tests/vnf/ims/clearwater.py
+++ b/functest/opnfv_tests/vnf/ims/clearwater.py
@@ -50,7 +50,7 @@ class ClearwaterTesting():
output_dict = {}
self.logger.debug('Ellis IP: %s', self.ellis_ip)
output_dict['ellis_ip'] = self.ellis_ip
- account_url = 'http://{0}/accounts'.format(self.ellis_ip)
+ account_url = f'http://{self.ellis_ip}/accounts'
params = {"password": "functest",
"full_name": "opnfv functest user",
"email": "functest@opnfv.org",
@@ -60,7 +60,7 @@ class ClearwaterTesting():
number_res = self._create_ellis_account(account_url, params)
output_dict['number'] = number_res
- session_url = 'http://{0}/session'.format(self.ellis_ip)
+ session_url = f'http://{self.ellis_ip}/session'
session_data = {
'username': params['email'],
'password': params['password'],
@@ -68,8 +68,8 @@ class ClearwaterTesting():
}
cookies = self._get_ellis_session_cookies(session_url, session_data)
- number_url = 'http://{0}/accounts/{1}/numbers'.format(
- self.ellis_ip, params['email'])
+ number_url = (
+ f"http://{self.ellis_ip}/accounts/{params['email']}/numbers")
self.logger.debug('Create 1st calling number on Ellis')
number_res = self._create_ellis_number(number_url, cookies)
@@ -97,8 +97,7 @@ class ClearwaterTesting():
"try %s: cannot create ellis account", iloop + 1)
time.sleep(30)
raise Exception(
- "Unable to create an account {}".format(
- params.get('full_name')))
+ f"Unable to create an account {params.get('full_name')}")
def _get_ellis_session_cookies(self, session_url, params):
i = 15
@@ -150,24 +149,20 @@ class ClearwaterTesting():
"""
# pylint: disable=too-many-locals,too-many-arguments
self.logger.info('Run Clearwater live test')
- script = ('cd {0};'
- 'rake test[{1}] SIGNUP_CODE={2}'
- .format(self.test_dir,
- public_domain,
- signup_code))
+ script = (f'cd {self.test_dir};'
+ f'rake test[{public_domain}] SIGNUP_CODE={signup_code}')
if self.bono_ip and self.ellis_ip:
- subscript = ' PROXY={0} ELLIS={1}'.format(
- self.bono_ip, self.ellis_ip)
- script = '{0}{1}'.format(script, subscript)
- script = ('{0}{1}'.format(script, ' --trace'))
- cmd = "/bin/bash -c '{0}'".format(script)
+ subscript = f' PROXY={self.bono_ip} ELLIS={self.ellis_ip}'
+ script = f'{script}{subscript}'
+ script = f'{script} --trace'
+ cmd = f"/bin/sh -c '{script}'"
self.logger.debug('Live test cmd: %s', cmd)
output_file = os.path.join(self.result_dir, "ims_test_output.txt")
ft_utils.execute_command(cmd,
error_msg='Clearwater live test failed',
output_file=output_file)
- with open(output_file, 'r') as ofile:
+ with open(output_file, 'r', encoding='utf-8') as ofile:
result = ofile.read()
if result != "":
diff --git a/functest/opnfv_tests/vnf/ims/cloudify_ims.py b/functest/opnfv_tests/vnf/ims/cloudify_ims.py
index d937cc052..b93af7d6d 100644
--- a/functest/opnfv_tests/vnf/ims/cloudify_ims.py
+++ b/functest/opnfv_tests/vnf/ims/cloudify_ims.py
@@ -53,14 +53,14 @@ class CloudifyIms(cloudify.Cloudify):
"""Initialize CloudifyIms testcase object."""
if "case_name" not in kwargs:
kwargs["case_name"] = "cloudify_ims"
- super(CloudifyIms, self).__init__(**kwargs)
+ super().__init__(**kwargs)
# Retrieve the configuration
try:
self.config = getattr(
- config.CONF, 'vnf_{}_config'.format(self.case_name))
- except Exception:
- raise Exception("VNF config file not found")
+ config.CONF, f'vnf_{self.case_name}_config')
+ except Exception as exc:
+ raise Exception("VNF config file not found") from exc
self.case_dir = pkg_resources.resource_filename(
'functest', 'opnfv_tests/vnf/ims')
@@ -114,7 +114,7 @@ class CloudifyIms(cloudify.Cloudify):
network, security group, fip, VM creation
"""
- assert super(CloudifyIms, self).execute() == 0
+ assert super().execute() == 0
start_time = time.time()
self.orig_cloud.set_network_quotas(
self.project.project.name,
@@ -259,4 +259,4 @@ class CloudifyIms(cloudify.Cloudify):
self.cloud.delete_image(self.image_alt)
if self.flavor_alt:
self.orig_cloud.delete_flavor(self.flavor_alt.id)
- super(CloudifyIms, self).clean()
+ super().clean()
diff --git a/functest/opnfv_tests/vnf/ims/heat_ims.py b/functest/opnfv_tests/vnf/ims/heat_ims.py
index 4edb2ddd9..0d4e345a0 100644
--- a/functest/opnfv_tests/vnf/ims/heat_ims.py
+++ b/functest/opnfv_tests/vnf/ims/heat_ims.py
@@ -57,14 +57,14 @@ class HeatIms(singlevm.VmReady2):
"""Initialize HeatIms testcase object."""
if "case_name" not in kwargs:
kwargs["case_name"] = "heat_ims"
- super(HeatIms, self).__init__(**kwargs)
+ super().__init__(**kwargs)
# Retrieve the configuration
try:
self.config = getattr(
- config.CONF, 'vnf_{}_config'.format(self.case_name))
- except Exception:
- raise Exception("VNF config file not found")
+ config.CONF, f'vnf_{self.case_name}_config')
+ except Exception as exc:
+ raise Exception("VNF config file not found") from exc
self.case_dir = pkg_resources.resource_filename(
'functest', 'opnfv_tests/vnf/ims')
@@ -112,9 +112,10 @@ class HeatIms(singlevm.VmReady2):
project=self.project.project.id,
domain=self.project.domain.id)
self.keypair = self.cloud.create_keypair(
- '{}-kp_{}'.format(self.case_name, self.guid))
+ f'{self.case_name}-kp_{self.guid}')
self.__logger.info("keypair:\n%s", self.keypair.private_key)
- with open(self.key_filename, 'w') as private_key_file:
+ with open(
+ self.key_filename, 'w', encoding='utf-8') as private_key_file:
private_key_file.write(self.keypair.private_key)
if self.deploy_vnf() and self.test_vnf():
@@ -137,7 +138,7 @@ class HeatIms(singlevm.VmReady2):
status = testcase.TestCase.EX_RUN_ERROR
try:
assert self.cloud
- assert super(HeatIms, self).run(
+ assert super().run(
**kwargs) == testcase.TestCase.EX_OK
self.result = 0
if not self.execute():
@@ -247,6 +248,6 @@ class HeatIms(singlevm.VmReady2):
pass
except Exception: # pylint: disable=broad-except
self.__logger.exception("Cannot clean stack ressources")
- super(HeatIms, self).clean()
+ super().clean()
if self.role:
self.orig_cloud.delete_role(self.role.id)
diff --git a/functest/opnfv_tests/vnf/router/cloudify_vrouter.py b/functest/opnfv_tests/vnf/router/cloudify_vrouter.py
index 82f57ca7b..32d675347 100644
--- a/functest/opnfv_tests/vnf/router/cloudify_vrouter.py
+++ b/functest/opnfv_tests/vnf/router/cloudify_vrouter.py
@@ -51,14 +51,14 @@ class CloudifyVrouter(cloudify.Cloudify):
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = "vyos_vrouter"
- super(CloudifyVrouter, self).__init__(**kwargs)
+ super().__init__(**kwargs)
# Retrieve the configuration
try:
self.config = getattr(
- config.CONF, 'vnf_{}_config'.format(self.case_name))
- except Exception:
- raise Exception("VNF config file not found")
+ config.CONF, f'vnf_{self.case_name}_config')
+ except Exception as exc:
+ raise Exception("VNF config file not found") from exc
self.case_dir = pkg_resources.resource_filename(
'functest', 'opnfv_tests/vnf/router')
@@ -127,7 +127,7 @@ class CloudifyVrouter(cloudify.Cloudify):
network, security group, fip, VM creation
"""
# network creation
- super(CloudifyVrouter, self).execute()
+ super().execute()
start_time = time.time()
self.put_private_key()
self.upload_cfy_plugins(self.cop_yaml, self.cop_wgn)
@@ -231,4 +231,4 @@ class CloudifyVrouter(cloudify.Cloudify):
self.cloud.delete_image(self.image_alt)
if self.flavor_alt:
self.orig_cloud.delete_flavor(self.flavor_alt.id)
- super(CloudifyVrouter, self).clean()
+ super().clean()
diff --git a/functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py b/functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py
index 0a56913b7..9eb3c5d69 100644
--- a/functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py
+++ b/functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py
@@ -32,17 +32,16 @@ class FunctionTestExec():
credentials = util_info["credentials"]
self.vnf_ctrl = VnfController(util_info)
- test_cmd_map_file = open(
- os.path.join(
- self.util.vnf_data_dir, self.util.command_template_dir,
- self.util.test_cmd_map_yaml_file),
- 'r')
- self.test_cmd_map_yaml = yaml.safe_load(test_cmd_map_file)
- test_cmd_map_file.close()
+ with open(
+ os.path.join(
+ self.util.vnf_data_dir, self.util.command_template_dir,
+ self.util.test_cmd_map_yaml_file),
+ 'r', encoding='utf-8') as test_cmd_map_file:
+ self.test_cmd_map_yaml = yaml.safe_load(test_cmd_map_file)
self.util.set_credentials(credentials["cloud"])
- with open(self.util.test_env_config_yaml) as file_fd:
+ with open(self.util.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
diff --git a/functest/opnfv_tests/vnf/router/utilvnf.py b/functest/opnfv_tests/vnf/router/utilvnf.py
index 2db3b38e5..111f20c1a 100644
--- a/functest/opnfv_tests/vnf/router/utilvnf.py
+++ b/functest/opnfv_tests/vnf/router/utilvnf.py
@@ -64,7 +64,7 @@ class Utilvnf(): # pylint: disable=too-many-instance-attributes
if not os.path.exists(self.vnf_data_dir):
os.makedirs(self.vnf_data_dir)
- with open(self.test_env_config_yaml) as file_fd:
+ with open(self.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
@@ -98,9 +98,7 @@ class Utilvnf(): # pylint: disable=too-many-instance-attributes
return mac_address
def get_blueprint_outputs(self, cfy_manager_ip, deployment_name):
- url = "http://%s/deployments/%s/outputs" % (
- cfy_manager_ip, deployment_name)
-
+ url = f"http://{cfy_manager_ip}/deployments/{deployment_name}/outputs"
response = requests.get(
url,
auth=requests.auth.HTTPBasicAuth('admin', 'admin'),
@@ -212,24 +210,29 @@ class Utilvnf(): # pylint: disable=too-many-instance-attributes
def write_result_data(self, result_data):
test_result = []
if not os.path.isfile(self.test_result_json_file):
- file_fd = open(self.test_result_json_file, "w")
- file_fd.close()
+ with open(
+ self.test_result_json_file, "w",
+ encoding="utf-8") as file_fd:
+ pass
else:
- file_fd = open(self.test_result_json_file, "r")
- test_result = json.load(file_fd)
- file_fd.close()
+ with open(
+ self.test_result_json_file, "r",
+ encoding="utf-8") as file_fd:
+ test_result = json.load(file_fd)
test_result.append(result_data)
- file_fd = open(self.test_result_json_file, "w")
- json.dump(test_result, file_fd)
- file_fd.close()
+ with open(
+ self.test_result_json_file, "w",
+ encoding="utf-8") as file_fd:
+ json.dump(test_result, file_fd)
def output_test_result_json(self):
if os.path.isfile(self.test_result_json_file):
- file_fd = open(self.test_result_json_file, "r")
- test_result = json.load(file_fd)
- file_fd.close()
+ with open(
+ self.test_result_json_file, "r",
+ encoding="utf-8") as file_fd:
+ test_result = json.load(file_fd)
output_json_data = json.dumps(test_result,
sort_keys=True,
indent=4)
@@ -239,8 +242,6 @@ class Utilvnf(): # pylint: disable=too-many-instance-attributes
@staticmethod
def get_test_scenario(file_path):
- test_scenario_file = open(file_path,
- 'r')
- test_scenario_yaml = yaml.safe_load(test_scenario_file)
- test_scenario_file.close()
+ with open(file_path, "r", encoding="utf-8") as test_scenario_file:
+ test_scenario_yaml = yaml.safe_load(test_scenario_file)
return test_scenario_yaml["test_scenario_list"]
diff --git a/functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py b/functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py
index 0969eab3b..269f6526b 100644
--- a/functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py
+++ b/functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py
@@ -43,7 +43,7 @@ class SshClient(): # pylint: disable=too-many-instance-attributes
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.util = Utilvnf()
- with open(self.util.test_env_config_yaml) as file_fd:
+ with open(self.util.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
diff --git a/functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py b/functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py
index b159ddda4..2210b3909 100644
--- a/functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py
+++ b/functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py
@@ -36,7 +36,7 @@ class VmController():
self.util = Utilvnf()
self.util.set_credentials(credentials["cloud"])
- with open(self.util.test_env_config_yaml) as file_fd:
+ with open(self.util.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
@@ -101,10 +101,8 @@ class VmController():
def command_create_and_execute(self, ssh, test_cmd_file_path,
cmd_input_param, prompt_file_path):
- prompt_file = open(prompt_file_path,
- 'r')
- prompt = yaml.safe_load(prompt_file)
- prompt_file.close()
+ with open(prompt_file_path, 'r', encoding='utf-8') as prompt_file:
+ prompt = yaml.safe_load(prompt_file)
config_mode_prompt = prompt["config_mode"]
commands = self.command_gen_from_template(test_cmd_file_path,
diff --git a/functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py b/functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py
index 7ed287c6e..46584456f 100644
--- a/functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py
+++ b/functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py
@@ -36,7 +36,7 @@ class VnfController():
self.util = Utilvnf()
self.vm_controller = VmController(util_info)
- with open(self.util.test_env_config_yaml) as file_fd:
+ with open(self.util.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
@@ -49,10 +49,9 @@ class VnfController():
def config_vnf(self, source_vnf, destination_vnf, test_cmd_file_path,
parameter_file_path, prompt_file_path):
# pylint: disable=too-many-arguments
- parameter_file = open(parameter_file_path,
- 'r')
- cmd_input_param = yaml.safe_load(parameter_file)
- parameter_file.close()
+ with open(
+ parameter_file_path, 'r', encoding='utf-8') as parameter_file:
+ cmd_input_param = yaml.safe_load(parameter_file)
cmd_input_param["macaddress"] = source_vnf["data_plane_network_mac"]
cmd_input_param["source_ip"] = source_vnf["data_plane_network_ip"]
@@ -71,19 +70,16 @@ class VnfController():
res_dict_data_list = []
- parameter_file = open(parameter_file_path,
- 'r')
- cmd_input_param = yaml.safe_load(parameter_file)
- parameter_file.close()
+ with open(
+ parameter_file_path, 'r', encoding='utf-8') as parameter_file:
+ cmd_input_param = yaml.safe_load(parameter_file)
cmd_input_param["source_ip"] = target_vnf["data_plane_network_ip"]
cmd_input_param["destination_ip"] = reference_vnf[
"data_plane_network_ip"]
- prompt_file = open(prompt_file_path,
- 'r')
- prompt = yaml.safe_load(prompt_file)
- prompt_file.close()
+ with open(prompt_file_path, 'r', encoding='utf-8') as prompt_file:
+ prompt = yaml.safe_load(prompt_file)
terminal_mode_prompt = prompt["terminal_mode"]
ssh = SshClient(target_vnf["floating_ip"],