Merge "Enable refstack work on https without SSL checks"
[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         self.insecure = ''
48         if ('https' in CONST.__getattribute__('OS_AUTH_URL') and
49                 CONST.__getattribute__('OS_INSECURE').lower() == 'true'):
50             self.insecure = '-k'
51
52     def run_defcore(self, conf, testlist):
53         cmd = ("refstack-client test {0} -c {1} -v --test-list {2}"
54                .format(self.insecure, conf, testlist))
55         logger.info("Starting Refstack_defcore test case: '%s'." % cmd)
56         ft_utils.execute_command(cmd)
57
58     def run_defcore_default(self):
59         cmd = ("refstack-client test {0} -c {1} -v --test-list {2}"
60                .format(self.insecure, self.confpath, self.defcorelist))
61         logger.info("Starting Refstack_defcore test case: '%s'." % cmd)
62
63         header = ("Refstack environment:\n"
64                   "  SUT: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
65                   (CONST.__getattribute__('INSTALLER_TYPE'),
66                    CONST.__getattribute__('DEPLOY_SCENARIO'),
67                    CONST.__getattribute__('NODE_NAME'),
68                    time.strftime("%a %b %d %H:%M:%S %Z %Y")))
69
70         f_stdout = open(
71             os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
72                          "refstack.log"), 'w+')
73         f_env = open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
74                                   "environment.log"), 'w+')
75         f_env.write(header)
76
77         p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
78                              stderr=subprocess.STDOUT, bufsize=1)
79
80         with p.stdout:
81             for line in iter(p.stdout.readline, b''):
82                 if 'Tests' in line:
83                     break
84                 if re.search("\} tempest\.", line):
85                     logger.info(line.replace('\n', ''))
86                 f_stdout.write(line)
87         p.wait()
88
89         f_stdout.close()
90         f_env.close()
91
92     def parse_refstack_result(self):
93         try:
94             with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
95                                    "refstack.log"), 'r') as logfile:
96                 output = logfile.read()
97
98             for match in re.findall("Ran: (\d+) tests in (\d+\.\d{4}) sec.",
99                                     output):
100                 num_tests = match[0]
101                 logger.info("Ran: %s tests in %s sec." % (num_tests, match[1]))
102             for match in re.findall("(- Passed: )(\d+)", output):
103                 num_success = match[1]
104                 logger.info("".join(match))
105             for match in re.findall("(- Skipped: )(\d+)", output):
106                 num_skipped = match[1]
107                 logger.info("".join(match))
108             for match in re.findall("(- Failed: )(\d+)", output):
109                 num_failures = match[1]
110                 logger.info("".join(match))
111             success_testcases = ""
112             for match in re.findall(r"\{0\}(.*?)[. ]*ok", output):
113                 success_testcases += match + ", "
114             failed_testcases = ""
115             for match in re.findall(r"\{0\}(.*?)[. ]*FAILED", output):
116                 failed_testcases += match + ", "
117             skipped_testcases = ""
118             for match in re.findall(r"\{0\}(.*?)[. ]*SKIPPED:", output):
119                 skipped_testcases += match + ", "
120
121             num_executed = int(num_tests) - int(num_skipped)
122
123             try:
124                 self.result = 100 * int(num_success) / int(num_executed)
125             except ZeroDivisionError:
126                 logger.error("No test has been 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             self.result = 0
135
136         logger.info("Testcase %s success_rate is %s%%"
137                     % (self.case_name, self.result))
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.run_defcore_default()
151             self.parse_refstack_result()
152             res = testcase.TestCase.EX_OK
153         except Exception as e:
154             logger.error('Error with run: %s', e)
155             res = testcase.TestCase.EX_RUN_ERROR
156
157         self.stop_time = time.time()
158         return res
159
160     def _prep_test(self):
161         '''Check that the config file exists.'''
162         if not os.path.isfile(self.confpath):
163             logger.error("Conf file not valid: %s" % self.confpath)
164         if not os.path.isfile(self.testlist):
165             logger.error("testlist file not valid: %s" % self.testlist)
166
167     def main(self, **kwargs):
168         '''used for manually running,
169            python refstack_client.py -c <tempest_conf_path>
170            --testlist <testlist_path>
171            can generate a reference refstack_tempest.conf by
172            python tempest_conf.py
173         '''
174         try:
175             self.confpath = kwargs['config']
176             self.testlist = kwargs['testlist']
177         except KeyError as e:
178             logger.error("Cannot run refstack client. Please check "
179                          "%s", e)
180             return self.EX_RUN_ERROR
181         try:
182             self._prep_test()
183             self.run_defcore(self.confpath, self.testlist)
184             res = testcase.TestCase.EX_OK
185         except Exception as e:
186             logger.error('Error with run: %s', e)
187             res = testcase.TestCase.EX_RUN_ERROR
188
189         return res
190
191
192 class RefstackClientParser(object):
193
194     def __init__(self):
195         self.FUNCTEST_TEST = pkg_resources.resource_filename(
196             'functest', 'opnfv_tests')
197         self.CONF_PATH = pkg_resources.resource_filename(
198             'functest',
199             'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
200         self.DEFCORE_LIST = pkg_resources.resource_filename(
201             'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
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 refstack_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 def main():
223     logging.basicConfig()
224     refstackclient = RefstackClient()
225     parser = RefstackClientParser()
226     args = parser.parse_args(sys.argv[1:])
227     try:
228         result = refstackclient.main(**args)
229         if result != testcase.TestCase.EX_OK:
230             return result
231     except Exception:
232         return testcase.TestCase.EX_RUN_ERROR