557ba08dd21cc93945706a286d6d0677462c98e0
[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.testcase_base as testcase_base
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     source_rc_file()
128
129     if GlobalVariables.CLEAN_FLAG:
130         generate_os_snapshot()
131
132     flags = (" -t %s" % (test_name))
133     if GlobalVariables.REPORT_FLAG:
134         flags += " -r"
135
136     result = testcase_base.TestcaseBase.EX_RUN_ERROR
137     run_dict = get_run_dict_if_defined(test_name)
138     if run_dict:
139         try:
140             module = importlib.import_module(run_dict['module'])
141             cls = getattr(module, run_dict['class'])
142             test_case = cls()
143             result = test_case.run()
144             if result == testcase_base.TestcaseBase.EX_OK:
145                 if GlobalVariables.REPORT_FLAG:
146                     test_case.push_to_db()
147                 result = test_case.check_criteria()
148         except ImportError:
149             logger.exception("Cannot import module {}".format(
150                 run_dict['module']))
151         except AttributeError:
152             logger.exception("Cannot get class {}".format(
153                 run_dict['class']))
154     else:
155         cmd = ("%s%s" % (EXEC_SCRIPT, flags))
156         logger.info("Executing command {} because {} "
157                     "doesn't implement the new framework".format(
158                         cmd, test_name))
159         result = ft_utils.execute_command(cmd)
160
161     if GlobalVariables.CLEAN_FLAG:
162         cleanup()
163     end = datetime.datetime.now()
164     duration = (end - start).seconds
165     duration_str = ("%02d:%02d" % divmod(duration, 60))
166     logger.info("Test execution time: %s" % duration_str)
167
168     if result != 0:
169         logger.error("The test case '%s' failed. " % test_name)
170         OVERALL_RESULT = -1
171         result_str = "FAIL"
172
173         if test.is_blocking():
174             if not args.test or args.test == "all":
175                 logger.info("This test case is blocking. Aborting overall "
176                             "execution.")
177                 # if it is a single test we don't print the whole results table
178                 update_test_info(test_name, result_str, duration_str)
179                 generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
180             logger.info("Execution exit value: %s" % OVERALL_RESULT)
181             sys.exit(OVERALL_RESULT)
182
183     update_test_info(test_name, result_str, duration_str)
184
185
186 def run_tier(tier):
187     tier_name = tier.get_name()
188     tests = tier.get_tests()
189     if tests is None or len(tests) == 0:
190         logger.info("There are no supported test cases in this tier "
191                     "for the given scenario")
192         return 0
193     logger.info("\n\n")  # blank line
194     print_separator("#")
195     logger.info("Running tier '%s'" % tier_name)
196     print_separator("#")
197     logger.debug("\n%s" % tier)
198     for test in tests:
199         run_test(test, tier_name)
200
201
202 def run_all(tiers):
203     summary = ""
204     BUILD_TAG = ft_constants.CI_BUILD_TAG
205     if BUILD_TAG is not None and re.search("daily", BUILD_TAG) is not None:
206         CI_LOOP = "daily"
207     else:
208         CI_LOOP = "weekly"
209
210     tiers_to_run = []
211
212     for tier in tiers.get_tiers():
213         if (len(tier.get_tests()) != 0 and
214                 re.search(CI_LOOP, tier.get_ci_loop()) is not None):
215             tiers_to_run.append(tier)
216             summary += ("\n    - %s:\n\t   %s"
217                         % (tier.get_name(),
218                            tier.get_test_names()))
219
220     logger.info("Tests to be executed:%s" % summary)
221     GlobalVariables.EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
222     for tier in tiers_to_run:
223         run_tier(tier)
224
225     generate_report.main(GlobalVariables.EXECUTED_TEST_CASES)
226
227
228 def main():
229
230     CI_INSTALLER_TYPE = ft_constants.CI_INSTALLER_TYPE
231     CI_SCENARIO = ft_constants.CI_SCENARIO
232
233     file = ft_constants.FUNCTEST_TESTCASES_YAML
234     _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
235
236     if args.noclean:
237         GlobalVariables.CLEAN_FLAG = False
238
239     if args.report:
240         GlobalVariables.REPORT_FLAG = True
241
242     if args.test:
243         source_rc_file()
244         if _tiers.get_tier(args.test):
245             run_tier(_tiers.get_tier(args.test))
246
247         elif _tiers.get_test(args.test):
248             run_test(_tiers.get_test(args.test), _tiers.get_tier(args.test))
249
250         elif args.test == "all":
251             run_all(_tiers)
252
253         else:
254             logger.error("Unknown test case or tier '%s', or not supported by "
255                          "the given scenario '%s'."
256                          % (args.test, CI_SCENARIO))
257             logger.debug("Available tiers are:\n\n%s"
258                          % _tiers)
259     else:
260         run_all(_tiers)
261
262     logger.info("Execution exit value: %s" % GlobalVariables.OVERALL_RESULT)
263     sys.exit(GlobalVariables.OVERALL_RESULT)
264
265
266 if __name__ == '__main__':
267     main()