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
31 import functest.utils.openstack_utils as os_utils
33 # logging configuration """
34 LOGGER = logging.getLogger(__name__)
37 class RefstackClient(testcase.TestCase):
38 """RefstackClient testcase implementation class."""
40 def __init__(self, **kwargs):
41 """Initialize RefstackClient testcase object."""
42 if "case_name" not in kwargs:
43 kwargs["case_name"] = "refstack_defcore"
44 super(RefstackClient, self).__init__(**kwargs)
45 self.tempestconf = None
46 self.conf_path = pkg_resources.resource_filename(
48 'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
49 self.functest_test = pkg_resources.resource_filename(
50 'functest', 'opnfv_tests')
51 self.defcore_list = 'openstack/refstack_client/defcore.txt'
52 self.confpath = os.path.join(self.functest_test,
54 self.defcorelist = pkg_resources.resource_filename(
55 'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
58 if ('https' in CONST.__getattribute__('OS_AUTH_URL') and
59 CONST.__getattribute__('OS_INSECURE').lower() == 'true'):
62 def generate_conf(self):
63 if not os.path.exists(conf_utils.REFSTACK_RESULTS_DIR):
64 os.makedirs(conf_utils.REFSTACK_RESULTS_DIR)
66 self.tempestconf = TempestConf()
67 self.tempestconf.generate_tempestconf()
69 def run_defcore(self, conf, testlist):
70 """Run defcore sys command."""
71 cmd = ("refstack-client test {0} -c {1} -v --test-list {2}"
72 .format(self.insecure, conf, testlist))
73 LOGGER.info("Starting Refstack_defcore test case: '%s'.", cmd)
74 ft_utils.execute_command(cmd)
76 def run_defcore_default(self):
77 """Run default defcore sys command."""
78 options = ["-v"] if not self.insecure else ["-v", self.insecure]
79 cmd = (["refstack-client", "test", "-c", self.confpath] +
80 options + ["--test-list", self.defcorelist])
81 LOGGER.info("Starting Refstack_defcore test case: '%s'.", cmd)
83 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
84 "environment.log"), 'w+') as f_env:
86 ("Refstack environment:\n"
87 " SUT: {}\n Scenario: {}\n Node: {}\n Date: {}\n").format(
88 CONST.__getattribute__('INSTALLER_TYPE'),
89 CONST.__getattribute__('DEPLOY_SCENARIO'),
90 CONST.__getattribute__('NODE_NAME'),
91 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
93 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
94 "refstack.log"), 'w+') as f_stdout:
95 subprocess.call(cmd, shell=False, stdout=f_stdout,
96 stderr=subprocess.STDOUT)
98 def parse_refstack_result(self):
99 """Parse Refstack results."""
101 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
102 "refstack.log"), 'r') as logfile:
103 output = logfile.read()
105 for match in re.findall(r"Ran: (\d+) tests in (\d+\.\d{4}) sec.",
108 LOGGER.info("Ran: %s tests in %s sec.", num_tests, match[1])
109 for match in re.findall(r"(- Passed: )(\d+)", output):
110 num_success = match[1]
111 LOGGER.info("".join(match))
112 for match in re.findall(r"(- Skipped: )(\d+)", output):
113 num_skipped = match[1]
114 LOGGER.info("".join(match))
115 for match in re.findall(r"(- Failed: )(\d+)", output):
116 num_failures = match[1]
117 LOGGER.info("".join(match))
118 success_testcases = []
119 for match in re.findall(r"\{0\} (.*?)[. ]*ok", output):
120 success_testcases.append(match)
121 failed_testcases = []
122 for match in re.findall(r"\{0\} (.*?)[. ]*FAILED", output):
123 failed_testcases.append(match)
124 skipped_testcases = []
125 for match in re.findall(r"\{0\} (.*?)[. ]*SKIPPED:", output):
126 skipped_testcases.append(match)
128 num_executed = int(num_tests) - int(num_skipped)
131 self.result = 100 * int(num_success) / int(num_executed)
132 except ZeroDivisionError:
133 LOGGER.error("No test has been executed")
135 self.details = {"tests": int(num_tests),
136 "failures": int(num_failures),
137 "success": success_testcases,
138 "errors": failed_testcases,
139 "skipped": skipped_testcases}
143 LOGGER.info("Testcase %s success_rate is %s%%",
144 self.case_name, self.result)
146 @energy.enable_recording
147 def run(self, **kwargs):
149 Start RefstackClient testcase.
151 used for functest command line,
152 functest testcase run refstack_defcore
154 self.start_time = time.time()
157 # Make sure that Tempest is configured
158 if not self.tempestconf:
160 self.run_defcore_default()
161 self.parse_refstack_result()
162 res = testcase.TestCase.EX_OK
164 LOGGER.exception("Error with run")
165 res = testcase.TestCase.EX_RUN_ERROR
167 self.tempestconf.clean()
169 self.stop_time = time.time()
172 def _prep_test(self):
173 """Check that the config file exists."""
174 if not os.path.isfile(self.confpath):
175 LOGGER.error("Conf file not valid: %s", self.confpath)
176 if not os.path.isfile(self.testlist):
177 LOGGER.error("testlist file not valid: %s", self.testlist)
179 def main(self, **kwargs):
181 Execute RefstackClient testcase manually.
183 used for manually running,
184 python refstack_client.py -c <tempest_conf_path>
185 --testlist <testlist_path>
186 can generate a reference refstack_tempest.conf by
187 python tempest_conf.py
190 self.confpath = kwargs['config']
191 self.testlist = kwargs['testlist']
192 except KeyError as exc:
193 LOGGER.error("Cannot run refstack client. Please check "
195 return self.EX_RUN_ERROR
198 self.run_defcore(self.confpath, self.testlist)
199 res = testcase.TestCase.EX_OK
200 except Exception as exc:
201 LOGGER.error('Error with run: %s', exc)
202 res = testcase.TestCase.EX_RUN_ERROR
206 def create_snapshot(self):
208 Run the Tempest cleanup utility to initialize OS state.
209 For details, see https://docs.openstack.org/tempest/latest/cleanup.html
211 :return: TestCase.EX_OK
213 LOGGER.info("Initializing the saved state of the OpenStack deployment")
215 # Make sure that Tempest is configured
216 if not self.tempestconf:
219 os_utils.init_tempest_cleanup(
220 self.tempestconf.DEPLOYMENT_DIR, 'tempest.conf',
221 os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
222 "tempest-cleanup-init.log")
225 return super(RefstackClient, self).create_snapshot()
229 Run the Tempest cleanup utility to delete and destroy OS resources.
230 For details, see https://docs.openstack.org/tempest/latest/cleanup.html
232 LOGGER.info("Destroying the resources created for tempest")
234 os_utils.perform_tempest_cleanup(
235 self.tempestconf.DEPLOYMENT_DIR, 'tempest.conf',
236 os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
237 "tempest-cleanup.log")
240 return super(RefstackClient, self).clean()
243 class RefstackClientParser(object): # pylint: disable=too-few-public-methods
244 """Command line argument parser helper."""
247 """Initialize helper object."""
248 self.functest_test = pkg_resources.resource_filename(
249 'functest', 'opnfv_tests')
250 self.conf_path = pkg_resources.resource_filename(
252 'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
253 self.defcore_list = pkg_resources.resource_filename(
254 'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
255 self.confpath = os.path.join(self.functest_test,
257 self.defcorelist = os.path.join(self.functest_test,
259 self.parser = argparse.ArgumentParser()
260 self.parser.add_argument(
262 help='the file path of refstack_tempest.conf',
263 default=self.confpath)
264 self.parser.add_argument(
266 help='Specify the file path or URL of a test list text file. '
267 'This test list will contain specific test cases that '
269 default=self.defcorelist)
271 def parse_args(self, argv=None):
272 """Parse command line arguments."""
273 return vars(self.parser.parse_args(argv))
277 """Run RefstackClient testcase with CLI."""
278 logging.basicConfig()
279 refstackclient = RefstackClient()
280 parser = RefstackClientParser()
281 args = parser.parse_args(sys.argv[1:])
283 result = refstackclient.main(**args)
284 if result != testcase.TestCase.EX_OK:
287 return testcase.TestCase.EX_RUN_ERROR