Merge "Add case_name as constructor arg"
[functest.git] / functest / opnfv_tests / openstack / refstack_client / refstack_client.py
1 #!/usr/bin/env python
2
3 # matthew.lijun@huawei.com wangwulin@huawei.com
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 import argparse
9 import os
10 import re
11 import sys
12 import subprocess
13 import time
14
15 from functest.core import testcase
16 from functest.opnfv_tests.openstack.tempest import conf_utils
17 from functest.utils.constants import CONST
18 import functest.utils.functest_logger as ft_logger
19 import functest.utils.functest_utils as ft_utils
20 from tempest_conf import TempestConf
21
22 """ logging configuration """
23 logger = ft_logger.Logger("refstack_defcore").getLogger()
24
25
26 class RefstackClient(testcase.TestCase):
27
28     def __init__(self, case_name="refstack_defcore"):
29         super(RefstackClient, self).__init__(case_name)
30         self.FUNCTEST_TEST = CONST.dir_functest_test
31         self.CONF_PATH = CONST.refstack_tempest_conf_path
32         self.DEFCORE_LIST = CONST.refstack_defcore_list
33         self.confpath = os.path.join(self.FUNCTEST_TEST,
34                                      self.CONF_PATH)
35         self.defcorelist = os.path.join(self.FUNCTEST_TEST,
36                                         self.DEFCORE_LIST)
37
38     def source_venv(self):
39
40         cmd = ("cd {0};"
41                ". .venv/bin/activate;"
42                "cd -;".format(CONST.dir_refstack_client))
43         ft_utils.execute_command(cmd)
44
45     def run_defcore(self, conf, testlist):
46         logger.debug("Generating test case list...")
47
48         cmd = ("cd {0};"
49                "./refstack-client test -c {1} -v --test-list {2};"
50                "cd -;".format(CONST.dir_refstack_client,
51                               conf,
52                               testlist))
53         ft_utils.execute_command(cmd)
54
55     def run_defcore_default(self):
56         logger.debug("Generating test case list...")
57
58         cmd = ("cd {0};"
59                "./refstack-client test -c {1} -v --test-list {2};"
60                "cd -;".format(CONST.dir_refstack_client,
61                               self.confpath,
62                               self.defcorelist))
63         logger.info("Starting Refstack_defcore test case: '%s'." % cmd)
64
65         header = ("Refstack environment:\n"
66                   "  SUT: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
67                   (CONST.INSTALLER_TYPE,
68                    CONST.DEPLOY_SCENARIO,
69                    CONST.NODE_NAME,
70                    time.strftime("%a %b %d %H:%M:%S %Z %Y")))
71
72         f_stdout = open(
73             os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
74                          "refstack.log"), 'w+')
75         f_env = open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
76                                   "environment.log"), 'w+')
77         f_env.write(header)
78
79         p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
80                              stderr=subprocess.STDOUT, bufsize=1)
81
82         with p.stdout:
83             for line in iter(p.stdout.readline, b''):
84                 if 'Tests' in line:
85                     break
86                 if re.search("\} tempest\.", line):
87                     logger.info(line.replace('\n', ''))
88                 f_stdout.write(line)
89         p.wait()
90
91         f_stdout.close()
92         f_env.close()
93
94     def parse_refstack_result(self):
95         try:
96             with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
97                                    "refstack.log"), 'r') as logfile:
98                 output = logfile.read()
99
100             for match in re.findall("Ran: (\d+) tests in (\d+\.\d{4}) sec.",
101                                     output):
102                 num_tests = match[0]
103                 logger.info("Ran: %s tests in %s sec." % (num_tests, match[1]))
104             for match in re.findall("(- Passed: )(\d+)", output):
105                 num_success = match[1]
106                 logger.info("".join(match))
107             for match in re.findall("(- Skipped: )(\d+)", output):
108                 num_skipped = match[1]
109                 logger.info("".join(match))
110             for match in re.findall("(- Failed: )(\d+)", output):
111                 num_failures = match[1]
112                 logger.info("".join(match))
113             success_testcases = ""
114             for match in re.findall(r"\{0\}(.*?)[. ]*ok", output):
115                 success_testcases += match + ", "
116             failed_testcases = ""
117             for match in re.findall(r"\{0\}(.*?)[. ]*FAILED", output):
118                 failed_testcases += match + ", "
119             skipped_testcases = ""
120             for match in re.findall(r"\{0\}(.*?)[. ]*SKIPPED:", output):
121                 skipped_testcases += match + ", "
122
123             num_executed = int(num_tests) - int(num_skipped)
124             success_rate = 100 * int(num_success) / int(num_executed)
125
126             self.details = {"tests": int(num_tests),
127                             "failures": int(num_failures),
128                             "success": success_testcases,
129                             "errors": failed_testcases,
130                             "skipped": skipped_testcases}
131         except Exception:
132             success_rate = 0
133
134         self.criteria = ft_utils.check_success_rate(
135             self.case_name, success_rate)
136         logger.info("Testcase %s success_rate is %s%%, is marked as %s"
137                     % (self.case_name, success_rate, self.criteria))
138
139     def run(self):
140         '''used for functest command line,
141            functest testcase run refstack_defcore'''
142         self.start_time = time.time()
143
144         if not os.path.exists(conf_utils.REFSTACK_RESULTS_DIR):
145             os.makedirs(conf_utils.REFSTACK_RESULTS_DIR)
146
147         try:
148             tempestconf = TempestConf()
149             tempestconf.generate_tempestconf()
150             self.source_venv()
151             self.run_defcore_default()
152             self.parse_refstack_result()
153             res = testcase.TestCase.EX_OK
154         except Exception as e:
155             logger.error('Error with run: %s', e)
156             res = testcase.TestCase.EX_RUN_ERROR
157
158         self.stop_time = time.time()
159         return res
160
161     def _prep_test(self):
162         '''Check that the config file exists.'''
163         if not os.path.isfile(self.confpath):
164             logger.error("Conf file not valid: %s" % self.confpath)
165         if not os.path.isfile(self.testlist):
166             logger.error("testlist file not valid: %s" % self.testlist)
167
168     def main(self, **kwargs):
169         '''used for manually running,
170            python refstack_client.py -c <tempest_conf_path>
171            --testlist <testlist_path>
172            can generate a reference tempest.conf by
173            python tempest_conf.py
174         '''
175         try:
176             self.confpath = kwargs['config']
177             self.testlist = kwargs['testlist']
178         except KeyError as e:
179             logger.error("Cannot run refstack client. Please check "
180                          "%s", e)
181             return self.EX_RUN_ERROR
182         try:
183             self.source_venv()
184             self._prep_test()
185             self.run_defcore(self.confpath, self.testlist)
186             res = testcase.TestCase.EX_OK
187         except Exception as e:
188             logger.error('Error with run: %s', e)
189             res = testcase.TestCase.EX_RUN_ERROR
190
191         return res
192
193
194 class RefstackClientParser(testcase.TestCase):
195
196     def __init__(self, case_name=''):
197         super(RefstackClientParser, self).__init__(case_name)
198         self.FUNCTEST_TEST = CONST.dir_functest_test
199         self.CONF_PATH = CONST.refstack_tempest_conf_path
200         self.DEFCORE_LIST = CONST.refstack_defcore_list
201         self.confpath = os.path.join(self.FUNCTEST_TEST,
202                                      self.CONF_PATH)
203         self.defcorelist = os.path.join(self.FUNCTEST_TEST,
204                                         self.DEFCORE_LIST)
205         self.parser = argparse.ArgumentParser()
206         self.parser.add_argument(
207             '-c', '--config',
208             help='the file path of tempest.conf',
209             default=self.confpath)
210         self.parser.add_argument(
211             '-t', '--testlist',
212             help='Specify the file path or URL of a test list text file. '
213                  'This test list will contain specific test cases that '
214                  'should be tested.',
215             default=self.defcorelist)
216
217     def parse_args(self, argv=[]):
218         return vars(self.parser.parse_args(argv))
219
220
221 if __name__ == '__main__':
222     refstackclient = RefstackClient()
223     parser = RefstackClientParser()
224     args = parser.parse_args(sys.argv[1:])
225     try:
226         result = refstackclient.main(**args)
227         if result != testcase.TestCase.EX_OK:
228             sys.exit(result)
229     except Exception:
230         sys.exit(testcase.TestCase.EX_RUN_ERROR)