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
23 import os_client_config
24 from xtesting.core import testcase
27 from functest.opnfv_tests.openstack.tempest import conf_utils
28 from functest.utils import config
29 from functest.utils import env
31 LOGGER = logging.getLogger(__name__)
34 class TempestCommon(testcase.TestCase):
35 # pylint: disable=too-many-instance-attributes
36 """TempestCommon testcases implementation class."""
38 TEMPEST_RESULTS_DIR = os.path.join(
39 getattr(config.CONF, 'dir_results'), 'tempest')
41 def __init__(self, **kwargs):
42 super(TempestCommon, self).__init__(**kwargs)
43 self.resources = TempestResourcesManager()
46 self.verifier_id = conf_utils.get_verifier_id()
47 self.verifier_repo_dir = conf_utils.get_verifier_repo_dir(
49 self.deployment_id = conf_utils.get_verifier_deployment_id()
50 self.deployment_dir = conf_utils.get_verifier_deployment_dir(
51 self.verifier_id, self.deployment_id)
52 self.verification_id = None
53 self.res_dir = TempestCommon.TEMPEST_RESULTS_DIR
54 self.raw_list = os.path.join(self.res_dir, 'test_raw_list.txt')
55 self.list = os.path.join(self.res_dir, 'test_list.txt')
59 def read_file(filename):
60 """Read file and return content as a stripped list."""
61 with open(filename) as src:
62 return [line.strip() for line in src.readlines()]
65 def get_verifier_result(verif_id):
66 """Retrieve verification results."""
73 cmd = ["rally", "verify", "show", "--uuid", verif_id]
74 LOGGER.info("Showing result for a verification: '%s'.", cmd)
75 proc = subprocess.Popen(cmd,
76 stdout=subprocess.PIPE,
77 stderr=subprocess.STDOUT)
78 for line in proc.stdout:
79 new_line = line.replace(' ', '').split('|')
80 if 'Tests' in new_line:
83 if 'Testscount' in new_line:
84 result['num_tests'] = int(new_line[2])
85 elif 'Success' in new_line:
86 result['num_success'] = int(new_line[2])
87 elif 'Skipped' in new_line:
88 result['num_skipped'] = int(new_line[2])
89 elif 'Failures' in new_line:
90 result['num_failures'] = int(new_line[2])
94 def backup_tempest_config(conf_file, res_dir):
96 Copy config file to tempest results directory
98 if not os.path.exists(res_dir):
100 shutil.copyfile(conf_file,
101 os.path.join(res_dir, 'tempest.conf'))
103 def generate_test_list(self):
104 """Generate test list based on the test mode."""
105 LOGGER.debug("Generating test case list...")
106 if self.mode == 'custom':
107 if os.path.isfile(conf_utils.TEMPEST_CUSTOM):
109 conf_utils.TEMPEST_CUSTOM, self.list)
111 raise Exception("Tempest test list file %s NOT found."
112 % conf_utils.TEMPEST_CUSTOM)
114 if self.mode == 'smoke':
115 testr_mode = r"'^tempest\.(api|scenario).*\[.*\bsmoke\b.*\]$'"
116 elif self.mode == 'full':
117 testr_mode = r"'^tempest\.'"
119 testr_mode = self.mode
120 cmd = "(cd {0}; stestr list {1} >{2} 2>/dev/null)".format(
121 self.verifier_repo_dir, testr_mode, self.list)
122 output = subprocess.check_output(cmd, shell=True)
123 LOGGER.info("%s\n%s", cmd, output)
125 def apply_tempest_blacklist(self):
126 """Exclude blacklisted test cases."""
127 LOGGER.debug("Applying tempest blacklist...")
128 if os.path.exists(self.raw_list):
129 os.remove(self.raw_list)
130 os.rename(self.list, self.raw_list)
131 cases_file = self.read_file(self.raw_list)
132 result_file = open(self.list, 'w')
135 installer_type = env.get('INSTALLER_TYPE')
136 deploy_scenario = env.get('DEPLOY_SCENARIO')
137 if bool(installer_type) * bool(deploy_scenario):
138 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the
140 black_list_file = open(conf_utils.TEMPEST_BLACKLIST)
141 black_list_yaml = yaml.safe_load(black_list_file)
142 black_list_file.close()
143 for item in black_list_yaml:
144 scenarios = item['scenarios']
145 installers = item['installers']
146 if (deploy_scenario in scenarios and
147 installer_type in installers):
148 tests = item['tests']
150 black_tests.append(test)
152 except Exception: # pylint: disable=broad-except
154 LOGGER.debug("Tempest blacklist file does not exist.")
156 for cases_line in cases_file:
157 for black_tests_line in black_tests:
158 if black_tests_line in cases_line:
161 result_file.write(str(cases_line) + '\n')
164 def run_verifier_tests(self):
165 """Execute tempest test cases."""
166 cmd = ["rally", "verify", "start", "--load-list",
168 cmd.extend(self.option)
169 LOGGER.info("Starting Tempest test suite: '%s'.", cmd)
172 os.path.join(self.res_dir, "tempest.log"), 'w+')
174 os.path.join(self.res_dir,
175 "tempest-error.log"), 'w+')
177 proc = subprocess.Popen(
179 stdout=subprocess.PIPE,
184 for line in iter(proc.stdout.readline, b''):
185 if re.search(r"\} tempest\.", line):
186 LOGGER.info(line.replace('\n', ''))
187 elif re.search(r'(?=\(UUID=(.*)\))', line):
188 self.verification_id = re.search(
189 r'(?=\(UUID=(.*)\))', line).group(1)
190 LOGGER.info('Verification UUID: %s', self.verification_id)
197 if self.verification_id is None:
198 raise Exception('Verification UUID not found')
200 def parse_verifier_result(self):
201 """Parse and save test results."""
202 stat = self.get_verifier_result(self.verification_id)
204 num_executed = stat['num_tests'] - stat['num_skipped']
206 self.result = 100 * stat['num_success'] / num_executed
207 except ZeroDivisionError:
209 if stat['num_tests'] > 0:
210 LOGGER.info("All tests have been skipped")
212 LOGGER.error("No test has been executed")
215 with open(os.path.join(self.res_dir,
216 "tempest.log"), 'r') as logfile:
217 output = logfile.read()
219 success_testcases = []
220 for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} success ',
222 success_testcases.append(match)
223 failed_testcases = []
224 for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} fail',
226 failed_testcases.append(match)
227 skipped_testcases = []
228 for match in re.findall(r'.*\{\d{1,2}\} (.*?) \.{3} skip:',
230 skipped_testcases.append(match)
232 self.details = {"tests_number": stat['num_tests'],
233 "success_number": stat['num_success'],
234 "skipped_number": stat['num_skipped'],
235 "failures_number": stat['num_failures'],
236 "success": success_testcases,
237 "skipped": skipped_testcases,
238 "failures": failed_testcases}
239 except Exception: # pylint: disable=broad-except
242 LOGGER.info("Tempest %s success_rate is %s%%",
243 self.case_name, self.result)
245 def generate_report(self):
246 """Generate verification report."""
247 html_file = os.path.join(self.res_dir,
248 "tempest-report.html")
249 cmd = ["rally", "verify", "report", "--type", "html", "--uuid",
250 self.verification_id, "--to", html_file]
251 subprocess.Popen(cmd, stdout=subprocess.PIPE,
252 stderr=subprocess.STDOUT)
254 def configure(self, **kwargs): # pylint: disable=unused-argument
256 Create all openstack resources for tempest-based testcases and write
259 if not os.path.exists(self.res_dir):
260 os.makedirs(self.res_dir)
261 self.resources.create()
262 compute_cnt = len(self.resources.cloud.list_hypervisors())
263 self.conf_file = conf_utils.configure_verifier(self.deployment_dir)
264 conf_utils.configure_tempest_update_params(
265 self.conf_file, network_name=self.resources.network.id,
266 image_id=self.resources.image.id,
267 flavor_id=self.resources.flavor.id,
268 compute_cnt=compute_cnt,
269 image_alt_id=self.resources.image_alt.id,
270 flavor_alt_id=self.resources.flavor_alt.id)
271 self.backup_tempest_config(self.conf_file, self.res_dir)
273 def run(self, **kwargs):
274 self.start_time = time.time()
276 self.configure(**kwargs)
277 self.generate_test_list()
278 self.apply_tempest_blacklist()
279 self.run_verifier_tests()
280 self.parse_verifier_result()
281 self.generate_report()
282 res = testcase.TestCase.EX_OK
283 except Exception: # pylint: disable=broad-except
284 LOGGER.exception('Error with run')
285 res = testcase.TestCase.EX_RUN_ERROR
287 self.resources.cleanup()
288 self.stop_time = time.time()
292 class TempestSmokeSerial(TempestCommon):
293 """Tempest smoke serial testcase implementation."""
294 def __init__(self, **kwargs):
295 if "case_name" not in kwargs:
296 kwargs["case_name"] = 'tempest_smoke_serial'
297 TempestCommon.__init__(self, **kwargs)
299 self.option = ["--concurrency", "1"]
302 class TempestNeutronTrunk(TempestCommon):
303 """Tempest neutron trunk testcase implementation."""
304 def __init__(self, **kwargs):
305 if "case_name" not in kwargs:
306 kwargs["case_name"] = 'neutron_trunk'
307 TempestCommon.__init__(self, **kwargs)
308 self.mode = "'neutron_tempest_plugin.(api|scenario).test_trunk'"
309 self.res_dir = os.path.join(
310 getattr(config.CONF, 'dir_results'), 'neutron_trunk')
311 self.raw_list = os.path.join(self.res_dir, 'test_raw_list.txt')
312 self.list = os.path.join(self.res_dir, 'test_list.txt')
314 def configure(self, **kwargs):
315 super(TempestNeutronTrunk, self).configure(**kwargs)
316 rconfig = conf_utils.ConfigParser.RawConfigParser()
317 rconfig.read(self.conf_file)
318 rconfig.set('network-feature-enabled', 'api_extensions', 'all')
319 with open(self.conf_file, 'wb') as config_file:
320 rconfig.write(config_file)
323 class TempestSmokeParallel(TempestCommon):
324 """Tempest smoke parallel testcase implementation."""
325 def __init__(self, **kwargs):
326 if "case_name" not in kwargs:
327 kwargs["case_name"] = 'tempest_smoke_parallel'
328 TempestCommon.__init__(self, **kwargs)
332 class TempestFullParallel(TempestCommon):
333 """Tempest full parallel testcase implementation."""
334 def __init__(self, **kwargs):
335 if "case_name" not in kwargs:
336 kwargs["case_name"] = 'tempest_full_parallel'
337 TempestCommon.__init__(self, **kwargs)
341 class TempestCustom(TempestCommon):
342 """Tempest custom testcase implementation."""
343 def __init__(self, **kwargs):
344 if "case_name" not in kwargs:
345 kwargs["case_name"] = 'tempest_custom'
346 TempestCommon.__init__(self, **kwargs)
348 self.option = ["--concurrency", "1"]
351 class TempestDefcore(TempestCommon):
352 """Tempest Defcore testcase implementation."""
353 def __init__(self, **kwargs):
354 if "case_name" not in kwargs:
355 kwargs["case_name"] = 'tempest_defcore'
356 TempestCommon.__init__(self, **kwargs)
357 self.mode = "defcore"
358 self.option = ["--concurrency", "1"]
361 class TempestResourcesManager(object):
362 # pylint: disable=too-many-instance-attributes
363 """Tempest resource manager."""
365 self.guid = '-' + str(uuid.uuid4())
366 self.cloud = os_client_config.make_shade()
367 LOGGER.debug("cloud: %s", self.cloud)
368 self.domain = self.cloud.auth.get("project_domain_name", "Default")
369 LOGGER.debug("domain: %s", self.domain)
375 self.image_alt = None
377 self.flavor_alt = None
379 def _create_project(self):
380 """Create project for tests."""
381 self.project = self.cloud.create_project(
382 getattr(config.CONF, 'tempest_identity_tenant_name') + self.guid,
384 config.CONF, 'tempest_identity_tenant_description'),
385 domain_id=self.domain)
386 LOGGER.debug("project: %s", self.project)
388 def _create_user(self):
389 """Create user for tests."""
390 self.user = self.cloud.create_user(
392 config.CONF, 'tempest_identity_user_name') + self.guid,
393 password=getattr(config.CONF, 'tempest_identity_user_password'),
394 default_project=getattr(
395 config.CONF, 'tempest_identity_tenant_name') + self.guid,
396 domain_id=self.domain)
397 LOGGER.debug("user: %s", self.user)
399 def _create_network(self):
400 """Create network for tests."""
401 tempest_net_name = getattr(
402 config.CONF, 'tempest_private_net_name') + self.guid
404 if hasattr(config.CONF, 'tempest_network_type'):
405 provider["network_type"] = getattr(
406 config.CONF, 'tempest_network_type')
407 if hasattr(config.CONF, 'tempest_physical_network'):
408 provider["physical_network"] = getattr(
409 config.CONF, 'tempest_physical_network')
410 if hasattr(config.CONF, 'tempest_segmentation_id'):
411 provider["segmentation_id"] = getattr(
412 config.CONF, 'tempest_segmentation_id')
414 "Creating network with name: '%s'", tempest_net_name)
415 self.network = self.cloud.create_network(
416 tempest_net_name, provider=provider)
417 LOGGER.debug("network: %s", self.network)
419 self.subnet = self.cloud.create_subnet(
422 config.CONF, 'tempest_private_subnet_name') + self.guid,
423 cidr=getattr(config.CONF, 'tempest_private_subnet_cidr'),
425 dns_nameservers=[env.get('NAMESERVER')])
426 LOGGER.debug("subnet: %s", self.subnet)
428 def _create_image(self, name):
429 """Create image for tests"""
430 LOGGER.info("Creating image with name: '%s'", name)
431 meta = getattr(config.CONF, 'openstack_extra_properties', None)
432 image = self.cloud.create_image(
433 name, filename=getattr(config.CONF, 'openstack_image_url'),
434 is_public=True, meta=meta)
435 LOGGER.debug("image: %s", image)
438 def _create_flavor(self, name):
439 """Create flavor for tests."""
440 flavor = self.cloud.create_flavor(
441 name, getattr(config.CONF, 'openstack_flavor_ram'),
442 getattr(config.CONF, 'openstack_flavor_vcpus'),
443 getattr(config.CONF, 'openstack_flavor_disk'))
444 self.cloud.set_flavor_specs(
445 flavor.id, getattr(config.CONF, 'flavor_extra_specs', {}))
446 LOGGER.debug("flavor: %s", flavor)
449 def create(self, create_project=False):
450 """Create resources for Tempest test suite."""
452 self._create_project()
454 self._create_network()
456 LOGGER.debug("Creating two images for Tempest suite")
457 self.image = self._create_image(
458 getattr(config.CONF, 'openstack_image_name') + self.guid)
459 self.image_alt = self._create_image(
460 getattr(config.CONF, 'openstack_image_name_alt') + self.guid)
462 LOGGER.info("Creating two flavors for Tempest suite")
463 self.flavor = self._create_flavor(
464 getattr(config.CONF, 'openstack_flavor_name') + self.guid)
465 self.flavor_alt = self._create_flavor(
466 getattr(config.CONF, 'openstack_flavor_name_alt') + self.guid)
470 Cleanup all OpenStack objects. Should be called on completion.
472 self.cloud.delete_image(self.image)
473 self.cloud.delete_image(self.image_alt)
474 self.cloud.delete_network(self.network.id)
475 self.cloud.delete_flavor(self.flavor.id)
476 self.cloud.delete_flavor(self.flavor_alt.id)
478 self.cloud.delete_user(self.user.id)
479 self.cloud.delete_project(self.project.id)