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
96 logger.debug("OS_AUTH_URL:%s" % CONST.OS_AUTH_URL)
97 logger.debug("OS_USERNAME:%s" % CONST.OS_USERNAME)
98 logger.debug("OS_TENANT_NAME:%s" % CONST.OS_TENANT_NAME)
99 logger.debug("OS_PASSWORD:%s" % CONST.OS_PASSWORD)
102 def generate_os_snapshot():
110 def update_test_info(test_name, result, duration):
111 for test in GlobalVariables.EXECUTED_TEST_CASES:
112 if test['test_name'] == test_name:
113 test.update({"result": result,
114 "duration": duration})
117 def get_run_dict_if_defined(testname):
119 dict = ft_utils.get_dict_by_test(testname)
121 logger.error("Cannot get {}'s config options".format(testname))
126 logger.exception("Cannot get {}'s config options".format(testname))
130 def run_test(test, tier_name, testcases=None):
132 start = datetime.datetime.now()
133 test_name = test.get_name()
134 logger.info("\n") # blank line
136 logger.info("Running test case '%s'..." % test_name)
138 logger.debug("\n%s" % test)
141 if GlobalVariables.CLEAN_FLAG:
142 generate_os_snapshot()
144 flags = (" -t %s" % (test_name))
145 if GlobalVariables.REPORT_FLAG:
148 result = testcase_base.TestcaseBase.EX_RUN_ERROR
149 run_dict = get_run_dict_if_defined(test_name)
152 module = importlib.import_module(run_dict['module'])
153 cls = getattr(module, run_dict['class'])
155 result = test_case.run()
156 if result == testcase_base.TestcaseBase.EX_OK:
157 if GlobalVariables.REPORT_FLAG:
158 test_case.publish_report()
159 result = test_case.check_criteria()
161 logger.exception("Cannot import module {}".format(
163 except AttributeError:
164 logger.exception("Cannot get class {}".format(
167 cmd = ("%s%s" % (EXEC_SCRIPT, flags))
168 logger.info("Executing command {} because {} "
169 "doesn't implement the new framework".format(
171 result = ft_utils.execute_command(cmd)
173 if 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 = -1
185 if test.is_blocking():
186 if not testcases or testcases == "all":
187 logger.info("This test case is blocking. Aborting overall "
189 # if it is a single test we don't print the whole results table
190 update_test_info(test_name, result_str, duration_str)
191 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
192 logger.info("Execution exit value: %s" %
193 GlobalVariables.OVERALL_RESULT)
194 sys.exit(GlobalVariables.OVERALL_RESULT)
196 update_test_info(test_name, result_str, duration_str)
200 tier_name = tier.get_name()
201 tests = tier.get_tests()
202 if tests is None or len(tests) == 0:
203 logger.info("There are no supported test cases in this tier "
204 "for the given scenario")
206 logger.info("\n\n") # blank line
208 logger.info("Running tier '%s'" % tier_name)
210 logger.debug("\n%s" % tier)
212 run_test(test, tier_name)
219 for tier in tiers.get_tiers():
220 if (len(tier.get_tests()) != 0 and
221 re.search(CONST.CI_LOOP, tier.get_ci_loop()) is not None):
222 tiers_to_run.append(tier)
223 summary += ("\n - %s:\n\t %s"
225 tier.get_test_names()))
227 logger.info("Tests to be executed:%s" % summary)
228 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
229 for tier in tiers_to_run:
232 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
237 CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
238 CI_SCENARIO = CONST.DEPLOY_SCENARIO
240 file = CONST.functest_testcases_yaml
241 _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
243 if kwargs['noclean']:
244 GlobalVariables.CLEAN_FLAG = False
247 GlobalVariables.REPORT_FLAG = True
251 if _tiers.get_tier(kwargs['test']):
252 run_tier(_tiers.get_tier(kwargs['test']))
254 elif _tiers.get_test(kwargs['test']):
255 run_test(_tiers.get_test(kwargs['test']),
256 _tiers.get_tier(kwargs['test']),
259 elif kwargs['test'] == "all":
263 logger.error("Unknown test case or tier '%s', or not supported by "
264 "the given scenario '%s'."
265 % (kwargs['test'], CI_SCENARIO))
266 logger.debug("Available tiers are:\n\n%s"
271 logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
272 sys.exit(GlobalVariables.OVERALL_RESULT)
275 if __name__ == '__main__':
276 parser = RunTestsParser()
277 args = parser.parse_args(sys.argv[1:])