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