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