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():
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 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'])
161 kwargs = run_dict['args']
162 result = test_case.run(**kwargs)
164 result = test_case.run()
165 if result == testcase_base.TestcaseBase.EX_OK:
166 if GlobalVariables.REPORT_FLAG:
167 test_case.push_to_db()
168 result = test_case.check_criteria()
170 logger.exception("Cannot import module {}".format(
172 except AttributeError:
173 logger.exception("Cannot get class {}".format(
176 cmd = ("%s%s" % (EXEC_SCRIPT, flags))
177 logger.info("Executing command {} because {} "
178 "doesn't implement the new framework".format(
180 result = ft_utils.execute_command(cmd)
182 if GlobalVariables.CLEAN_FLAG:
184 end = datetime.datetime.now()
185 duration = (end - start).seconds
186 duration_str = ("%02d:%02d" % divmod(duration, 60))
187 logger.info("Test execution time: %s" % duration_str)
190 logger.error("The test case '%s' failed. " % test_name)
191 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
194 if test.is_blocking():
195 if not testcases or testcases == "all":
196 # if it is a single test we don't print the whole results table
197 update_test_info(test_name, result_str, duration_str)
198 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
199 raise BlockingTestFailed("The test case {} failed and is blocking"
200 .format(test.get_name()))
202 update_test_info(test_name, result_str, duration_str)
206 tier_name = tier.get_name()
207 tests = tier.get_tests()
208 if tests is None or len(tests) == 0:
209 logger.info("There are no supported test cases in this tier "
210 "for the given scenario")
212 logger.info("\n\n") # blank line
214 logger.info("Running tier '%s'" % tier_name)
216 logger.debug("\n%s" % tier)
218 run_test(test, tier_name)
225 for tier in tiers.get_tiers():
226 if (len(tier.get_tests()) != 0 and
227 re.search(CONST.CI_LOOP, tier.get_ci_loop()) is not None):
228 tiers_to_run.append(tier)
229 summary += ("\n - %s:\n\t %s"
231 tier.get_test_names()))
233 logger.info("Tests to be executed:%s" % summary)
234 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
235 for tier in tiers_to_run:
238 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
243 CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
244 CI_SCENARIO = CONST.DEPLOY_SCENARIO
246 file = CONST.functest_testcases_yaml
247 _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
249 if kwargs['noclean']:
250 GlobalVariables.CLEAN_FLAG = False
253 GlobalVariables.REPORT_FLAG = True
258 if _tiers.get_tier(kwargs['test']):
259 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(
260 [_tiers.get_tier(kwargs['test'])])
261 run_tier(_tiers.get_tier(kwargs['test']))
262 elif _tiers.get_test(kwargs['test']):
263 run_test(_tiers.get_test(kwargs['test']),
264 _tiers.get_tier(kwargs['test']),
266 elif kwargs['test'] == "all":
269 logger.error("Unknown test case or tier '%s', "
270 "or not supported by "
271 "the given scenario '%s'."
272 % (kwargs['test'], CI_SCENARIO))
273 logger.debug("Available tiers are:\n\n%s"
275 return Result.EX_ERROR
278 except Exception as e:
280 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
281 logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
282 return GlobalVariables.OVERALL_RESULT
285 if __name__ == '__main__':
286 parser = RunTestsParser()
287 args = parser.parse_args(sys.argv[1:])
288 sys.exit(main(**args).value)