3 # Copyright (c) 2015 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
11 """Tempest testcases implementation."""
13 from __future__ import division
22 from six.moves import configparser
23 from xtesting.core import testcase
26 from functest.core import singlevm
27 from functest.opnfv_tests.openstack.tempest import conf_utils
28 from functest.utils import config
29 from functest.utils import env
30 from functest.utils import functest_utils
32 LOGGER = logging.getLogger(__name__)
35 class TempestCommon(singlevm.VmReady2):
36 # pylint: disable=too-many-instance-attributes
37 """TempestCommon testcases implementation class."""
40 filename_alt = '/home/opnfv/functest/images/cirros-0.4.0-x86_64-disk.img'
42 def __init__(self, **kwargs):
43 if "case_name" not in kwargs:
44 kwargs["case_name"] = 'tempest'
45 super(TempestCommon, self).__init__(**kwargs)
46 assert self.orig_cloud
49 if self.orig_cloud.get_role("admin"):
50 self.role_name = "admin"
51 elif self.orig_cloud.get_role("Admin"):
52 self.role_name = "Admin"
54 raise Exception("Cannot detect neither admin nor Admin")
55 self.orig_cloud.grant_role(
56 self.role_name, user=self.project.user.id,
57 project=self.project.project.id,
58 domain=self.project.domain.id)
59 self.orig_cloud.grant_role(
60 self.role_name, user=self.project.user.id,
61 domain=self.project.domain.id)
64 OS_USERNAME=self.project.user.name,
65 OS_PROJECT_NAME=self.project.project.name,
66 OS_PROJECT_ID=self.project.project.id,
67 OS_PASSWORD=self.project.password)
69 del environ['OS_TENANT_NAME']
70 del environ['OS_TENANT_ID']
71 except Exception: # pylint: disable=broad-except
73 self.deployment_id = conf_utils.create_rally_deployment(
75 if not self.deployment_id:
76 raise Exception("Deployment create failed")
77 self.verifier_id = conf_utils.create_verifier()
78 if not self.verifier_id:
79 raise Exception("Verifier create failed")
80 self.verifier_repo_dir = conf_utils.get_verifier_repo_dir(
82 self.deployment_dir = conf_utils.get_verifier_deployment_dir(
83 self.verifier_id, self.deployment_id)
84 self.verification_id = None
85 self.res_dir = os.path.join(
86 getattr(config.CONF, 'dir_results'), self.case_name)
87 self.raw_list = os.path.join(self.res_dir, 'test_raw_list.txt')
88 self.list = os.path.join(self.res_dir, 'test_list.txt')
91 self.flavor_alt = None
94 self.services = kwargs['run']['args']['services']
95 except Exception: # pylint: disable=broad-except
97 self.neutron_extensions = []
99 self.neutron_extensions = kwargs['run']['args'][
100 'neutron_extensions']
101 except Exception: # pylint: disable=broad-except
104 def create_network_resources(self):
107 def check_services(self):
108 """Check the mandatory services."""
109 for service in self.services:
111 self.cloud.search_services(service)[0]
112 except Exception: # pylint: disable=broad-except
113 self.is_skipped = True
116 def check_extensions(self):
117 """Check the mandatory network extensions."""
118 extensions = self.cloud.get_network_extensions()
119 for network_extension in self.neutron_extensions:
120 if network_extension not in extensions:
122 "Cannot find Neutron extension: %s", network_extension)
123 self.is_skipped = True
126 def check_requirements(self):
127 self.check_services()
128 self.check_extensions()
133 def read_file(filename):
134 """Read file and return content as a stripped list."""
135 with open(filename) as src:
136 return [line.strip() for line in src.readlines()]
139 def get_verifier_result(verif_id):
140 """Retrieve verification results."""
147 cmd = ["rally", "verify", "show", "--uuid", verif_id]
148 LOGGER.info("Showing result for a verification: '%s'.", cmd)
149 proc = subprocess.Popen(cmd,
150 stdout=subprocess.PIPE,
151 stderr=subprocess.STDOUT)
152 for line in proc.stdout:
153 LOGGER.info(line.rstrip())
154 new_line = line.replace(' ', '').split('|')
155 if 'Tests' in new_line:
157 if 'Testscount' in new_line:
158 result['num_tests'] = int(new_line[2])
159 elif 'Success' in new_line:
160 result['num_success'] = int(new_line[2])
161 elif 'Skipped' in new_line:
162 result['num_skipped'] = int(new_line[2])
163 elif 'Failures' in new_line:
164 result['num_failures'] = int(new_line[2])
168 def backup_tempest_config(conf_file, res_dir):
170 Copy config file to tempest results directory
172 if not os.path.exists(res_dir):
174 shutil.copyfile(conf_file,
175 os.path.join(res_dir, 'tempest.conf'))
177 def generate_test_list(self, **kwargs):
178 """Generate test list based on the test mode."""
179 LOGGER.debug("Generating test case list...")
180 self.backup_tempest_config(self.conf_file, '/etc')
181 if kwargs.get('mode') == 'custom':
182 if os.path.isfile(conf_utils.TEMPEST_CUSTOM):
184 conf_utils.TEMPEST_CUSTOM, self.list)
186 raise Exception("Tempest test list file %s NOT found."
187 % conf_utils.TEMPEST_CUSTOM)
189 testr_mode = kwargs.get(
190 'mode', r'^tempest\.(api|scenario).*\[.*\bsmoke\b.*\]$')
191 cmd = "(cd {0}; stestr list '{1}' >{2} 2>/dev/null)".format(
192 self.verifier_repo_dir, testr_mode, self.list)
193 output = subprocess.check_output(cmd, shell=True)
194 LOGGER.info("%s\n%s", cmd, output)
195 os.remove('/etc/tempest.conf')
197 def apply_tempest_blacklist(self):
198 """Exclude blacklisted test cases."""
199 LOGGER.debug("Applying tempest blacklist...")
200 if os.path.exists(self.raw_list):
201 os.remove(self.raw_list)
202 os.rename(self.list, self.raw_list)
203 cases_file = self.read_file(self.raw_list)
204 result_file = open(self.list, 'w')
207 deploy_scenario = env.get('DEPLOY_SCENARIO')
208 if bool(deploy_scenario):
209 # if DEPLOY_SCENARIO is set we read the file
210 black_list_file = open(conf_utils.TEMPEST_BLACKLIST)
211 black_list_yaml = yaml.safe_load(black_list_file)
212 black_list_file.close()
213 for item in black_list_yaml:
214 scenarios = item['scenarios']
215 if deploy_scenario in scenarios:
216 tests = item['tests']
218 black_tests.append(test)
220 except Exception: # pylint: disable=broad-except
222 LOGGER.debug("Tempest blacklist file does not exist.")
224 for cases_line in cases_file:
225 for black_tests_line in black_tests:
226 if black_tests_line in cases_line:
229 result_file.write(str(cases_line) + '\n')
232 def run_verifier_tests(self, **kwargs):
233 """Execute tempest test cases."""
234 cmd = ["rally", "verify", "start", "--load-list",
236 cmd.extend(kwargs.get('option', []))
237 LOGGER.info("Starting Tempest test suite: '%s'.", cmd)
240 os.path.join(self.res_dir, "tempest.log"), 'w+')
242 proc = subprocess.Popen(
244 stdout=subprocess.PIPE,
245 stderr=subprocess.STDOUT,
249 for line in iter(proc.stdout.readline, b''):
250 if re.search(r"\} tempest\.", line):
251 LOGGER.info(line.rstrip())
252 elif re.search(r'(?=\(UUID=(.*)\))', line):
253 self.verification_id = re.search(
254 r'(?=\(UUID=(.*)\))', line).group(1)
259 if self.verification_id is None:
260 raise Exception('Verification UUID not found')
261 LOGGER.info('Verification UUID: %s', self.verification_id)
264 "{}/tempest.log".format(self.deployment_dir),
265 "{}/tempest.debug.log".format(self.res_dir))
267 def parse_verifier_result(self):
268 """Parse and save test results."""
269 stat = self.get_verifier_result(self.verification_id)
271 num_executed = stat['num_tests'] - stat['num_skipped']
273 self.result = 100 * stat['num_success'] / num_executed
274 except ZeroDivisionError:
276 if stat['num_tests'] > 0:
277 LOGGER.info("All tests have been skipped")
279 LOGGER.error("No test has been executed")
282 with open(os.path.join(self.res_dir,
283 "tempest.log"), 'r') as logfile:
284 output = logfile.read()
286 success_testcases = []
287 for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} success ',
289 success_testcases.append(match)
290 failed_testcases = []
291 for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} fail',
293 failed_testcases.append(match)
294 skipped_testcases = []
295 for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} skip:',
297 skipped_testcases.append(match)
299 self.details = {"tests_number": stat['num_tests'],
300 "success_number": stat['num_success'],
301 "skipped_number": stat['num_skipped'],
302 "failures_number": stat['num_failures'],
303 "success": success_testcases,
304 "skipped": skipped_testcases,
305 "failures": failed_testcases}
306 except Exception: # pylint: disable=broad-except
309 LOGGER.info("Tempest %s success_rate is %s%%",
310 self.case_name, self.result)
312 def generate_report(self):
313 """Generate verification report."""
314 html_file = os.path.join(self.res_dir,
315 "tempest-report.html")
316 cmd = ["rally", "verify", "report", "--type", "html", "--uuid",
317 self.verification_id, "--to", str(html_file)]
318 subprocess.check_output(cmd)
320 def update_rally_regex(self, rally_conf='/etc/rally/rally.conf'):
321 """Set image name as tempest img_name_regex"""
322 rconfig = configparser.RawConfigParser()
323 rconfig.read(rally_conf)
324 if not rconfig.has_section('openstack'):
325 rconfig.add_section('openstack')
326 rconfig.set('openstack', 'img_name_regex', '^{}$'.format(
328 with open(rally_conf, 'wb') as config_file:
329 rconfig.write(config_file)
331 def update_default_role(self, rally_conf='/etc/rally/rally.conf'):
332 """Detect and update the default role if required"""
333 role = self.get_default_role(self.cloud)
336 rconfig = configparser.RawConfigParser()
337 rconfig.read(rally_conf)
338 if not rconfig.has_section('openstack'):
339 rconfig.add_section('openstack')
340 rconfig.set('openstack', 'swift_operator_role', role.name)
341 with open(rally_conf, 'wb') as config_file:
342 rconfig.write(config_file)
344 def update_rally_logs(self, rally_conf='/etc/rally/rally.conf'):
345 """Print rally logs in res dir"""
346 if not os.path.exists(self.res_dir):
347 os.makedirs(self.res_dir)
348 rconfig = configparser.RawConfigParser()
349 rconfig.read(rally_conf)
350 rconfig.set('DEFAULT', 'log-file', 'rally.log')
351 rconfig.set('DEFAULT', 'log_dir', self.res_dir)
352 with open(rally_conf, 'wb') as config_file:
353 rconfig.write(config_file)
356 def clean_rally_conf(rally_conf='/etc/rally/rally.conf'):
357 """Clean Rally config"""
358 rconfig = configparser.RawConfigParser()
359 rconfig.read(rally_conf)
360 if rconfig.has_option('openstack', 'img_name_regex'):
361 rconfig.remove_option('openstack', 'img_name_regex')
362 if rconfig.has_option('openstack', 'swift_operator_role'):
363 rconfig.remove_option('openstack', 'swift_operator_role')
364 if rconfig.has_option('DEFAULT', 'log-file'):
365 rconfig.remove_option('DEFAULT', 'log-file')
366 if rconfig.has_option('DEFAULT', 'log_dir'):
367 rconfig.remove_option('DEFAULT', 'log_dir')
368 with open(rally_conf, 'wb') as config_file:
369 rconfig.write(config_file)
371 def update_scenario_section(self):
372 """Update scenario section in tempest.conf"""
373 rconfig = configparser.RawConfigParser()
374 rconfig.read(self.conf_file)
376 config.CONF, '{}_image'.format(self.case_name), self.filename)
377 if not rconfig.has_section('scenario'):
378 rconfig.add_section('scenario')
379 rconfig.set('scenario', 'img_file', os.path.basename(filename))
380 rconfig.set('scenario', 'img_dir', os.path.dirname(filename))
381 rconfig.set('scenario', 'img_disk_format', getattr(
382 config.CONF, '{}_image_format'.format(self.case_name),
384 extra_properties = self.extra_properties.copy()
385 if env.get('IMAGE_PROPERTIES'):
386 extra_properties.update(
387 functest_utils.convert_ini_to_dict(
388 env.get('IMAGE_PROPERTIES')))
389 extra_properties.update(
390 getattr(config.CONF, '{}_extra_properties'.format(
391 self.case_name), {}))
393 'scenario', 'img_properties',
394 functest_utils.convert_dict_to_ini(extra_properties))
395 with open(self.conf_file, 'wb') as config_file:
396 rconfig.write(config_file)
398 def configure(self, **kwargs): # pylint: disable=unused-argument
400 Create all openstack resources for tempest-based testcases and write
403 if not os.path.exists(self.res_dir):
404 os.makedirs(self.res_dir)
405 compute_cnt = len(self.cloud.list_hypervisors())
407 self.image_alt = self.publish_image_alt()
408 self.flavor_alt = self.create_flavor_alt()
409 LOGGER.debug("flavor: %s", self.flavor_alt)
411 self.conf_file = conf_utils.configure_verifier(self.deployment_dir)
412 if not self.conf_file:
413 raise Exception("Tempest verifier configuring failed")
414 conf_utils.configure_tempest_update_params(
416 image_id=self.image.id,
417 flavor_id=self.flavor.id,
418 compute_cnt=compute_cnt,
419 image_alt_id=self.image_alt.id,
420 flavor_alt_id=self.flavor_alt.id,
421 admin_role_name=self.role_name, cidr=self.cidr,
422 domain_id=self.project.domain.id)
423 self.update_scenario_section()
424 self.backup_tempest_config(self.conf_file, self.res_dir)
426 def run(self, **kwargs):
427 self.start_time = time.time()
429 assert super(TempestCommon, self).run(
430 **kwargs) == testcase.TestCase.EX_OK
431 if not os.path.exists(self.res_dir):
432 os.makedirs(self.res_dir)
433 self.update_rally_regex()
434 self.update_default_role()
435 self.update_rally_logs()
436 shutil.copy("/etc/rally/rally.conf", self.res_dir)
437 self.configure(**kwargs)
438 self.generate_test_list(**kwargs)
439 self.apply_tempest_blacklist()
440 self.run_verifier_tests(**kwargs)
441 self.parse_verifier_result()
442 self.generate_report()
443 res = testcase.TestCase.EX_OK
444 except Exception: # pylint: disable=broad-except
445 LOGGER.exception('Error with run')
447 res = testcase.TestCase.EX_RUN_ERROR
448 self.stop_time = time.time()
453 Cleanup all OpenStack objects. Should be called on completion.
455 self.clean_rally_conf()
457 self.cloud.delete_image(self.image_alt)
459 self.orig_cloud.delete_flavor(self.flavor_alt.id)
460 super(TempestCommon, self).clean()