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
9 """Refstack client testcase implemenation."""
11 from __future__ import division
24 from functest.core import testcase
25 from functest.energy import energy
26 from functest.opnfv_tests.openstack.refstack_client.tempest_conf \
28 from functest.opnfv_tests.openstack.tempest import conf_utils
29 from functest.utils.constants import CONST
30 import functest.utils.functest_utils as ft_utils
32 # logging configuration """
33 LOGGER = logging.getLogger(__name__)
36 class RefstackClient(testcase.TestCase):
37 """RefstackClient testcase implementation class."""
39 def __init__(self, **kwargs):
40 """Initialize RefstackClient testcase object."""
41 if "case_name" not in kwargs:
42 kwargs["case_name"] = "refstack_defcore"
43 super(RefstackClient, self).__init__(**kwargs)
44 self.tempestconf = None
45 self.conf_path = pkg_resources.resource_filename(
47 'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
48 self.functest_test = pkg_resources.resource_filename(
49 'functest', 'opnfv_tests')
50 self.defcore_list = 'openstack/refstack_client/defcore.txt'
51 self.confpath = os.path.join(self.functest_test,
53 self.defcorelist = pkg_resources.resource_filename(
54 'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
57 if ('https' in CONST.__getattribute__('OS_AUTH_URL') and
58 CONST.__getattribute__('OS_INSECURE').lower() == 'true'):
61 def generate_conf(self):
62 if not os.path.exists(conf_utils.REFSTACK_RESULTS_DIR):
63 os.makedirs(conf_utils.REFSTACK_RESULTS_DIR)
65 self.tempestconf = TempestConf()
66 self.tempestconf.generate_tempestconf()
68 def run_defcore(self, conf, testlist):
69 """Run defcore sys command."""
70 cmd = ("refstack-client test {0} -c {1} -v --test-list {2}"
71 .format(self.insecure, conf, testlist))
72 LOGGER.info("Starting Refstack_defcore test case: '%s'.", cmd)
73 ft_utils.execute_command(cmd)
75 def run_defcore_default(self):
76 """Run default defcore sys command."""
77 options = ["-v"] if not self.insecure else ["-v", self.insecure]
78 cmd = (["refstack-client", "test", "-c", self.confpath] +
79 options + ["--test-list", self.defcorelist])
80 LOGGER.info("Starting Refstack_defcore test case: '%s'.", cmd)
82 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
83 "environment.log"), 'w+') as f_env:
85 ("Refstack environment:\n"
86 " SUT: {}\n Scenario: {}\n Node: {}\n Date: {}\n").format(
87 CONST.__getattribute__('INSTALLER_TYPE'),
88 CONST.__getattribute__('DEPLOY_SCENARIO'),
89 CONST.__getattribute__('NODE_NAME'),
90 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
92 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
93 "refstack.log"), 'w+') as f_stdout:
94 subprocess.call(cmd, shell=False, stdout=f_stdout,
95 stderr=subprocess.STDOUT)
97 def parse_refstack_result(self):
98 """Parse Refstack results."""
100 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
101 "refstack.log"), 'r') as logfile:
102 for line in logfile.readlines():
105 if re.search(r"\} tempest\.", line):
106 LOGGER.info(line.replace('\n', ''))
108 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
109 "refstack.log"), 'r') as logfile:
110 output = logfile.read()
112 for match in re.findall(r"Ran: (\d+) tests in (\d+\.\d{4}) sec.",
115 LOGGER.info("Ran: %s tests in %s sec.", num_tests, match[1])
116 for match in re.findall(r"(- Passed: )(\d+)", output):
117 num_success = match[1]
118 LOGGER.info("".join(match))
119 for match in re.findall(r"(- Skipped: )(\d+)", output):
120 num_skipped = match[1]
121 LOGGER.info("".join(match))
122 for match in re.findall(r"(- Failed: )(\d+)", output):
123 num_failures = match[1]
124 LOGGER.info("".join(match))
125 success_testcases = []
126 for match in re.findall(r"\{0\} (.*?)[. ]*ok", output):
127 success_testcases.append(match)
128 failed_testcases = []
129 for match in re.findall(r"\{0\} (.*?)[. ]*FAILED", output):
130 failed_testcases.append(match)
131 skipped_testcases = []
132 for match in re.findall(r"\{0\} (.*?)[. ]*SKIPPED:", output):
133 skipped_testcases.append(match)
135 num_executed = int(num_tests) - int(num_skipped)
138 self.result = 100 * int(num_success) / int(num_executed)
139 except ZeroDivisionError:
140 LOGGER.error("No test has been executed")
142 self.details = {"tests": int(num_tests),
143 "failures": int(num_failures),
144 "success": success_testcases,
145 "errors": failed_testcases,
146 "skipped": skipped_testcases}
150 LOGGER.info("Testcase %s success_rate is %s%%",
151 self.case_name, self.result)
153 @energy.enable_recording
154 def run(self, **kwargs):
156 Start RefstackClient testcase.
158 used for functest command line,
159 functest testcase run refstack_defcore
161 self.start_time = time.time()
164 # Make sure that Tempest is configured
165 if not self.tempestconf:
167 self.run_defcore_default()
168 self.parse_refstack_result()
169 res = testcase.TestCase.EX_OK
171 LOGGER.exception("Error with run")
172 res = testcase.TestCase.EX_RUN_ERROR
174 self.tempestconf.clean()
176 self.stop_time = time.time()
179 def _prep_test(self):
180 """Check that the config file exists."""
181 if not os.path.isfile(self.confpath):
182 LOGGER.error("Conf file not valid: %s", self.confpath)
183 if not os.path.isfile(self.testlist):
184 LOGGER.error("testlist file not valid: %s", self.testlist)
186 def main(self, **kwargs):
188 Execute RefstackClient testcase manually.
190 used for manually running,
191 python refstack_client.py -c <tempest_conf_path>
192 --testlist <testlist_path>
193 can generate a reference refstack_tempest.conf by
194 python tempest_conf.py
197 self.confpath = kwargs['config']
198 self.testlist = kwargs['testlist']
199 except KeyError as exc:
200 LOGGER.error("Cannot run refstack client. Please check "
202 return self.EX_RUN_ERROR
205 self.run_defcore(self.confpath, self.testlist)
206 res = testcase.TestCase.EX_OK
207 except Exception as exc:
208 LOGGER.error('Error with run: %s', exc)
209 res = testcase.TestCase.EX_RUN_ERROR
214 class RefstackClientParser(object): # pylint: disable=too-few-public-methods
215 """Command line argument parser helper."""
218 """Initialize helper object."""
219 self.functest_test = pkg_resources.resource_filename(
220 'functest', 'opnfv_tests')
221 self.conf_path = pkg_resources.resource_filename(
223 'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
224 self.defcore_list = pkg_resources.resource_filename(
225 'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
226 self.confpath = os.path.join(self.functest_test,
228 self.defcorelist = os.path.join(self.functest_test,
230 self.parser = argparse.ArgumentParser()
231 self.parser.add_argument(
233 help='the file path of refstack_tempest.conf',
234 default=self.confpath)
235 self.parser.add_argument(
237 help='Specify the file path or URL of a test list text file. '
238 'This test list will contain specific test cases that '
240 default=self.defcorelist)
242 def parse_args(self, argv=None):
243 """Parse command line arguments."""
244 return vars(self.parser.parse_args(argv))
248 """Run RefstackClient testcase with CLI."""
249 logging.basicConfig()
250 refstackclient = RefstackClient()
251 parser = RefstackClientParser()
252 args = parser.parse_args(sys.argv[1:])
254 result = refstackclient.main(**args)
255 if result != testcase.TestCase.EX_OK:
258 return testcase.TestCase.EX_RUN_ERROR