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 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'])
154 kwargs = run_dict['args']
155 result = test_case.run(**kwargs)
157 result = test_case.run()
158 if result == testcase_base.TestcaseBase.EX_OK:
159 if GlobalVariables.REPORT_FLAG:
160 test_case.push_to_db()
161 result = test_case.check_criteria()
163 logger.exception("Cannot import module {}".format(
165 except AttributeError:
166 logger.exception("Cannot get class {}".format(
169 raise Exception("Cannot import the class for the test case.")
171 if GlobalVariables.CLEAN_FLAG:
173 end = datetime.datetime.now()
174 duration = (end - start).seconds
175 duration_str = ("%02d:%02d" % divmod(duration, 60))
176 logger.info("Test execution time: %s" % duration_str)
179 logger.error("The test case '%s' failed. " % test_name)
180 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
183 if test.is_blocking():
184 if not testcases or testcases == "all":
185 # if it is a single test we don't print the whole results table
186 update_test_info(test_name, result_str, duration_str)
187 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
188 raise BlockingTestFailed("The test case {} failed and is blocking"
189 .format(test.get_name()))
191 update_test_info(test_name, result_str, duration_str)
195 tier_name = tier.get_name()
196 tests = tier.get_tests()
197 if tests is None or len(tests) == 0:
198 logger.info("There are no supported test cases in this tier "
199 "for the given scenario")
201 logger.info("\n\n") # blank line
203 logger.info("Running tier '%s'" % tier_name)
205 logger.debug("\n%s" % tier)
207 run_test(test, tier_name)
214 for tier in tiers.get_tiers():
215 if (len(tier.get_tests()) != 0 and
216 re.search(CONST.CI_LOOP, tier.get_ci_loop()) is not None):
217 tiers_to_run.append(tier)
218 summary += ("\n - %s:\n\t %s"
220 tier.get_test_names()))
222 logger.info("Tests to be executed:%s" % summary)
223 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
224 for tier in tiers_to_run:
227 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
232 CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
233 CI_SCENARIO = CONST.DEPLOY_SCENARIO
235 file = CONST.functest_testcases_yaml
236 _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
238 if kwargs['noclean']:
239 GlobalVariables.CLEAN_FLAG = False
242 GlobalVariables.REPORT_FLAG = True
247 if _tiers.get_tier(kwargs['test']):
248 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(
249 [_tiers.get_tier(kwargs['test'])])
250 run_tier(_tiers.get_tier(kwargs['test']))
251 elif _tiers.get_test(kwargs['test']):
252 run_test(_tiers.get_test(kwargs['test']),
253 _tiers.get_tier(kwargs['test']),
255 elif kwargs['test'] == "all":
258 logger.error("Unknown test case or tier '%s', "
259 "or not supported by "
260 "the given scenario '%s'."
261 % (kwargs['test'], CI_SCENARIO))
262 logger.debug("Available tiers are:\n\n%s"
264 return Result.EX_ERROR
267 except Exception as e:
269 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
270 logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
271 return GlobalVariables.OVERALL_RESULT
274 if __name__ == '__main__':
275 parser = RunTestsParser()
276 args = parser.parse_args(sys.argv[1:])
277 sys.exit(main(**args).value)