From 4fdbdd34fb5fea55571a18b2438ececa953928ff Mon Sep 17 00:00:00 2001 From: Cédric Ollivier Date: Wed, 10 Nov 2021 15:42:57 +0100 Subject: Update linters and fix all new issues MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It mostly add encoding in open calls and leverage f-strings. Change-Id: Ifead18fc724a452c1067dcf91dc577032edc9c59 Signed-off-by: Cédric Ollivier --- .../opnfv_tests/openstack/barbican/barbican.py | 2 +- .../opnfv_tests/openstack/cinder/cinder_test.py | 8 +-- functest/opnfv_tests/openstack/patrole/patrole.py | 2 +- functest/opnfv_tests/openstack/rally/rally.py | 64 ++++++++++--------- .../opnfv_tests/openstack/refstack/refstack.py | 18 +++--- functest/opnfv_tests/openstack/shaker/shaker.py | 34 +++++------ functest/opnfv_tests/openstack/tempest/tempest.py | 71 +++++++++++----------- functest/opnfv_tests/openstack/vmtp/vmtp.py | 38 ++++++------ functest/opnfv_tests/openstack/vping/vping_ssh.py | 9 ++- .../opnfv_tests/openstack/vping/vping_userdata.py | 10 +-- 10 files changed, 127 insertions(+), 129 deletions(-) (limited to 'functest/opnfv_tests/openstack') diff --git a/functest/opnfv_tests/openstack/barbican/barbican.py b/functest/opnfv_tests/openstack/barbican/barbican.py index 0c2429e10..706304bbf 100644 --- a/functest/opnfv_tests/openstack/barbican/barbican.py +++ b/functest/opnfv_tests/openstack/barbican/barbican.py @@ -32,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 47bf41b8d..7d8c0a0bd 100644 --- a/functest/opnfv_tests/openstack/cinder/cinder_test.py +++ b/functest/opnfv_tests/openstack/cinder/cinder_test.py @@ -54,12 +54,12 @@ class CinderCheck(singlevm.SingleVm2): def prepare(self): 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( diff --git a/functest/opnfv_tests/openstack/patrole/patrole.py b/functest/opnfv_tests/openstack/patrole/patrole.py index bdf18d35e..88c42f269 100644 --- a/functest/opnfv_tests/openstack/patrole/patrole.py +++ b/functest/opnfv_tests/openstack/patrole/patrole.py @@ -23,6 +23,6 @@ class Patrole(tempest.TempestCommon): 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/rally.py b/functest/opnfv_tests/openstack/rally/rally.py index 36f377ccf..3d897e25d 100644 --- a/functest/opnfv_tests/openstack/rally/rally.py +++ b/functest/opnfv_tests/openstack/rally/rally.py @@ -145,7 +145,7 @@ class RallyBase(singlevm.VmReady2): 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) @@ -154,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) @@ -190,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): @@ -228,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 @@ -239,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 @@ -291,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') @@ -335,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': @@ -362,8 +368,8 @@ class RallyBase(singlevm.VmReady2): def apply_blacklist(self, case_file_name, result_file_name): """Apply blacklist.""" LOGGER.debug("Applying blacklist...") - with open(case_file_name, 'r') as cases_file, open( - result_file_name, 'w') as result_file: + 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)) @@ -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,7 @@ class RallyBase(singlevm.VmReady2): output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) LOGGER.info("%s\n%s", " ".join(cmd), output.decode("utf-8")) - with open(report_json_dir) as json_file: + with open(report_json_dir, encoding='utf-8') as json_file: json_results = json_file.read() self._append_summary(json_results, test_name) @@ -492,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) @@ -500,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) @@ -570,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, @@ -588,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, @@ -664,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 @@ -680,7 +684,7 @@ 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): @@ -695,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 @@ -751,14 +755,14 @@ class RallyJobs(RallyBase): def prepare_run(self, **kwargs): """Create resources needed by test scenarios.""" super().prepare_run(**kwargs) - with open(os.path.join(self.rally_dir, - 'rally_jobs.yaml'), 'r') as task_file: + 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 @@ -770,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 @@ -800,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): @@ -821,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/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 7d9922060..275cc3077 100644 --- a/functest/opnfv_tests/openstack/shaker/shaker.py +++ b/functest/opnfv_tests/openstack/shaker/shaker.py @@ -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": diff --git a/functest/opnfv_tests/openstack/tempest/tempest.py b/functest/opnfv_tests/openstack/tempest/tempest.py index 60224019c..808ccba33 100644 --- a/functest/opnfv_tests/openstack/tempest/tempest.py +++ b/functest/opnfv_tests/openstack/tempest/tempest.py @@ -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 @@ -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 @@ -324,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') @@ -342,13 +342,13 @@ class TempestCommon(singlevm.VmReady2): os.remove(self.raw_list) os.rename(self.list, self.raw_list) cases_file = self.read_file(self.raw_list) - with open(self.list, 'w') as result_file: + with open(self.list, 'w', encoding='utf-8') as result_file: black_tests = [] try: deploy_scenario = env.get('DEPLOY_SCENARIO') if bool(deploy_scenario): # if DEPLOY_SCENARIO is set we read the file - with open(black_list) as black_list_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: @@ -376,12 +376,11 @@ class TempestCommon(singlevm.VmReady2): LOGGER.info("Starting Tempest test suite: '%s'.", cmd) with open( - os.path.join(self.res_dir, "tempest.log"), 'w+') as f_stdout: - + 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")): @@ -399,8 +398,8 @@ class TempestCommon(singlevm.VmReady2): 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.""" @@ -417,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 = [] @@ -453,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'): @@ -468,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 @@ -480,7 +478,7 @@ 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): @@ -503,11 +501,11 @@ class TempestCommon(singlevm.VmReady2): 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) + 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') as config_file: + with open(self.conf_file, 'w', encoding='utf-8') as config_file: rconfig.write(config_file) def update_network_section(self): @@ -524,7 +522,7 @@ class TempestCommon(singlevm.VmReady2): 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') as config_file: + with open(self.conf_file, 'w', encoding='utf-8') as config_file: rconfig.write(config_file) def update_compute_section(self): @@ -536,7 +534,7 @@ class TempestCommon(singlevm.VmReady2): rconfig.set( 'compute', 'fixed_network_name', self.network.name if self.network else env.get("EXTERNAL_NETWORK")) - 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_validation_section(self): @@ -551,7 +549,7 @@ class TempestCommon(singlevm.VmReady2): rconfig.set( 'validation', 'network_for_ssh', self.network.name if self.network else env.get("EXTERNAL_NETWORK")) - 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_scenario_section(self): @@ -559,12 +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', 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'): @@ -572,12 +570,11 @@ 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): @@ -590,7 +587,7 @@ class TempestCommon(singlevm.VmReady2): rconfig.set('dashboard', 'dashboard_url', env.get('DASHBOARD_URL')) else: rconfig.set('service_available', 'horizon', 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) def configure(self, **kwargs): # pylint: disable=unused-argument @@ -706,7 +703,7 @@ class TempestHeat(TempestCommon): def __init__(self, **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( @@ -764,7 +761,7 @@ class TempestHeat(TempestCommon): env.get("EXTERNAL_NETWORK")) rconfig.set( 'heat_plugin', 'network_for_ssh', env.get("EXTERNAL_NETWORK")) - 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/vmtp/vmtp.py b/functest/opnfv_tests/openstack/vmtp/vmtp.py index b0e6ff427..9833cc72a 100644 --- a/functest/opnfv_tests/openstack/vmtp/vmtp.py +++ b/functest/opnfv_tests/openstack/vmtp/vmtp.py @@ -57,7 +57,7 @@ class Vmtp(singlevm.VmReady2): if "case_name" not in kwargs: kwargs["case_name"] = 'vmtp' super().__init__(**kwargs) - self.config = "{}/vmtp.conf".format(self.res_dir) + 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): @@ -207,7 +207,7 @@ class Vmtp(singlevm.VmReady2): 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 2eb040b0e..ad64348c4 100644 --- a/functest/opnfv_tests/openstack/vping/vping_ssh.py +++ b/functest/opnfv_tests/openstack/vping/vping_ssh.py @@ -35,7 +35,7 @@ class VPingSSH(singlevm.SingleVm2): def prepare(self): 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() diff --git a/functest/opnfv_tests/openstack/vping/vping_userdata.py b/functest/opnfv_tests/openstack/vping/vping_userdata.py index 5b2308ec1..7de70f677 100644 --- a/functest/opnfv_tests/openstack/vping/vping_userdata.py +++ b/functest/opnfv_tests/openstack/vping/vping_userdata.py @@ -44,7 +44,7 @@ class VPingUserdata(singlevm.VmReady2): 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() @@ -106,11 +106,13 @@ class VPingUserdata(singlevm.VmReady2): :param test_ip: the IP value to substitute into the script :return: the bash 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): -- cgit 1.2.3-korg