fix KeyError: 'clean_flag'
[functest.git] / functest / ci / run_tests.py
1 #!/usr/bin/python -u
2 #
3 # Author: Jose Lausuch (jose.lausuch@ericsson.com)
4 #
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
9 #
10
11 import argparse
12 import datetime
13 import enum
14 import importlib
15 import os
16 import re
17 import sys
18
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
29
30
31 """ logging configuration """
32 logger = ft_logger.Logger("run_tests").getLogger()
33
34
35 """ global variables """
36 EXEC_SCRIPT = ("%s/functest/ci/exec_test.sh" % CONST.dir_repo_functest)
37
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
40
41
42 class Result(enum.Enum):
43     EX_OK = os.EX_OK
44     EX_ERROR = -1
45
46
47 class BlockingTestFailed(Exception):
48     pass
49
50
51 class RunTestsParser(object):
52
53     def __init__(self):
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 "
58                                  "if not specified.")
59         self.parser.add_argument("-n", "--noclean", help="Do not clean "
60                                  "OpenStack resources after running each "
61                                  "test (default=false).",
62                                  action="store_true")
63         self.parser.add_argument("-r", "--report", help="Push results to "
64                                  "database (default=false).",
65                                  action="store_true")
66
67     def parse_args(self, argv=[]):
68         return vars(self.parser.parse_args(argv))
69
70
71 class GlobalVariables:
72     EXECUTED_TEST_CASES = []
73     OVERALL_RESULT = Result.EX_OK
74     CLEAN_FLAG = True
75     REPORT_FLAG = False
76
77
78 def print_separator(str, count=45):
79     line = ""
80     for i in range(0, count - 1):
81         line += str
82     logger.info("%s" % line)
83
84
85 def source_rc_file():
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
105
106
107 def generate_os_snapshot():
108     os_snapshot.main()
109
110
111 def cleanup():
112     os_clean.main()
113
114
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})
120
121
122 def get_run_dict_if_defined(testname):
123     try:
124         dict = ft_utils.get_dict_by_test(testname)
125         if not dict:
126             logger.error("Cannot get {}'s config options".format(testname))
127         elif 'run' in dict:
128             return dict['run']
129         return None
130     except Exception:
131         logger.exception("Cannot get {}'s config options".format(testname))
132         return None
133
134
135 def run_test(test, tier_name, testcases=None):
136     result_str = "PASS"
137     start = datetime.datetime.now()
138     test_name = test.get_name()
139     logger.info("\n")  # blank line
140     print_separator("=")
141     logger.info("Running test case '%s'..." % test_name)
142     print_separator("=")
143     logger.debug("\n%s" % test)
144     source_rc_file()
145
146     if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
147         generate_os_snapshot()
148
149     flags = (" -t %s" % (test_name))
150     if GlobalVariables.REPORT_FLAG:
151         flags += " -r"
152
153     result = testcase_base.TestcaseBase.EX_RUN_ERROR
154     run_dict = get_run_dict_if_defined(test_name)
155     if run_dict:
156         try:
157             module = importlib.import_module(run_dict['module'])
158             cls = getattr(module, run_dict['class'])
159             test_case = cls()
160
161             try:
162                 kwargs = run_dict['args']
163                 result = test_case.run(**kwargs)
164             except KeyError:
165                 result = test_case.run()
166             if result == testcase_base.TestcaseBase.EX_OK:
167                 if GlobalVariables.REPORT_FLAG:
168                     test_case.push_to_db()
169                 result = test_case.check_criteria()
170         except ImportError:
171             logger.exception("Cannot import module {}".format(
172                 run_dict['module']))
173         except AttributeError:
174             logger.exception("Cannot get class {}".format(
175                 run_dict['class']))
176     else:
177         cmd = ("%s%s" % (EXEC_SCRIPT, flags))
178         logger.info("Executing command {} because {} "
179                     "doesn't implement the new framework".format(
180                         cmd, test_name))
181         result = ft_utils.execute_command(cmd)
182
183     if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
184         cleanup()
185
186     end = datetime.datetime.now()
187     duration = (end - start).seconds
188     duration_str = ("%02d:%02d" % divmod(duration, 60))
189     logger.info("Test execution time: %s" % duration_str)
190
191     if result != 0:
192         logger.error("The test case '%s' failed. " % test_name)
193         GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
194         result_str = "FAIL"
195
196         if test.is_blocking():
197             if not testcases or testcases == "all":
198                 # if it is a single test we don't print the whole results table
199                 update_test_info(test_name, result_str, duration_str)
200                 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
201             raise BlockingTestFailed("The test case {} failed and is blocking"
202                                      .format(test.get_name()))
203
204     update_test_info(test_name, result_str, duration_str)
205
206
207 def run_tier(tier):
208     tier_name = tier.get_name()
209     tests = tier.get_tests()
210     if tests is None or len(tests) == 0:
211         logger.info("There are no supported test cases in this tier "
212                     "for the given scenario")
213         return 0
214     logger.info("\n\n")  # blank line
215     print_separator("#")
216     logger.info("Running tier '%s'" % tier_name)
217     print_separator("#")
218     logger.debug("\n%s" % tier)
219     for test in tests:
220         run_test(test, tier_name)
221
222
223 def run_all(tiers):
224     summary = ""
225     tiers_to_run = []
226
227     for tier in tiers.get_tiers():
228         if (len(tier.get_tests()) != 0 and
229                 re.search(CONST.CI_LOOP, tier.get_ci_loop()) is not None):
230             tiers_to_run.append(tier)
231             summary += ("\n    - %s:\n\t   %s"
232                         % (tier.get_name(),
233                            tier.get_test_names()))
234
235     logger.info("Tests to be executed:%s" % summary)
236     GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
237     for tier in tiers_to_run:
238         run_tier(tier)
239
240     generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
241
242
243 def main(**kwargs):
244
245     CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
246     CI_SCENARIO = CONST.DEPLOY_SCENARIO
247
248     file = CONST.functest_testcases_yaml
249     _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
250
251     if kwargs['noclean']:
252         GlobalVariables.CLEAN_FLAG = False
253
254     if kwargs['report']:
255         GlobalVariables.REPORT_FLAG = True
256
257     try:
258         if kwargs['test']:
259             source_rc_file()
260             if _tiers.get_tier(kwargs['test']):
261                 GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(
262                     [_tiers.get_tier(kwargs['test'])])
263                 run_tier(_tiers.get_tier(kwargs['test']))
264             elif _tiers.get_test(kwargs['test']):
265                 run_test(_tiers.get_test(kwargs['test']),
266                          _tiers.get_tier(kwargs['test']),
267                          kwargs['test'])
268             elif kwargs['test'] == "all":
269                 run_all(_tiers)
270             else:
271                 logger.error("Unknown test case or tier '%s', "
272                              "or not supported by "
273                              "the given scenario '%s'."
274                              % (kwargs['test'], CI_SCENARIO))
275                 logger.debug("Available tiers are:\n\n%s"
276                              % _tiers)
277                 return Result.EX_ERROR
278         else:
279             run_all(_tiers)
280     except Exception as e:
281         logger.error(e)
282         GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
283     logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
284     return GlobalVariables.OVERALL_RESULT
285
286
287 if __name__ == '__main__':
288     parser = RunTestsParser()
289     args = parser.parse_args(sys.argv[1:])
290     sys.exit(main(**args).value)