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