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 """ global variables """
36 EXEC_SCRIPT = ("%s/functest/ci/exec_test.sh" % CONST.dir_repo_functest)
38 # This will be the return code of this script. If any of the tests fails,
39 # this variable will change to Result.EX_ERROR
42 class Result(enum.Enum):
47 class BlockingTestFailed(Exception):
51 class RunTestsParser(object):
54 self.parser = argparse.ArgumentParser()
55 self.parser.add_argument("-t", "--test", dest="test", action='store',
56 help="Test case or tier (group of tests) "
57 "to be executed. It will run all the test "
59 self.parser.add_argument("-n", "--noclean", help="Do not clean "
60 "OpenStack resources after running each "
61 "test (default=false).",
63 self.parser.add_argument("-r", "--report", help="Push results to "
64 "database (default=false).",
67 def parse_args(self, argv=[]):
68 return vars(self.parser.parse_args(argv))
71 class GlobalVariables:
72 EXECUTED_TEST_CASES = []
73 OVERALL_RESULT = Result.EX_OK
78 def print_separator(str, count=45):
80 for i in range(0, count - 1):
82 logger.info("%s" % line)
86 rc_file = CONST.openstack_creds
87 if not os.path.isfile(rc_file):
88 raise Exception("RC file %s does not exist..." % rc_file)
89 logger.debug("Sourcing the OpenStack RC file...")
90 os_utils.source_credentials(rc_file)
91 for key, value in os.environ.iteritems():
92 if re.search("OS_", key):
93 if key == 'OS_AUTH_URL':
94 ft_constants.OS_AUTH_URL = value
95 CONST.OS_AUTH_URL = value
96 elif key == 'OS_USERNAME':
97 ft_constants.OS_USERNAME = value
98 CONST.OS_USERNAME = value
99 elif key == 'OS_TENANT_NAME':
100 ft_constants.OS_TENANT_NAME = value
101 CONST.OS_TENANT_NAME = value
102 elif key == 'OS_PASSWORD':
103 ft_constants.OS_PASSWORD = value
104 CONST.OS_PASSWORD = value
107 def generate_os_snapshot():
115 def update_test_info(test_name, result, duration):
116 for test in GlobalVariables.EXECUTED_TEST_CASES:
117 if test['test_name'] == test_name:
118 test.update({"result": result,
119 "duration": duration})
122 def get_run_dict_if_defined(testname):
124 dict = ft_utils.get_dict_by_test(testname)
126 logger.error("Cannot get {}'s config options".format(testname))
131 logger.exception("Cannot get {}'s config options".format(testname))
135 def run_test(test, tier_name, testcases=None):
137 start = datetime.datetime.now()
138 test_name = test.get_name()
139 logger.info("\n") # blank line
141 logger.info("Running test case '%s'..." % test_name)
143 logger.debug("\n%s" % test)
146 if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
147 generate_os_snapshot()
149 flags = (" -t %s" % (test_name))
150 if GlobalVariables.REPORT_FLAG:
153 result = testcase_base.TestcaseBase.EX_RUN_ERROR
154 run_dict = get_run_dict_if_defined(test_name)
157 module = importlib.import_module(run_dict['module'])
158 cls = getattr(module, run_dict['class'])
162 kwargs = run_dict['args']
163 result = test_case.run(**kwargs)
165 result = test_case.run()
166 if result == testcase_base.TestcaseBase.EX_OK:
167 if GlobalVariables.REPORT_FLAG:
168 test_case.push_to_db()
169 result = test_case.check_criteria()
171 logger.exception("Cannot import module {}".format(
173 except AttributeError:
174 logger.exception("Cannot get class {}".format(
177 cmd = ("%s%s" % (EXEC_SCRIPT, flags))
178 logger.info("Executing command {} because {} "
179 "doesn't implement the new framework".format(
181 result = ft_utils.execute_command(cmd)
183 if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
186 end = datetime.datetime.now()
187 duration = (end - start).seconds
188 duration_str = ("%02d:%02d" % divmod(duration, 60))
189 logger.info("Test execution time: %s" % duration_str)
192 logger.error("The test case '%s' failed. " % test_name)
193 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
196 if test.is_blocking():
197 if not testcases or testcases == "all":
198 # if it is a single test we don't print the whole results table
199 update_test_info(test_name, result_str, duration_str)
200 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
201 raise BlockingTestFailed("The test case {} failed and is blocking"
202 .format(test.get_name()))
204 update_test_info(test_name, result_str, duration_str)
208 tier_name = tier.get_name()
209 tests = tier.get_tests()
210 if tests is None or len(tests) == 0:
211 logger.info("There are no supported test cases in this tier "
212 "for the given scenario")
214 logger.info("\n\n") # blank line
216 logger.info("Running tier '%s'" % tier_name)
218 logger.debug("\n%s" % tier)
220 run_test(test, tier_name)
227 for tier in tiers.get_tiers():
228 if (len(tier.get_tests()) != 0 and
229 re.search(CONST.CI_LOOP, tier.get_ci_loop()) is not None):
230 tiers_to_run.append(tier)
231 summary += ("\n - %s:\n\t %s"
233 tier.get_test_names()))
235 logger.info("Tests to be executed:%s" % summary)
236 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
237 for tier in tiers_to_run:
240 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
245 CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
246 CI_SCENARIO = CONST.DEPLOY_SCENARIO
248 file = CONST.functest_testcases_yaml
249 _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
251 if kwargs['noclean']:
252 GlobalVariables.CLEAN_FLAG = False
255 GlobalVariables.REPORT_FLAG = True
260 if _tiers.get_tier(kwargs['test']):
261 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(
262 [_tiers.get_tier(kwargs['test'])])
263 run_tier(_tiers.get_tier(kwargs['test']))
264 elif _tiers.get_test(kwargs['test']):
265 run_test(_tiers.get_test(kwargs['test']),
266 _tiers.get_tier(kwargs['test']),
268 elif kwargs['test'] == "all":
271 logger.error("Unknown test case or tier '%s', "
272 "or not supported by "
273 "the given scenario '%s'."
274 % (kwargs['test'], CI_SCENARIO))
275 logger.debug("Available tiers are:\n\n%s"
277 return Result.EX_ERROR
280 except Exception as e:
282 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
283 logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
284 return GlobalVariables.OVERALL_RESULT
287 if __name__ == '__main__':
288 parser = RunTestsParser()
289 args = parser.parse_args(sys.argv[1:])
290 sys.exit(main(**args).value)