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