Merge "Bugfix: fix the wrong script path for healthcheck."
[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 datetime
12 import importlib
13 import os
14 import re
15 import sys
16
17 import argparse
18
19 import functest.ci.generate_report as generate_report
20 import functest.ci.tier_builder as tb
21 import functest.core.TestCasesBase as TestCasesBase
22 import functest.utils.functest_logger as ft_logger
23 import functest.utils.functest_utils as ft_utils
24 import functest.utils.functest_constants as ft_constants
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
29
30 parser = argparse.ArgumentParser()
31 parser.add_argument("-t", "--test", dest="test", action='store',
32                     help="Test case or tier (group of tests) to be executed. "
33                     "It will run all the test if not specified.")
34 parser.add_argument("-n", "--noclean", help="Do not clean OpenStack resources"
35                     " after running each test (default=false).",
36                     action="store_true")
37 parser.add_argument("-r", "--report", help="Push results to database "
38                     "(default=false).", action="store_true")
39 args = parser.parse_args()
40
41
42 """ logging configuration """
43 logger = ft_logger.Logger("run_tests").getLogger()
44
45
46 """ global variables """
47 EXEC_SCRIPT = ("%s/functest/ci/exec_test.sh" % ft_constants.FUNCTEST_REPO_DIR)
48
49 # This will be the return code of this script. If any of the tests fails,
50 # this variable will change to -1
51
52
53 class GlobalVariables:
54     EXECUTED_TEST_CASES = []
55     OVERALL_RESULT = 0
56     CLEAN_FLAG = True
57     REPORT_FLAG = False
58
59
60 def print_separator(str, count=45):
61     line = ""
62     for i in range(0, count - 1):
63         line += str
64     logger.info("%s" % line)
65
66
67 def source_rc_file():
68     rc_file = ft_constants.OPENSTACK_CREDS
69     if not os.path.isfile(rc_file):
70         logger.error("RC file %s does not exist..." % rc_file)
71         sys.exit(1)
72     logger.debug("Sourcing the OpenStack RC file...")
73     creds = os_utils.source_credentials(rc_file)
74     for key, value in creds.iteritems():
75         if re.search("OS_", key):
76             if key == 'OS_AUTH_URL':
77                 ft_constants.OS_AUTH_URL = value
78             elif key == 'OS_USERNAME':
79                 ft_constants.OS_USERNAME = value
80             elif key == 'OS_TENANT_NAME':
81                 ft_constants.OS_TENANT_NAME = value
82             elif key == 'OS_PASSWORD':
83                 ft_constants.OS_PASSWORD = value
84     logger.debug("OS_AUTH_URL:%s" % ft_constants.OS_AUTH_URL)
85     logger.debug("OS_USERNAME:%s" % ft_constants.OS_USERNAME)
86     logger.debug("OS_TENANT_NAME:%s" % ft_constants.OS_TENANT_NAME)
87     logger.debug("OS_PASSWORD:%s" % ft_constants.OS_PASSWORD)
88
89
90 def generate_os_snapshot():
91     os_snapshot.main()
92
93
94 def cleanup():
95     os_clean.main()
96
97
98 def update_test_info(test_name, result, duration):
99     for test in GlobalVariables.EXECUTED_TEST_CASES:
100         if test['test_name'] == test_name:
101             test.update({"result": result,
102                          "duration": duration})
103
104
105 def get_run_dict_if_defined(testname):
106     try:
107         dict = ft_utils.get_dict_by_test(testname)
108         if not dict:
109             logger.error("Cannot get {}'s config options".format(testname))
110         elif 'run' in dict:
111             return dict['run']
112         return None
113     except Exception:
114         logger.exception("Cannot get {}'s config options".format(testname))
115         return None
116
117
118 def run_test(test, tier_name):
119     result_str = "PASS"
120     start = datetime.datetime.now()
121     test_name = test.get_name()
122     logger.info("\n")  # blank line
123     print_separator("=")
124     logger.info("Running test case '%s'..." % test_name)
125     print_separator("=")
126     logger.debug("\n%s" % test)
127
128     if GlobalVariables.CLEAN_FLAG:
129         generate_os_snapshot()
130
131     flags = (" -t %s" % (test_name))
132     if GlobalVariables.REPORT_FLAG:
133         flags += " -r"
134
135     result = TestCasesBase.TestCasesBase.EX_RUN_ERROR
136     run_dict = get_run_dict_if_defined(test_name)
137     if run_dict:
138         try:
139             module = importlib.import_module(run_dict['module'])
140             cls = getattr(module, run_dict['class'])
141             test_case = cls()
142             result = test_case.run()
143
144             if result != TestCasesBase.TestCasesBase.EX_SKIP and \
145                GlobalVariables.REPORT_FLAG:
146                 test_case.push_to_db()
147         except ImportError:
148             logger.exception("Cannot import module {}".format(
149                 run_dict['module']))
150         except AttributeError:
151             logger.exception("Cannot get class {}".format(
152                 run_dict['class']))
153     else:
154         cmd = ("%s%s" % (EXEC_SCRIPT, flags))
155         logger.info("Executing command {} because {} "
156                     "doesn't implement the new framework".format(
157                         cmd, test_name))
158         result = ft_utils.execute_command(cmd)
159
160     if GlobalVariables.CLEAN_FLAG:
161         cleanup()
162     end = datetime.datetime.now()
163     duration = (end - start).seconds
164     duration_str = ("%02d:%02d" % divmod(duration, 60))
165     logger.info("Test execution time: %s" % duration_str)
166
167     if result != 0:
168         logger.error("The test case '%s' failed. " % test_name)
169         OVERALL_RESULT = -1
170         result_str = "FAIL"
171
172         if test.is_blocking():
173             if not args.test or args.test == "all":
174                 logger.info("This test case is blocking. Aborting overall "
175                             "execution.")
176                 # if it is a single test we don't print the whole results table
177                 update_test_info(test_name, result_str, duration_str)
178                 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
179             logger.info("Execution exit value: %s" % OVERALL_RESULT)
180             sys.exit(OVERALL_RESULT)
181
182     update_test_info(test_name, result_str, duration_str)
183
184
185 def run_tier(tier):
186     tier_name = tier.get_name()
187     tests = tier.get_tests()
188     if tests is None or len(tests) == 0:
189         logger.info("There are no supported test cases in this tier "
190                     "for the given scenario")
191         return 0
192     logger.info("\n\n")  # blank line
193     print_separator("#")
194     logger.info("Running tier '%s'" % tier_name)
195     print_separator("#")
196     logger.debug("\n%s" % tier)
197     for test in tests:
198         run_test(test, tier_name)
199
200
201 def run_all(tiers):
202     summary = ""
203     BUILD_TAG = ft_constants.CI_BUILD_TAG
204     if BUILD_TAG is not None and re.search("daily", BUILD_TAG) is not None:
205         CI_LOOP = "daily"
206     else:
207         CI_LOOP = "weekly"
208
209     tiers_to_run = []
210
211     for tier in tiers.get_tiers():
212         if (len(tier.get_tests()) != 0 and
213                 re.search(CI_LOOP, tier.get_ci_loop()) is not None):
214             tiers_to_run.append(tier)
215             summary += ("\n    - %s:\n\t   %s"
216                         % (tier.get_name(),
217                            tier.get_test_names()))
218
219     logger.info("Tests to be executed:%s" % summary)
220     GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
221     for tier in tiers_to_run:
222         run_tier(tier)
223
224     generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
225
226
227 def main():
228
229     CI_INSTALLER_TYPE = ft_constants.CI_INSTALLER_TYPE
230     CI_SCENARIO = ft_constants.CI_SCENARIO
231
232     file = ft_constants.FUNCTEST_TESTCASES_YAML
233     _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
234
235     if args.noclean:
236         GlobalVariables.CLEAN_FLAG = False
237
238     if args.report:
239         GlobalVariables.REPORT_FLAG = True
240
241     if args.test:
242         source_rc_file()
243         if _tiers.get_tier(args.test):
244             run_tier(_tiers.get_tier(args.test))
245
246         elif _tiers.get_test(args.test):
247             run_test(_tiers.get_test(args.test), _tiers.get_tier(args.test))
248
249         elif args.test == "all":
250             run_all(_tiers)
251
252         else:
253             logger.error("Unknown test case or tier '%s', or not supported by "
254                          "the given scenario '%s'."
255                          % (args.test, CI_SCENARIO))
256             logger.debug("Available tiers are:\n\n%s"
257                          % _tiers)
258     else:
259         run_all(_tiers)
260
261     logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
262     sys.exit(GlobalVariables.OVERALL_RESULT)
263
264
265 if __name__ == '__main__':
266     main()