3 # Author: Jose Lausuch (jose.lausuch@ericsson.com)
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
22 import functest.ci.tier_builder as tb
23 import functest.core.testcase as testcase
24 import functest.utils.functest_utils as ft_utils
25 import functest.utils.openstack_clean as os_clean
26 import functest.utils.openstack_snapshot as os_snapshot
27 import functest.utils.openstack_utils as os_utils
28 from functest.utils.constants import CONST
30 # __name__ cannot be used here
31 logger = logging.getLogger('functest.ci.run_tests')
34 class Result(enum.Enum):
39 class BlockingTestFailed(Exception):
43 class TestNotEnabled(Exception):
47 class RunTestsParser(object):
50 self.parser = argparse.ArgumentParser()
51 self.parser.add_argument("-t", "--test", dest="test", action='store',
52 help="Test case or tier (group of tests) "
53 "to be executed. It will run all the test "
55 self.parser.add_argument("-n", "--noclean", help="Do not clean "
56 "OpenStack resources after running each "
57 "test (default=false).",
59 self.parser.add_argument("-r", "--report", help="Push results to "
60 "database (default=false).",
63 def parse_args(self, argv=[]):
64 return vars(self.parser.parse_args(argv))
67 class GlobalVariables:
68 EXECUTED_TEST_CASES = []
69 OVERALL_RESULT = Result.EX_OK
74 def print_separator(str, count=45):
76 for i in range(0, count - 1):
78 logger.info("%s" % line)
82 rc_file = CONST.__getattribute__('openstack_creds')
83 if not os.path.isfile(rc_file):
84 raise Exception("RC file %s does not exist..." % rc_file)
85 logger.debug("Sourcing the OpenStack RC file...")
86 os_utils.source_credentials(rc_file)
87 for key, value in os.environ.iteritems():
88 if re.search("OS_", key):
89 if key == 'OS_AUTH_URL':
90 CONST.__setattr__('OS_AUTH_URL', value)
91 elif key == 'OS_USERNAME':
92 CONST.__setattr__('OS_USERNAME', value)
93 elif key == 'OS_TENANT_NAME':
94 CONST.__setattr__('OS_TENANT_NAME', value)
95 elif key == 'OS_PASSWORD':
96 CONST.__setattr__('OS_PASSWORD', value)
99 def generate_os_snapshot():
107 def get_run_dict(testname):
109 dict = ft_utils.get_dict_by_test(testname)
111 logger.error("Cannot get {}'s config options".format(testname))
116 logger.exception("Cannot get {}'s config options".format(testname))
120 def run_test(test, tier_name, testcases=None):
121 if not test.is_enabled():
122 raise TestNotEnabled("The test case {} is not enabled"
123 .format(test.get_name()))
124 test_name = test.get_name()
125 logger.info("\n") # blank line
127 logger.info("Running test case '%s'..." % test_name)
129 logger.debug("\n%s" % test)
132 if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
133 generate_os_snapshot()
135 flags = (" -t %s" % (test_name))
136 if GlobalVariables.REPORT_FLAG:
139 result = testcase.TestCase.EX_RUN_ERROR
140 run_dict = get_run_dict(test_name)
143 module = importlib.import_module(run_dict['module'])
144 cls = getattr(module, run_dict['class'])
145 test_dict = ft_utils.get_dict_by_test(test_name)
146 test_case = cls(**test_dict)
147 GlobalVariables.EXECUTED_TEST_CASES.append(test_case)
149 kwargs = run_dict['args']
150 result = test_case.run(**kwargs)
152 result = test_case.run()
153 if result == testcase.TestCase.EX_OK:
154 if GlobalVariables.REPORT_FLAG:
155 test_case.push_to_db()
156 result = test_case.is_successful()
157 logger.info("Test result:\n\n%s\n", test_case)
159 logger.exception("Cannot import module {}".format(
161 except AttributeError:
162 logger.exception("Cannot get class {}".format(
165 raise Exception("Cannot import the class for the test case.")
167 if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
169 if result != testcase.TestCase.EX_OK:
170 logger.error("The test case '%s' failed. " % test_name)
171 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
172 if test.is_blocking():
173 raise BlockingTestFailed("The test case {} failed and is blocking"
174 .format(test.get_name()))
178 tier_name = tier.get_name()
179 tests = tier.get_tests()
180 if tests is None or len(tests) == 0:
181 logger.info("There are no supported test cases in this tier "
182 "for the given scenario")
184 logger.info("\n\n") # blank line
186 logger.info("Running tier '%s'" % tier_name)
188 logger.debug("\n%s" % tier)
190 run_test(test, tier_name)
197 for tier in tiers.get_tiers():
198 if (len(tier.get_tests()) != 0 and
199 re.search(CONST.__getattribute__('CI_LOOP'),
200 tier.get_ci_loop()) is not None):
201 tiers_to_run.append(tier)
202 summary += ("\n - %s:\n\t %s"
204 tier.get_test_names()))
206 logger.info("Tests to be executed:%s" % summary)
207 for tier in tiers_to_run:
213 file = CONST.functest_testcases_yaml
214 _tiers = tb.TierBuilder(CONST.__getattribute__('INSTALLER_TYPE'),
215 CONST.__getattribute__('DEPLOY_SCENARIO'),
218 if kwargs['noclean']:
219 GlobalVariables.CLEAN_FLAG = False
222 GlobalVariables.REPORT_FLAG = True
227 if _tiers.get_tier(kwargs['test']):
228 run_tier(_tiers.get_tier(kwargs['test']))
229 elif _tiers.get_test(kwargs['test']):
230 run_test(_tiers.get_test(kwargs['test']),
231 _tiers.get_tier_name(kwargs['test']),
233 elif kwargs['test'] == "all":
236 logger.error("Unknown test case or tier '%s', "
237 "or not supported by "
238 "the given scenario '%s'."
240 CONST.__getattribute__('DEPLOY_SCENARIO')))
241 logger.debug("Available tiers are:\n\n%s"
243 return Result.EX_ERROR
246 except Exception as e:
248 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
250 msg = prettytable.PrettyTable(
251 header_style='upper', padding_width=5,
252 field_names=['env var', 'value'])
253 for env_var in ['INSTALLER_TYPE', 'DEPLOY_SCENARIO', 'BUILD_TAG',
255 msg.add_row([env_var, CONST.__getattribute__(env_var)])
256 logger.info("Deployment description: \n\n%s\n", msg)
258 msg = prettytable.PrettyTable(
259 header_style='upper', padding_width=5,
260 field_names=['test case', 'project', 'tier', 'duration', 'result'])
261 for test_case in GlobalVariables.EXECUTED_TEST_CASES:
262 result = 'PASS' if(test_case.is_successful(
263 ) == test_case.EX_OK) else 'FAIL'
264 msg.add_row([test_case.case_name, test_case.project_name,
265 _tiers.get_tier_name(test_case.case_name),
266 test_case.get_duration(), result])
267 logger.info("FUNCTEST REPORT: \n\n%s\n", msg)
269 logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
270 return GlobalVariables.OVERALL_RESULT
273 if __name__ == '__main__':
274 logging.config.fileConfig(
275 CONST.__getattribute__('dir_functest_logging_cfg'))
276 parser = RunTestsParser()
277 args = parser.parse_args(sys.argv[1:])
278 sys.exit(main(**args).value)