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
20 import functest.ci.generate_report as generate_report
21 import functest.ci.tier_builder as tb
22 import functest.core.testcase as testcase
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
29 # __name__ cannot be used here
30 logger = logging.getLogger('functest.ci.run_tests')
33 class Result(enum.Enum):
38 class BlockingTestFailed(Exception):
42 class RunTestsParser(object):
45 self.parser = argparse.ArgumentParser()
46 self.parser.add_argument("-t", "--test", dest="test", action='store',
47 help="Test case or tier (group of tests) "
48 "to be executed. It will run all the test "
50 self.parser.add_argument("-n", "--noclean", help="Do not clean "
51 "OpenStack resources after running each "
52 "test (default=false).",
54 self.parser.add_argument("-r", "--report", help="Push results to "
55 "database (default=false).",
58 def parse_args(self, argv=[]):
59 return vars(self.parser.parse_args(argv))
62 class GlobalVariables:
63 EXECUTED_TEST_CASES = []
64 OVERALL_RESULT = Result.EX_OK
69 def print_separator(str, count=45):
71 for i in range(0, count - 1):
73 logger.info("%s" % line)
77 rc_file = CONST.openstack_creds
78 if not os.path.isfile(rc_file):
79 raise Exception("RC file %s does not exist..." % rc_file)
80 logger.debug("Sourcing the OpenStack RC file...")
81 os_utils.source_credentials(rc_file)
82 for key, value in os.environ.iteritems():
83 if re.search("OS_", key):
84 if key == 'OS_AUTH_URL':
85 CONST.OS_AUTH_URL = value
86 elif key == 'OS_USERNAME':
87 CONST.OS_USERNAME = value
88 elif key == 'OS_TENANT_NAME':
89 CONST.OS_TENANT_NAME = value
90 elif key == 'OS_PASSWORD':
91 CONST.OS_PASSWORD = value
94 def generate_os_snapshot():
102 def update_test_info(test_name, result, duration):
103 for test in GlobalVariables.EXECUTED_TEST_CASES:
104 if test['test_name'] == test_name:
105 test.update({"result": result,
106 "duration": duration})
109 def get_run_dict(testname):
111 dict = ft_utils.get_dict_by_test(testname)
113 logger.error("Cannot get {}'s config options".format(testname))
118 logger.exception("Cannot get {}'s config options".format(testname))
122 def run_test(test, tier_name, testcases=None):
125 test_name = test.get_name()
126 logger.info("\n") # blank line
128 logger.info("Running test case '%s'..." % test_name)
130 logger.debug("\n%s" % test)
133 if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
134 generate_os_snapshot()
136 flags = (" -t %s" % (test_name))
137 if GlobalVariables.REPORT_FLAG:
140 result = testcase.TestCase.EX_RUN_ERROR
141 run_dict = get_run_dict(test_name)
144 module = importlib.import_module(run_dict['module'])
145 cls = getattr(module, run_dict['class'])
146 test_dict = ft_utils.get_dict_by_test(test_name)
147 test_case = cls(**test_dict)
149 kwargs = run_dict['args']
150 result = test_case.run(**kwargs)
152 result = test_case.run()
153 if result == testcase.TestCase.EX_OK:
154 if GlobalVariables.REPORT_FLAG:
155 test_case.push_to_db()
156 result = test_case.is_successful()
157 duration = test_case.get_duration()
159 logger.exception("Cannot import module {}".format(
161 except AttributeError:
162 logger.exception("Cannot get class {}".format(
165 raise Exception("Cannot import the class for the test case.")
167 if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
170 logger.info("Test execution time: %s", duration)
172 if result != testcase.TestCase.EX_OK:
173 logger.error("The test case '%s' failed. " % test_name)
174 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
177 if test.is_blocking():
178 if not testcases or testcases == "all":
179 # if it is a single test we don't print the whole results table
180 update_test_info(test_name, result_str, duration)
181 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
182 raise BlockingTestFailed("The test case {} failed and is blocking"
183 .format(test.get_name()))
185 update_test_info(test_name, result_str, duration)
189 tier_name = tier.get_name()
190 tests = tier.get_tests()
191 if tests is None or len(tests) == 0:
192 logger.info("There are no supported test cases in this tier "
193 "for the given scenario")
195 logger.info("\n\n") # blank line
197 logger.info("Running tier '%s'" % tier_name)
199 logger.debug("\n%s" % tier)
201 run_test(test, tier_name)
208 for tier in tiers.get_tiers():
209 if (len(tier.get_tests()) != 0 and
210 re.search(CONST.CI_LOOP, tier.get_ci_loop()) is not None):
211 tiers_to_run.append(tier)
212 summary += ("\n - %s:\n\t %s"
214 tier.get_test_names()))
216 logger.info("Tests to be executed:%s" % summary)
217 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
218 for tier in tiers_to_run:
221 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
226 CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
227 CI_SCENARIO = CONST.DEPLOY_SCENARIO
229 file = CONST.functest_testcases_yaml
230 _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
232 if kwargs['noclean']:
233 GlobalVariables.CLEAN_FLAG = False
236 GlobalVariables.REPORT_FLAG = True
241 if _tiers.get_tier(kwargs['test']):
242 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(
243 [_tiers.get_tier(kwargs['test'])])
244 run_tier(_tiers.get_tier(kwargs['test']))
245 elif _tiers.get_test(kwargs['test']):
246 run_test(_tiers.get_test(kwargs['test']),
247 _tiers.get_tier(kwargs['test']),
249 elif kwargs['test'] == "all":
252 logger.error("Unknown test case or tier '%s', "
253 "or not supported by "
254 "the given scenario '%s'."
255 % (kwargs['test'], CI_SCENARIO))
256 logger.debug("Available tiers are:\n\n%s"
258 return Result.EX_ERROR
261 except Exception as e:
263 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
264 logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
265 return GlobalVariables.OVERALL_RESULT
268 if __name__ == '__main__':
269 logging.config.fileConfig(
270 CONST.__getattribute__('dir_functest_logging_cfg'))
271 parser = RunTestsParser()
272 args = parser.parse_args(sys.argv[1:])
273 sys.exit(main(**args).value)