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
18 import functest.ci.generate_report as generate_report
19 import functest.ci.tier_builder as tb
20 import functest.core.testcase_base as testcase_base
21 import functest.utils.functest_constants as ft_constants
22 import functest.utils.functest_logger as ft_logger
23 import functest.utils.functest_utils as ft_utils
24 import functest.utils.openstack_clean as os_clean
25 import functest.utils.openstack_snapshot as os_snapshot
26 import functest.utils.openstack_utils as os_utils
27 from functest.utils.constants import CONST
30 """ logging configuration """
31 logger = ft_logger.Logger("run_tests").getLogger()
34 """ global variables """
35 EXEC_SCRIPT = ("%s/functest/ci/exec_test.sh" % CONST.dir_repo_functest)
37 # This will be the return code of this script. If any of the tests fails,
38 # this variable will change to -1
41 class RunTestsParser():
44 self.parser = argparse.ArgumentParser()
45 self.parser.add_argument("-t", "--test", dest="test", action='store',
46 help="Test case or tier (group of tests) "
47 "to be executed. It will run all the test "
49 self.parser.add_argument("-n", "--noclean", help="Do not clean "
50 "OpenStack resources after running each "
51 "test (default=false).",
53 self.parser.add_argument("-r", "--report", help="Push results to "
54 "database (default=false).",
57 def parse_args(self, argv=[]):
58 return vars(self.parser.parse_args(argv))
61 class GlobalVariables:
62 EXECUTED_TEST_CASES = []
68 def print_separator(str, count=45):
70 for i in range(0, count - 1):
72 logger.info("%s" % line)
76 rc_file = CONST.openstack_creds
77 if not os.path.isfile(rc_file):
78 logger.error("RC file %s does not exist..." % rc_file)
80 logger.debug("Sourcing the OpenStack RC file...")
81 creds = os_utils.source_credentials(rc_file)
82 for key, value in creds.iteritems():
83 if re.search("OS_", key):
84 if key == 'OS_AUTH_URL':
85 ft_constants.OS_AUTH_URL = value
86 CONST.OS_AUTH_URL = value
87 elif key == 'OS_USERNAME':
88 ft_constants.OS_USERNAME = value
89 CONST.OS_USERNAME = value
90 elif key == 'OS_TENANT_NAME':
91 ft_constants.OS_TENANT_NAME = value
92 CONST.OS_TENANT_NAME = value
93 elif key == 'OS_PASSWORD':
94 ft_constants.OS_PASSWORD = value
95 CONST.OS_PASSWORD = value
98 def generate_os_snapshot():
106 def update_test_info(test_name, result, duration):
107 for test in GlobalVariables.EXECUTED_TEST_CASES:
108 if test['test_name'] == test_name:
109 test.update({"result": result,
110 "duration": duration})
113 def get_run_dict_if_defined(testname):
115 dict = ft_utils.get_dict_by_test(testname)
117 logger.error("Cannot get {}'s config options".format(testname))
122 logger.exception("Cannot get {}'s config options".format(testname))
126 def run_test(test, tier_name, testcases=None):
128 start = datetime.datetime.now()
129 test_name = test.get_name()
130 logger.info("\n") # blank line
132 logger.info("Running test case '%s'..." % test_name)
134 logger.debug("\n%s" % test)
137 if GlobalVariables.CLEAN_FLAG:
138 generate_os_snapshot()
140 flags = (" -t %s" % (test_name))
141 if GlobalVariables.REPORT_FLAG:
144 result = testcase_base.TestcaseBase.EX_RUN_ERROR
145 run_dict = get_run_dict_if_defined(test_name)
148 module = importlib.import_module(run_dict['module'])
149 cls = getattr(module, run_dict['class'])
151 result = test_case.run()
152 if result == testcase_base.TestcaseBase.EX_OK:
153 if GlobalVariables.REPORT_FLAG:
154 test_case.publish_report()
155 result = test_case.check_criteria()
157 logger.exception("Cannot import module {}".format(
159 except AttributeError:
160 logger.exception("Cannot get class {}".format(
163 cmd = ("%s%s" % (EXEC_SCRIPT, flags))
164 logger.info("Executing command {} because {} "
165 "doesn't implement the new framework".format(
167 result = ft_utils.execute_command(cmd)
169 if GlobalVariables.CLEAN_FLAG:
171 end = datetime.datetime.now()
172 duration = (end - start).seconds
173 duration_str = ("%02d:%02d" % divmod(duration, 60))
174 logger.info("Test execution time: %s" % duration_str)
177 logger.error("The test case '%s' failed. " % test_name)
178 GlobalVariables.OVERALL_RESULT = -1
181 if test.is_blocking():
182 if not testcases or testcases == "all":
183 logger.info("This test case is blocking. Aborting overall "
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 logger.info("Execution exit value: %s" %
189 GlobalVariables.OVERALL_RESULT)
190 sys.exit(GlobalVariables.OVERALL_RESULT)
192 update_test_info(test_name, result_str, duration_str)
196 tier_name = tier.get_name()
197 tests = tier.get_tests()
198 if tests is None or len(tests) == 0:
199 logger.info("There are no supported test cases in this tier "
200 "for the given scenario")
202 logger.info("\n\n") # blank line
204 logger.info("Running tier '%s'" % tier_name)
206 logger.debug("\n%s" % tier)
208 run_test(test, tier_name)
215 for tier in tiers.get_tiers():
216 if (len(tier.get_tests()) != 0 and
217 re.search(CONST.CI_LOOP, tier.get_ci_loop()) is not None):
218 tiers_to_run.append(tier)
219 summary += ("\n - %s:\n\t %s"
221 tier.get_test_names()))
223 logger.info("Tests to be executed:%s" % summary)
224 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
225 for tier in tiers_to_run:
228 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
233 CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
234 CI_SCENARIO = CONST.DEPLOY_SCENARIO
236 file = CONST.functest_testcases_yaml
237 _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
239 if kwargs['noclean']:
240 GlobalVariables.CLEAN_FLAG = False
243 GlobalVariables.REPORT_FLAG = True
247 if _tiers.get_tier(kwargs['test']):
248 run_tier(_tiers.get_tier(kwargs['test']))
250 elif _tiers.get_test(kwargs['test']):
251 run_test(_tiers.get_test(kwargs['test']),
252 _tiers.get_tier(kwargs['test']),
255 elif kwargs['test'] == "all":
259 logger.error("Unknown test case or tier '%s', or not supported by "
260 "the given scenario '%s'."
261 % (kwargs['test'], CI_SCENARIO))
262 logger.debug("Available tiers are:\n\n%s"
267 logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
268 sys.exit(GlobalVariables.OVERALL_RESULT)
271 if __name__ == '__main__':
272 parser = RunTestsParser()
273 args = parser.parse_args(sys.argv[1:])