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