Merge "Refactor SFC testcase" into stable/colorado
[functest.git] / 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 os
14 import re
15 import sys
16
17 import functest.ci.generate_report as generate_report
18 import functest.ci.tier_builder as tb
19 from functest.testcases.Controllers.ODL.OpenDaylightTesting import ODLTestCases
20 import functest.utils.functest_logger as ft_logger
21 import functest.utils.functest_utils as ft_utils
22 import functest.utils.openstack_clean as os_clean
23 import functest.utils.openstack_snapshot as os_snapshot
24 import functest.utils.openstack_utils as os_utils
25
26
27 parser = argparse.ArgumentParser()
28 parser.add_argument("-t", "--test", dest="test", action='store',
29                     help="Test case or tier (group of tests) to be executed. "
30                     "It will run all the test if not specified.")
31 parser.add_argument("-n", "--noclean", help="Do not clean OpenStack resources"
32                     " after running each test (default=false).",
33                     action="store_true")
34 parser.add_argument("-r", "--report", help="Push results to database "
35                     "(default=false).", action="store_true")
36 args = parser.parse_args()
37
38
39 """ logging configuration """
40 logger = ft_logger.Logger("run_tests").getLogger()
41
42
43 """ global variables """
44 REPOS_DIR = os.getenv('repos_dir')
45 FUNCTEST_REPO = ("%s/functest/" % REPOS_DIR)
46 EXEC_SCRIPT = ("%sci/exec_test.sh" % FUNCTEST_REPO)
47 CLEAN_FLAG = True
48 REPORT_FLAG = False
49 EXECUTED_TEST_CASES = []
50
51 # This will be the return code of this script. If any of the tests fails,
52 # this variable will change to -1
53 OVERALL_RESULT = 0
54
55
56 def print_separator(str, count=45):
57     line = ""
58     for i in range(0, count - 1):
59         line += str
60     logger.info("%s" % line)
61
62
63 def source_rc_file():
64     rc_file = os.getenv('creds')
65     if not os.path.isfile(rc_file):
66         logger.error("RC file %s does not exist..." % rc_file)
67         sys.exit(1)
68     logger.debug("Sourcing the OpenStack RC file...")
69     os_utils.source_credentials(rc_file)
70
71
72 def generate_os_snapshot():
73     os_snapshot.main()
74
75
76 def cleanup():
77     os_clean.main()
78
79
80 def update_test_info(test_name, result, duration):
81     for test in EXECUTED_TEST_CASES:
82         if test['test_name'] == test_name:
83             test.update({"result": result,
84                          "duration": duration})
85
86
87 def run_test(test, tier_name):
88     global OVERALL_RESULT, EXECUTED_TEST_CASES
89     result_str = "PASS"
90     start = datetime.datetime.now()
91     test_name = test.get_name()
92     logger.info("\n")  # blank line
93     print_separator("=")
94     logger.info("Running test case '%s'..." % test_name)
95     print_separator("=")
96     logger.debug("\n%s" % test)
97
98     if CLEAN_FLAG:
99         generate_os_snapshot()
100
101     flags = (" -t %s" % (test_name))
102     if REPORT_FLAG:
103         flags += " -r"
104
105     if test_name == 'odl':
106         result = ODLTestCases.functest_run()
107         if result and REPORT_FLAG:
108             result = ODLTestCases.push_to_db()
109         result = not result
110     else:
111         cmd = ("%s%s" % (EXEC_SCRIPT, flags))
112         logger.debug("Executing command '%s'" % cmd)
113         result = ft_utils.execute_command(cmd, exit_on_error=False)
114
115     if CLEAN_FLAG:
116         cleanup()
117     end = datetime.datetime.now()
118     duration = (end - start).seconds
119     duration_str = ("%02d:%02d" % divmod(duration, 60))
120     logger.info("Test execution time: %s" % duration_str)
121
122     if result != 0:
123         logger.error("The test case '%s' failed. " % test_name)
124         OVERALL_RESULT = -1
125         result_str = "FAIL"
126
127         if test.is_blocking():
128             if not args.test or args.test == "all":
129                 logger.info("This test case is blocking. Aborting overall "
130                             "execution.")
131                 # if it is a single test we don't print the whole results table
132                 update_test_info(test_name, result_str, duration_str)
133                 generate_report.main(EXECUTED_TEST_CASES)
134             logger.info("Execution exit value: %s" % OVERALL_RESULT)
135             sys.exit(OVERALL_RESULT)
136
137     update_test_info(test_name, result_str, duration_str)
138
139
140 def run_tier(tier):
141     tier_name = tier.get_name()
142     tests = tier.get_tests()
143     if tests is None or len(tests) == 0:
144         logger.info("There are no supported test cases in this tier "
145                     "for the given scenario")
146         return 0
147     logger.info("\n\n")  # blank line
148     print_separator("#")
149     logger.info("Running tier '%s'" % tier_name)
150     print_separator("#")
151     logger.debug("\n%s" % tier)
152     for test in tests:
153         run_test(test, tier_name)
154
155
156 def run_all(tiers):
157     global EXECUTED_TEST_CASES
158     summary = ""
159     BUILD_TAG = os.getenv('BUILD_TAG')
160     if BUILD_TAG is not None and re.search("daily", BUILD_TAG) is not None:
161         CI_LOOP = "daily"
162     else:
163         CI_LOOP = "weekly"
164
165     tiers_to_run = []
166
167     for tier in tiers.get_tiers():
168         if (len(tier.get_tests()) != 0 and
169                 re.search(CI_LOOP, tier.get_ci_loop()) is not None):
170             tiers_to_run.append(tier)
171             summary += ("\n    - %s:\n\t   %s"
172                         % (tier.get_name(),
173                            tier.get_test_names()))
174
175     logger.info("Tests to be executed:%s" % summary)
176     EXECUTED_TEST_CASES = generate_report.init(tiers_to_run)
177     for tier in tiers_to_run:
178         run_tier(tier)
179
180     generate_report.main(EXECUTED_TEST_CASES)
181
182
183 def main():
184     global CLEAN_FLAG
185     global REPORT_FLAG
186
187     CI_INSTALLER_TYPE = os.getenv('INSTALLER_TYPE')
188     CI_SCENARIO = os.getenv('DEPLOY_SCENARIO')
189
190     file = ft_utils.get_testcases_file()
191     _tiers = tb.TierBuilder(CI_INSTALLER_TYPE, CI_SCENARIO, file)
192
193     if args.noclean:
194         CLEAN_FLAG = False
195
196     if args.report:
197         REPORT_FLAG = True
198
199     if args.test:
200         source_rc_file()
201         if _tiers.get_tier(args.test):
202             run_tier(_tiers.get_tier(args.test))
203
204         elif _tiers.get_test(args.test):
205             run_test(_tiers.get_test(args.test), _tiers.get_tier(args.test))
206
207         elif args.test == "all":
208             run_all(_tiers)
209
210         else:
211             logger.error("Unknown test case or tier '%s', or not supported by "
212                          "the given scenario '%s'."
213                          % (args.test, CI_SCENARIO))
214             logger.debug("Available tiers are:\n\n%s"
215                          % _tiers)
216     else:
217         run_all(_tiers)
218
219     logger.info("Execution exit value: %s" % OVERALL_RESULT)
220     sys.exit(OVERALL_RESULT)
221
222 if __name__ == '__main__':
223     main()