diff options
Diffstat (limited to 'functest/opnfv_tests/openstack/rally/rally.py')
-rw-r--r-- | functest/opnfv_tests/openstack/rally/rally.py | 171 |
1 files changed, 79 insertions, 92 deletions
diff --git a/functest/opnfv_tests/openstack/rally/rally.py b/functest/opnfv_tests/openstack/rally/rally.py index 3f483069b..3d897e25d 100644 --- a/functest/opnfv_tests/openstack/rally/rally.py +++ b/functest/opnfv_tests/openstack/rally/rally.py @@ -43,7 +43,8 @@ class RallyBase(singlevm.VmReady2): # pylint: disable=too-many-instance-attributes, too-many-public-methods stests = ['authenticate', 'glance', 'cinder', 'gnocchi', 'heat', - 'keystone', 'neutron', 'nova', 'quotas', 'swift', 'barbican'] + 'keystone', 'neutron', 'nova', 'quotas', 'swift', 'barbican', + 'vm'] rally_conf_path = "/etc/rally/rally.conf" rally_aar4_patch_path = pkg_resources.resource_filename( @@ -68,12 +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"): @@ -95,7 +96,6 @@ class RallyBase(singlevm.VmReady2): self.smoke = None self.start_time = None self.result = None - self.details = None self.compute_cnt = 0 self.flavor_alt = None self.tests = [] @@ -122,6 +122,7 @@ class RallyBase(singlevm.VmReady2): task_args['volume_version'] = self.volume_version task_args['volume_service_type'] = self.volume_service_type task_args['block_migration'] = env.get("BLOCK_MIGRATION").lower() + task_args['username'] = self.username if self.ext_net: task_args['floating_network'] = str(self.ext_net.name) @@ -131,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) @@ -146,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) @@ -166,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 @@ -182,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): @@ -220,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 @@ -231,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 @@ -283,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') @@ -327,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': @@ -354,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): @@ -406,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]) @@ -414,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 @@ -489,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) @@ -497,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) @@ -567,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, @@ -585,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, @@ -595,10 +602,10 @@ class RallyBase(singlevm.VmReady2): LOGGER.info("Rally '%s' success_rate is %s%% in %s/%s modules", self.case_name, success_rate, nb_modules, len(self.summary)) - payload.append({'summary': {'duration': total_duration, - 'nb tests': total_nb_tests, - 'nb success': success_rate}}) - self.details = payload + self.details['summary'] = {'duration': total_duration, + 'nb tests': total_nb_tests, + 'nb success': success_rate} + self.details["modules"] = payload @staticmethod def export_task(file_name, export_type="html"): @@ -640,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.""" @@ -648,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'): @@ -661,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 @@ -677,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()) @@ -692,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 @@ -712,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') @@ -726,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') @@ -741,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 @@ -767,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 @@ -797,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): @@ -811,30 +818,14 @@ class RallyJobs(RallyBase): task_args['flavor_name'] = str(self.flavor.name) return task_args - @staticmethod - def _remove_plugins_extra(): - inst_dir = getattr(config.CONF, 'dir_rally_inst') - try: - shutil.rmtree(os.path.join(inst_dir, 'plugins')) - shutil.rmtree(os.path.join(inst_dir, 'extra')) - except Exception: # pylint: disable=broad-except - pass - def prepare_task(self, test_name): """Prepare resources for test run.""" - self._remove_plugins_extra() jobs_dir = os.path.join( getattr(config.CONF, 'dir_rally_data'), test_name, 'rally-jobs') - inst_dir = getattr(config.CONF, 'dir_rally_inst') - shutil.copytree(os.path.join(jobs_dir, 'plugins'), - os.path.join(inst_dir, 'plugins')) - shutil.copytree(os.path.join(jobs_dir, 'extra'), - os.path.join(inst_dir, 'extra')) - 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): @@ -845,7 +836,3 @@ class RallyJobs(RallyBase): "--task", task_file_name, "--task-args", str(self.build_task_args(test_name))]) return True - - def clean(self): - self._remove_plugins_extra() - super(RallyJobs, self).clean() |