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