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