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.__getattribute__('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.__setattr__('OS_AUTH_URL', value)
86 elif key == 'OS_USERNAME':
87 CONST.__setattr__('OS_USERNAME', value)
88 elif key == 'OS_TENANT_NAME':
89 CONST.__setattr__('OS_TENANT_NAME', value)
90 elif key == 'OS_PASSWORD':
91 CONST.__setattr__('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()
158 logger.info("\n%s\n", test_case)
160 logger.exception("Cannot import module {}".format(
162 except AttributeError:
163 logger.exception("Cannot get class {}".format(
166 raise Exception("Cannot import the class for the test case.")
168 if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
171 if result != testcase.TestCase.EX_OK:
172 logger.error("The test case '%s' failed. " % test_name)
173 GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
176 if test.is_blocking():
177 if not testcases or testcases == "all":
178 # if it is a single test we don't print the whole results table
179 update_test_info(test_name, result_str, duration)
180 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
181 raise BlockingTestFailed("The test case {} failed and is blocking"
182 .format(test.get_name()))
184 update_test_info(test_name, result_str, duration)
188 tier_name = tier.get_name()
189 tests = tier.get_tests()
190 if tests is None or len(tests) == 0:
191 logger.info("There are no supported test cases in this tier "
192 "for the given scenario")
194 logger.info("\n\n") # blank line
196 logger.info("Running tier '%s'" % tier_name)
198 logger.debug("\n%s" % tier)
200 run_test(test, tier_name)
207 for tier in tiers.get_tiers():
208 if (len(tier.get_tests()) != 0 and
209 re.search(CONST.__getattribute__('CI_LOOP'),
210 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 file = CONST.functest_testcases_yaml
227 _tiers = tb.TierBuilder(CONST.__getattribute__('INSTALLER_TYPE'),
228 CONST.__getattribute__('DEPLOY_SCENARIO'),
231 if kwargs['noclean']:
232 GlobalVariables.CLEAN_FLAG = False
235 GlobalVariables.REPORT_FLAG = True
240 if _tiers.get_tier(kwargs['test']):
241 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(
242 [_tiers.get_tier(kwargs['test'])])
243 run_tier(_tiers.get_tier(kwargs['test']))
244 elif _tiers.get_test(kwargs['test']):
245 run_test(_tiers.get_test(kwargs['test']),
246 _tiers.get_tier(kwargs['test']),
248 elif kwargs['test'] == "all":
251 logger.error("Unknown test case or tier '%s', "
252 "or not supported by "
253 "the given scenario '%s'."
255 CONST.__getattribute__('DEPLOY_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)