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
19 import functest.ci.generate_report as generate_report
20 import functest.ci.tier_builder as tb
21 import functest.core.testcase_base as testcase_base
22 import functest.utils.functest_constants as ft_constants
23 import functest.utils.functest_logger as ft_logger
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
31 """ logging configuration """
32 logger = ft_logger.Logger("run_tests").getLogger()
35 class Result(enum.Enum):
40 class BlockingTestFailed(Exception):
44 class RunTestsParser(object):
47 self.parser = argparse.ArgumentParser()
48 self.parser.add_argument("-t", "--test", dest="test", action='store',
49 help="Test case or tier (group of tests) "
50 "to be executed. It will run all the test "
52 self.parser.add_argument("-n", "--noclean", help="Do not clean "
53 "OpenStack resources after running each "
54 "test (default=false).",
56 self.parser.add_argument("-r", "--report", help="Push results to "
57 "database (default=false).",
60 def parse_args(self, argv=[]):
61 return vars(self.parser.parse_args(argv))
64 class GlobalVariables:
65 EXECUTED_TEST_CASES = []
66 OVERALL_RESULT = Result.EX_OK
71 def print_separator(str, count=45):
73 for i in range(0, count - 1):
75 logger.info("%s" % line)
79 rc_file = CONST.openstack_creds
80 if not os.path.isfile(rc_file):
81 raise Exception("RC file %s does not exist..." % rc_file)
82 logger.debug("Sourcing the OpenStack RC file...")
83 os_utils.source_credentials(rc_file)
84 for key, value in os.environ.iteritems():
85 if re.search("OS_", key):
86 if key == 'OS_AUTH_URL':
87 ft_constants.OS_AUTH_URL = value
88 CONST.OS_AUTH_URL = value
89 elif key == 'OS_USERNAME':
90 ft_constants.OS_USERNAME = value
91 CONST.OS_USERNAME = value
92 elif key == 'OS_TENANT_NAME':
93 ft_constants.OS_TENANT_NAME = value
94 CONST.OS_TENANT_NAME = value
95 elif key == 'OS_PASSWORD':
96 ft_constants.OS_PASSWORD = value
97 CONST.OS_PASSWORD = value
100 def generate_os_snapshot():
108 def update_test_info(test_name, result, duration):
109 for test in GlobalVariables.EXECUTED_TEST_CASES:
110 if test['test_name'] == test_name:
111 test.update({"result": result,
112 "duration": duration})
115 def get_run_dict(testname):
117 dict = ft_utils.get_dict_by_test(testname)
119 logger.error("Cannot get {}'s config options".format(testname))
124 logger.exception("Cannot get {}'s config options".format(testname))
128 def run_test(test, tier_name, testcases=None):
130 start = datetime.datetime.now()
131 test_name = test.get_name()
132 logger.info("\n") # blank line
134 logger.info("Running test case '%s'..." % test_name)
136 logger.debug("\n%s" % test)
139 if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
140 generate_os_snapshot()
142 flags = (" -t %s" % (test_name))
143 if GlobalVariables.REPORT_FLAG:
146 result = testcase_base.TestcaseBase.EX_RUN_ERROR
147 run_dict = get_run_dict(test_name)
150 module = importlib.import_module(run_dict['module'])
151 cls = getattr(module, run_dict['class'])
155 kwargs = run_dict['args']
156 result = test_case.run(**kwargs)
158 result = test_case.run()
159 if result == testcase_base.TestcaseBase.EX_OK:
160 if GlobalVariables.REPORT_FLAG:
161 test_case.push_to_db()
162 result = test_case.check_criteria()
164 logger.exception("Cannot import module {}".format(
166 except AttributeError:
167 logger.exception("Cannot get class {}".format(
170 raise Exception("Cannot import the class for the test case.")
172 if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
175 end = datetime.datetime.now()
176 duration = (end - start).seconds
177 duration_str = ("%02d:%02d" % divmod(duration, 60))
178 logger.info("Test execution time: %s" % duration_str)
181 logger.error("The test case '%s' failed. " % test_name)
182 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
185 if test.is_blocking():
186 if not testcases or testcases == "all":
187 # if it is a single test we don't print the whole results table
188 update_test_info(test_name, result_str, duration_str)
189 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
190 raise BlockingTestFailed("The test case {} failed and is blocking"
191 .format(test.get_name()))
193 update_test_info(test_name, result_str, duration_str)
197 tier_name = tier.get_name()
198 tests = tier.get_tests()
199 if tests is None or len(tests) == 0:
200 logger.info("There are no supported test cases in this tier "
201 "for the given scenario")
203 logger.info("\n\n") # blank line
205 logger.info("Running tier '%s'" % tier_name)
207 logger.debug("\n%s" % tier)
209 run_test(test, tier_name)
216 for tier in tiers.get_tiers():
217 if (len(tier.get_tests()) != 0 and
218 re.search(CONST.CI_LOOP, tier.get_ci_loop()) is not None):
219 tiers_to_run.append(tier)
220 summary += ("\n - %s:\n\t %s"
222 tier.get_test_names()))
224 logger.info("Tests to be executed:%s" % summary)
225 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
226 for tier in tiers_to_run:
229 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
234 CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
235 CI_SCENARIO = CONST.DEPLOY_SCENARIO
237 file = CONST.functest_testcases_yaml
238 _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
240 if kwargs['noclean']:
241 GlobalVariables.CLEAN_FLAG = False
244 GlobalVariables.REPORT_FLAG = True
249 if _tiers.get_tier(kwargs['test']):
250 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(
251 [_tiers.get_tier(kwargs['test'])])
252 run_tier(_tiers.get_tier(kwargs['test']))
253 elif _tiers.get_test(kwargs['test']):
254 run_test(_tiers.get_test(kwargs['test']),
255 _tiers.get_tier(kwargs['test']),
257 elif kwargs['test'] == "all":
260 logger.error("Unknown test case or tier '%s', "
261 "or not supported by "
262 "the given scenario '%s'."
263 % (kwargs['test'], CI_SCENARIO))
264 logger.debug("Available tiers are:\n\n%s"
266 return Result.EX_ERROR
269 except Exception as e:
271 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
272 logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
273 return GlobalVariables.OVERALL_RESULT
276 if __name__ == '__main__':
277 parser = RunTestsParser()
278 args = parser.parse_args(sys.argv[1:])
279 sys.exit(main(**args).value)