Print the real testcase duration
[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 enum
13 import importlib
14 import logging
15 import logging.config
16 import os
17 import re
18 import sys
19
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
28
29 # __name__ cannot be used here
30 logger = logging.getLogger('functest.ci.run_tests')
31
32
33 class Result(enum.Enum):
34     EX_OK = os.EX_OK
35     EX_ERROR = -1
36
37
38 class BlockingTestFailed(Exception):
39     pass
40
41
42 class RunTestsParser(object):
43
44     def __init__(self):
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 "
49                                  "if not specified.")
50         self.parser.add_argument("-n", "--noclean", help="Do not clean "
51                                  "OpenStack resources after running each "
52                                  "test (default=false).",
53                                  action="store_true")
54         self.parser.add_argument("-r", "--report", help="Push results to "
55                                  "database (default=false).",
56                                  action="store_true")
57
58     def parse_args(self, argv=[]):
59         return vars(self.parser.parse_args(argv))
60
61
62 class GlobalVariables:
63     EXECUTED_TEST_CASES = []
64     OVERALL_RESULT = Result.EX_OK
65     CLEAN_FLAG = True
66     REPORT_FLAG = False
67
68
69 def print_separator(str, count=45):
70     line = ""
71     for i in range(0, count - 1):
72         line += str
73     logger.info("%s" % line)
74
75
76 def source_rc_file():
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
92
93
94 def generate_os_snapshot():
95     os_snapshot.main()
96
97
98 def cleanup():
99     os_clean.main()
100
101
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})
107
108
109 def get_run_dict(testname):
110     try:
111         dict = ft_utils.get_dict_by_test(testname)
112         if not dict:
113             logger.error("Cannot get {}'s config options".format(testname))
114         elif 'run' in dict:
115             return dict['run']
116         return None
117     except Exception:
118         logger.exception("Cannot get {}'s config options".format(testname))
119         return None
120
121
122 def run_test(test, tier_name, testcases=None):
123     duration = "XX:XX"
124     result_str = "PASS"
125     test_name = test.get_name()
126     logger.info("\n")  # blank line
127     print_separator("=")
128     logger.info("Running test case '%s'..." % test_name)
129     print_separator("=")
130     logger.debug("\n%s" % test)
131     source_rc_file()
132
133     if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
134         generate_os_snapshot()
135
136     flags = (" -t %s" % (test_name))
137     if GlobalVariables.REPORT_FLAG:
138         flags += " -r"
139
140     result = testcase.TestCase.EX_RUN_ERROR
141     run_dict = get_run_dict(test_name)
142     if run_dict:
143         try:
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)
148             try:
149                 kwargs = run_dict['args']
150                 result = test_case.run(**kwargs)
151             except KeyError:
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         except ImportError:
159             logger.exception("Cannot import module {}".format(
160                 run_dict['module']))
161         except AttributeError:
162             logger.exception("Cannot get class {}".format(
163                 run_dict['class']))
164     else:
165         raise Exception("Cannot import the class for the test case.")
166
167     if test.needs_clean() and GlobalVariables.CLEAN_FLAG:
168         cleanup()
169
170     logger.info("Test execution time: %s", duration)
171
172     if result != testcase.TestCase.EX_OK:
173         logger.error("The test case '%s' failed. " % test_name)
174         GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
175         result_str = "FAIL"
176
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()))
184
185     update_test_info(test_name, result_str, duration)
186
187
188 def run_tier(tier):
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")
194         return 0
195     logger.info("\n\n")  # blank line
196     print_separator("#")
197     logger.info("Running tier '%s'" % tier_name)
198     print_separator("#")
199     logger.debug("\n%s" % tier)
200     for test in tests:
201         run_test(test, tier_name)
202
203
204 def run_all(tiers):
205     summary = ""
206     tiers_to_run = []
207
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"
213                         % (tier.get_name(),
214                            tier.get_test_names()))
215
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:
219         run_tier(tier)
220
221     generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
222
223
224 def main(**kwargs):
225
226     CI_INSTALLER_TYPE = CONST.INSTALLER_TYPE
227     CI_SCENARIO = CONST.DEPLOY_SCENARIO
228
229     file = CONST.functest_testcases_yaml
230     _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
231
232     if kwargs['noclean']:
233         GlobalVariables.CLEAN_FLAG = False
234
235     if kwargs['report']:
236         GlobalVariables.REPORT_FLAG = True
237
238     try:
239         if kwargs['test']:
240             source_rc_file()
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']),
248                          kwargs['test'])
249             elif kwargs['test'] == "all":
250                 run_all(_tiers)
251             else:
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"
257                              % _tiers)
258                 return Result.EX_ERROR
259         else:
260             run_all(_tiers)
261     except Exception as e:
262         logger.error(e)
263         GlobalVariables.OVERALL_RESULT = Result.EX_ERROR
264     logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
265     return GlobalVariables.OVERALL_RESULT
266
267
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)