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