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