Merge "Added unit tests for vping."
[functest.git] / functest / opnfv_tests / openstack / refstack_client / refstack_client.py
1 #!/usr/bin/env python
2 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
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
9 from __future__ import division
10
11
12 import argparse
13 import logging
14 import os
15 import pkg_resources
16 import re
17 import sys
18 import subprocess
19 import time
20
21 from functest.core import testcase
22 from functest.opnfv_tests.openstack.tempest import conf_utils
23 from functest.utils.constants import CONST
24 import functest.utils.functest_utils as ft_utils
25 from tempest_conf import TempestConf
26
27 """ logging configuration """
28 logger = logging.getLogger(__name__)
29
30
31 class RefstackClient(testcase.OSGCTestCase):
32
33     def __init__(self, **kwargs):
34         if "case_name" not in kwargs:
35             kwargs["case_name"] = "refstack_defcore"
36         super(RefstackClient, self).__init__(**kwargs)
37         self.CONF_PATH = pkg_resources.resource_filename(
38             'functest',
39             'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
40         self.FUNCTEST_TEST = pkg_resources.resource_filename(
41             'functest', 'opnfv_tests')
42         self.DEFCORE_LIST = 'openstack/refstack_client/defcore.txt'
43         self.confpath = os.path.join(self.FUNCTEST_TEST,
44                                      self.CONF_PATH)
45         self.defcorelist = pkg_resources.resource_filename(
46             'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
47
48     def run_defcore(self, conf, testlist):
49         logger.debug("Generating test case list...")
50
51         cmd = ("refstack-client test -c {0} -v --test-list {1}"
52                .format(conf, testlist))
53         ft_utils.execute_command(cmd)
54
55     def run_defcore_default(self):
56         logger.debug("Generating test case list...")
57
58         cmd = ("refstack-client test -c {0} -v --test-list {1}"
59                .format(self.confpath, self.defcorelist))
60         logger.info("Starting Refstack_defcore test case: '%s'." % cmd)
61
62         header = ("Refstack environment:\n"
63                   "  SUT: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
64                   (CONST.__getattribute__('INSTALLER_TYPE'),
65                    CONST.__getattribute__('DEPLOY_SCENARIO'),
66                    CONST.__getattribute__('NODE_NAME'),
67                    time.strftime("%a %b %d %H:%M:%S %Z %Y")))
68
69         f_stdout = open(
70             os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
71                          "refstack.log"), 'w+')
72         f_env = open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
73                                   "environment.log"), 'w+')
74         f_env.write(header)
75
76         p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
77                              stderr=subprocess.STDOUT, bufsize=1)
78
79         with p.stdout:
80             for line in iter(p.stdout.readline, b''):
81                 if 'Tests' in line:
82                     break
83                 if re.search("\} tempest\.", line):
84                     logger.info(line.replace('\n', ''))
85                 f_stdout.write(line)
86         p.wait()
87
88         f_stdout.close()
89         f_env.close()
90
91     def parse_refstack_result(self):
92         try:
93             with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
94                                    "refstack.log"), 'r') as logfile:
95                 output = logfile.read()
96
97             for match in re.findall("Ran: (\d+) tests in (\d+\.\d{4}) sec.",
98                                     output):
99                 num_tests = match[0]
100                 logger.info("Ran: %s tests in %s sec." % (num_tests, match[1]))
101             for match in re.findall("(- Passed: )(\d+)", output):
102                 num_success = match[1]
103                 logger.info("".join(match))
104             for match in re.findall("(- Skipped: )(\d+)", output):
105                 num_skipped = match[1]
106                 logger.info("".join(match))
107             for match in re.findall("(- Failed: )(\d+)", output):
108                 num_failures = match[1]
109                 logger.info("".join(match))
110             success_testcases = ""
111             for match in re.findall(r"\{0\}(.*?)[. ]*ok", output):
112                 success_testcases += match + ", "
113             failed_testcases = ""
114             for match in re.findall(r"\{0\}(.*?)[. ]*FAILED", output):
115                 failed_testcases += match + ", "
116             skipped_testcases = ""
117             for match in re.findall(r"\{0\}(.*?)[. ]*SKIPPED:", output):
118                 skipped_testcases += match + ", "
119
120             num_executed = int(num_tests) - int(num_skipped)
121
122             try:
123                 self.result = 100 * int(num_success) / int(num_executed)
124             except ZeroDivisionError:
125                 logger.error("No test has been executed")
126
127             self.details = {"tests": int(num_tests),
128                             "failures": int(num_failures),
129                             "success": success_testcases,
130                             "errors": failed_testcases,
131                             "skipped": skipped_testcases}
132         except Exception:
133             self.result = 0
134
135         logger.info("Testcase %s success_rate is %s%%"
136                     % (self.case_name, self.result))
137
138     def run(self):
139         '''used for functest command line,
140            functest testcase run refstack_defcore'''
141         self.start_time = time.time()
142
143         if not os.path.exists(conf_utils.REFSTACK_RESULTS_DIR):
144             os.makedirs(conf_utils.REFSTACK_RESULTS_DIR)
145
146         try:
147             tempestconf = TempestConf()
148             tempestconf.generate_tempestconf()
149             self.run_defcore_default()
150             self.parse_refstack_result()
151             res = testcase.TestCase.EX_OK
152         except Exception as e:
153             logger.error('Error with run: %s', e)
154             res = testcase.TestCase.EX_RUN_ERROR
155
156         self.stop_time = time.time()
157         return res
158
159     def _prep_test(self):
160         '''Check that the config file exists.'''
161         if not os.path.isfile(self.confpath):
162             logger.error("Conf file not valid: %s" % self.confpath)
163         if not os.path.isfile(self.testlist):
164             logger.error("testlist file not valid: %s" % self.testlist)
165
166     def main(self, **kwargs):
167         '''used for manually running,
168            python refstack_client.py -c <tempest_conf_path>
169            --testlist <testlist_path>
170            can generate a reference refstack_tempest.conf by
171            python tempest_conf.py
172         '''
173         try:
174             self.confpath = kwargs['config']
175             self.testlist = kwargs['testlist']
176         except KeyError as e:
177             logger.error("Cannot run refstack client. Please check "
178                          "%s", e)
179             return self.EX_RUN_ERROR
180         try:
181             self._prep_test()
182             self.run_defcore(self.confpath, self.testlist)
183             res = testcase.TestCase.EX_OK
184         except Exception as e:
185             logger.error('Error with run: %s', e)
186             res = testcase.TestCase.EX_RUN_ERROR
187
188         return res
189
190
191 class RefstackClientParser(object):
192
193     def __init__(self):
194         self.FUNCTEST_TEST = pkg_resources.resource_filename(
195             'functest', 'opnfv_tests')
196         self.CONF_PATH = pkg_resources.resource_filename(
197             'functest',
198             'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
199         self.DEFCORE_LIST = pkg_resources.resource_filename(
200             'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
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 refstack_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     logging.basicConfig()
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)