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
25 from functest.core import testcase
26 from functest.opnfv_tests.openstack.snaps import snaps_utils
27 from functest.opnfv_tests.openstack.tempest import conf_utils
28 from functest.utils import config
29 from functest.utils import env
30 import functest.utils.functest_utils as ft_utils
32 from snaps.config.flavor import FlavorConfig
33 from snaps.config.network import NetworkConfig, SubnetConfig
34 from snaps.config.project import ProjectConfig
35 from snaps.config.user import UserConfig
37 from snaps.openstack import create_flavor
38 from snaps.openstack.create_flavor import OpenStackFlavor
39 from snaps.openstack.tests import openstack_tests
40 from snaps.openstack.utils import deploy_utils
43 LOGGER = logging.getLogger(__name__)
46 class TempestCommon(testcase.TestCase):
47 # pylint: disable=too-many-instance-attributes
48 """TempestCommon testcases implementation class."""
50 def __init__(self, **kwargs):
51 super(TempestCommon, self).__init__(**kwargs)
52 self.resources = TempestResourcesManager(**kwargs)
55 self.verifier_id = conf_utils.get_verifier_id()
56 self.verifier_repo_dir = conf_utils.get_verifier_repo_dir(
58 self.deployment_id = conf_utils.get_verifier_deployment_id()
59 self.deployment_dir = conf_utils.get_verifier_deployment_dir(
60 self.verifier_id, self.deployment_id)
61 self.verification_id = None
64 def read_file(filename):
65 """Read file and return content as a stripped list."""
66 with open(filename) as src:
67 return [line.strip() for line in src.readlines()]
70 def get_verifier_result(verif_id):
71 """Retrieve verification results."""
78 cmd = ["rally", "verify", "show", "--uuid", verif_id]
79 LOGGER.info("Showing result for a verification: '%s'.", cmd)
80 proc = subprocess.Popen(cmd,
81 stdout=subprocess.PIPE,
82 stderr=subprocess.STDOUT)
83 for line in proc.stdout:
84 new_line = line.replace(' ', '').split('|')
85 if 'Tests' in new_line:
88 if 'Testscount' in new_line:
89 result['num_tests'] = int(new_line[2])
90 elif 'Success' in new_line:
91 result['num_success'] = int(new_line[2])
92 elif 'Skipped' in new_line:
93 result['num_skipped'] = int(new_line[2])
94 elif 'Failures' in new_line:
95 result['num_failures'] = int(new_line[2])
98 def generate_test_list(self, verifier_repo_dir):
99 """Generate test list based on the test mode."""
100 LOGGER.debug("Generating test case list...")
101 if self.mode == 'custom':
102 if os.path.isfile(conf_utils.TEMPEST_CUSTOM):
104 conf_utils.TEMPEST_CUSTOM, conf_utils.TEMPEST_RAW_LIST)
106 raise Exception("Tempest test list file %s NOT found."
107 % conf_utils.TEMPEST_CUSTOM)
109 if self.mode == 'smoke':
110 testr_mode = r"'tempest\.(api|scenario).*\[.*\bsmoke\b.*\]'"
111 elif self.mode == 'full':
112 testr_mode = r"'^tempest\.'"
114 testr_mode = self.mode
116 "testr list-tests {1} > {2};"
117 "cd -;".format(verifier_repo_dir,
119 conf_utils.TEMPEST_RAW_LIST))
120 ft_utils.execute_command(cmd)
122 def apply_tempest_blacklist(self):
123 """Exclude blacklisted test cases."""
124 LOGGER.debug("Applying tempest blacklist...")
125 cases_file = self.read_file(conf_utils.TEMPEST_RAW_LIST)
126 result_file = open(conf_utils.TEMPEST_LIST, 'w')
129 installer_type = env.get('INSTALLER_TYPE')
130 deploy_scenario = env.get('DEPLOY_SCENARIO')
131 if bool(installer_type) * bool(deploy_scenario):
132 # if INSTALLER_TYPE and DEPLOY_SCENARIO are set we read the
134 black_list_file = open(conf_utils.TEMPEST_BLACKLIST)
135 black_list_yaml = yaml.safe_load(black_list_file)
136 black_list_file.close()
137 for item in black_list_yaml:
138 scenarios = item['scenarios']
139 installers = item['installers']
140 if (deploy_scenario in scenarios and
141 installer_type in installers):
142 tests = item['tests']
144 black_tests.append(test)
146 except Exception: # pylint: disable=broad-except
148 LOGGER.debug("Tempest blacklist file does not exist.")
150 for cases_line in cases_file:
151 for black_tests_line in black_tests:
152 if black_tests_line in cases_line:
155 result_file.write(str(cases_line) + '\n')
158 def run_verifier_tests(self):
159 """Execute tempest test cases."""
160 cmd = ["rally", "verify", "start", "--load-list",
161 conf_utils.TEMPEST_LIST]
162 cmd.extend(self.option)
163 LOGGER.info("Starting Tempest test suite: '%s'.", cmd)
166 os.path.join(conf_utils.TEMPEST_RESULTS_DIR, "tempest.log"), 'w+')
168 os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
169 "tempest-error.log"), 'w+')
171 proc = subprocess.Popen(
173 stdout=subprocess.PIPE,
178 for line in iter(proc.stdout.readline, b''):
179 if re.search(r"\} tempest\.", line):
180 LOGGER.info(line.replace('\n', ''))
181 elif re.search('Starting verification', line):
182 LOGGER.info(line.replace('\n', ''))
183 first_pos = line.index("UUID=") + len("UUID=")
184 last_pos = line.index(") for deployment")
185 self.verification_id = line[first_pos:last_pos]
186 LOGGER.debug('Verification UUID: %s', self.verification_id)
193 if self.verification_id is None:
194 raise Exception('Verification UUID not found')
196 def parse_verifier_result(self):
197 """Parse and save test results."""
198 stat = self.get_verifier_result(self.verification_id)
200 num_executed = stat['num_tests'] - stat['num_skipped']
202 self.result = 100 * stat['num_success'] / num_executed
203 except ZeroDivisionError:
205 if stat['num_tests'] > 0:
206 LOGGER.info("All tests have been skipped")
208 LOGGER.error("No test has been executed")
211 with open(os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
212 "tempest.log"), 'r') as logfile:
213 output = logfile.read()
215 success_testcases = []
216 for match in re.findall(r'.*\{0\} (.*?)[. ]*success ', output):
217 success_testcases.append(match)
218 failed_testcases = []
219 for match in re.findall(r'.*\{0\} (.*?)[. ]*fail ', output):
220 failed_testcases.append(match)
221 skipped_testcases = []
222 for match in re.findall(r'.*\{0\} (.*?)[. ]*skip:', output):
223 skipped_testcases.append(match)
225 self.details = {"tests": stat['num_tests'],
226 "failures": stat['num_failures'],
227 "success": success_testcases,
228 "skipped": skipped_testcases,
229 "errors": failed_testcases}
230 except Exception: # pylint: disable=broad-except
233 LOGGER.info("Tempest %s success_rate is %s%%",
234 self.case_name, self.result)
236 def generate_report(self):
237 """Generate verification report."""
238 html_file = os.path.join(conf_utils.TEMPEST_RESULTS_DIR,
239 "tempest-report.html")
240 cmd = ["rally", "verify", "report", "--type", "html", "--uuid",
241 self.verification_id, "--to", html_file]
242 subprocess.Popen(cmd, stdout=subprocess.PIPE,
243 stderr=subprocess.STDOUT)
245 def run(self, **kwargs):
247 self.start_time = time.time()
249 if not os.path.exists(conf_utils.TEMPEST_RESULTS_DIR):
250 os.makedirs(conf_utils.TEMPEST_RESULTS_DIR)
251 resources = self.resources.create()
252 compute_cnt = snaps_utils.get_active_compute_cnt(
253 self.resources.os_creds)
254 conf_utils.configure_tempest(
256 network_name=resources.get("network_name"),
257 image_id=resources.get("image_id"),
258 flavor_id=resources.get("flavor_id"),
259 compute_cnt=compute_cnt)
260 self.generate_test_list(self.verifier_repo_dir)
261 self.apply_tempest_blacklist()
262 self.run_verifier_tests()
263 self.parse_verifier_result()
264 self.generate_report()
265 res = testcase.TestCase.EX_OK
266 except Exception as err: # pylint: disable=broad-except
267 LOGGER.error('Error with run: %s', err)
268 res = testcase.TestCase.EX_RUN_ERROR
270 self.resources.cleanup()
272 self.stop_time = time.time()
276 class TempestSmokeSerial(TempestCommon):
277 """Tempest smoke serial testcase implementation."""
278 def __init__(self, **kwargs):
279 if "case_name" not in kwargs:
280 kwargs["case_name"] = 'tempest_smoke_serial'
281 TempestCommon.__init__(self, **kwargs)
283 self.option = ["--concurrency", "1"]
286 class TempestSmokeParallel(TempestCommon):
287 """Tempest smoke parallel testcase implementation."""
288 def __init__(self, **kwargs):
289 if "case_name" not in kwargs:
290 kwargs["case_name"] = 'tempest_smoke_parallel'
291 TempestCommon.__init__(self, **kwargs)
295 class TempestFullParallel(TempestCommon):
296 """Tempest full parallel testcase implementation."""
297 def __init__(self, **kwargs):
298 if "case_name" not in kwargs:
299 kwargs["case_name"] = 'tempest_full_parallel'
300 TempestCommon.__init__(self, **kwargs)
304 class TempestCustom(TempestCommon):
305 """Tempest custom testcase implementation."""
306 def __init__(self, **kwargs):
307 if "case_name" not in kwargs:
308 kwargs["case_name"] = 'tempest_custom'
309 TempestCommon.__init__(self, **kwargs)
311 self.option = ["--concurrency", "1"]
314 class TempestDefcore(TempestCommon):
315 """Tempest Defcore testcase implementation."""
316 def __init__(self, **kwargs):
317 if "case_name" not in kwargs:
318 kwargs["case_name"] = 'tempest_defcore'
319 TempestCommon.__init__(self, **kwargs)
320 self.mode = "defcore"
321 self.option = ["--concurrency", "1"]
324 class TempestResourcesManager(object):
325 """Tempest resource manager."""
326 def __init__(self, **kwargs):
327 self.os_creds = kwargs.get('os_creds') or snaps_utils.get_credentials()
328 self.guid = '-' + str(uuid.uuid4())
329 self.creators = list()
330 self.cirros_image_config = getattr(
331 config.CONF, 'snaps_images_cirros', None)
333 def _create_project(self):
334 """Create project for tests."""
335 project_creator = deploy_utils.create_project(
336 self.os_creds, ProjectConfig(
338 config.CONF, 'tempest_identity_tenant_name') + self.guid,
340 config.CONF, 'tempest_identity_tenant_description')))
341 if project_creator is None or project_creator.get_project() is None:
342 raise Exception("Failed to create tenant")
343 self.creators.append(project_creator)
344 return project_creator.get_project().id
346 def _create_user(self):
347 """Create user for tests."""
348 user_creator = deploy_utils.create_user(
349 self.os_creds, UserConfig(
351 config.CONF, 'tempest_identity_user_name') + self.guid,
353 config.CONF, 'tempest_identity_user_password'),
354 project_name=getattr(
355 config.CONF, 'tempest_identity_tenant_name') + self.guid))
356 if user_creator is None or user_creator.get_user() is None:
357 raise Exception("Failed to create user")
358 self.creators.append(user_creator)
359 return user_creator.get_user().id
361 def _create_network(self, project_name):
362 """Create network for tests."""
363 tempest_network_type = None
364 tempest_physical_network = None
365 tempest_segmentation_id = None
367 tempest_network_type = getattr(
368 config.CONF, 'tempest_network_type', None)
369 tempest_physical_network = getattr(
370 config.CONF, 'tempest_physical_network', None)
371 tempest_segmentation_id = getattr(
372 config.CONF, 'tempest_segmentation_id', None)
373 tempest_net_name = getattr(
374 config.CONF, 'tempest_private_net_name') + self.guid
376 network_creator = deploy_utils.create_network(
377 self.os_creds, NetworkConfig(
378 name=tempest_net_name,
379 project_name=project_name,
380 network_type=tempest_network_type,
381 physical_network=tempest_physical_network,
382 segmentation_id=tempest_segmentation_id,
383 subnet_settings=[SubnetConfig(
386 'tempest_private_subnet_name') + self.guid,
387 project_name=project_name,
389 config.CONF, 'tempest_private_subnet_cidr'))]))
390 if network_creator is None or network_creator.get_network() is None:
391 raise Exception("Failed to create private network")
392 self.creators.append(network_creator)
393 return tempest_net_name
395 def _create_image(self, name):
396 """Create image for tests"""
397 os_image_settings = openstack_tests.cirros_image_settings(
399 image_metadata=self.cirros_image_config)
400 image_creator = deploy_utils.create_image(
401 self.os_creds, os_image_settings)
402 if image_creator is None:
403 raise Exception('Failed to create image')
404 self.creators.append(image_creator)
405 return image_creator.get_image().id
407 def _create_flavor(self, name):
408 """Create flavor for tests."""
409 scenario = env.get('DEPLOY_SCENARIO')
410 flavor_metadata = None
411 if 'ovs' in scenario or 'fdio' in scenario:
412 flavor_metadata = create_flavor.MEM_PAGE_SIZE_LARGE
413 flavor_creator = OpenStackFlavor(
414 self.os_creds, FlavorConfig(
416 ram=getattr(config.CONF, 'openstack_flavor_ram'),
417 disk=getattr(config.CONF, 'openstack_flavor_disk'),
418 vcpus=getattr(config.CONF, 'openstack_flavor_vcpus'),
419 metadata=flavor_metadata))
420 flavor = flavor_creator.create()
422 raise Exception('Failed to create flavor')
423 self.creators.append(flavor_creator)
426 def create(self, use_custom_images=False, use_custom_flavors=False,
427 create_project=False):
428 """Create resources for Tempest test suite."""
430 'tempest_net_name': None,
432 'image_id_alt': None,
434 'flavor_id_alt': None
439 LOGGER.debug("Creating project and user for Tempest suite")
440 project_name = getattr(
441 config.CONF, 'tempest_identity_tenant_name') + self.guid
442 result['project_id'] = self._create_project()
443 result['user_id'] = self._create_user()
444 result['tenant_id'] = result['project_id'] # for compatibility
446 LOGGER.debug("Creating private network for Tempest suite")
447 result['tempest_net_name'] = self._create_network(project_name)
449 LOGGER.debug("Creating image for Tempest suite")
450 image_name = getattr(config.CONF, 'openstack_image_name') + self.guid
451 result['image_id'] = self._create_image(image_name)
453 if use_custom_images:
454 LOGGER.debug("Creating 2nd image for Tempest suite")
455 image_name = getattr(
456 config.CONF, 'openstack_image_name_alt') + self.guid
457 result['image_id_alt'] = self._create_image(image_name)
459 if (getattr(config.CONF, 'tempest_use_custom_flavors') == 'True' or
461 LOGGER.info("Creating flavor for Tempest suite")
462 name = getattr(config.CONF, 'openstack_flavor_name') + self.guid
463 result['flavor_id'] = self._create_flavor(name)
465 if use_custom_flavors:
466 LOGGER.info("Creating 2nd flavor for Tempest suite")
467 scenario = env.get('DEPLOY_SCENARIO')
468 if 'ovs' in scenario or 'fdio' in scenario:
469 setattr(config.CONF, 'openstack_flavor_ram', 1024)
471 config.CONF, 'openstack_flavor_name_alt') + self.guid
472 result['flavor_id_alt'] = self._create_flavor(name)
478 Cleanup all OpenStack objects. Should be called on completion.
480 for creator in reversed(self.creators):
483 except Exception as err: # pylint: disable=broad-except
484 LOGGER.error('Unexpected error cleaning - %s', err)