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.OSGCTestCase):
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.conf_path = pkg_resources.resource_filename(
46 'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
47 self.functest_test = pkg_resources.resource_filename(
48 'functest', 'opnfv_tests')
49 self.defcore_list = 'openstack/refstack_client/defcore.txt'
50 self.confpath = os.path.join(self.functest_test,
52 self.defcorelist = pkg_resources.resource_filename(
53 'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
56 if ('https' in CONST.__getattribute__('OS_AUTH_URL') and
57 CONST.__getattribute__('OS_INSECURE').lower() == 'true'):
60 def run_defcore(self, conf, testlist):
61 """Run defcore sys command."""
62 cmd = ("refstack-client test {0} -c {1} -v --test-list {2}"
63 .format(self.insecure, conf, testlist))
64 LOGGER.info("Starting Refstack_defcore test case: '%s'.", cmd)
65 ft_utils.execute_command(cmd)
67 def run_defcore_default(self):
68 """Run default defcore sys command."""
69 options = ["-v"] if not self.insecure else ["-v", self.insecure]
70 cmd = (["refstack-client", "test", "-c", self.confpath] +
71 options + ["--test-list", self.defcorelist])
72 LOGGER.info("Starting Refstack_defcore test case: '%s'.", cmd)
74 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
75 "environment.log"), 'w+') as f_env:
77 ("Refstack environment:\n"
78 " SUT: {}\n Scenario: {}\n Node: {}\n Date: {}\n").format(
79 CONST.__getattribute__('INSTALLER_TYPE'),
80 CONST.__getattribute__('DEPLOY_SCENARIO'),
81 CONST.__getattribute__('NODE_NAME'),
82 time.strftime("%a %b %d %H:%M:%S %Z %Y")))
84 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
85 "refstack.log"), 'w+') as f_stdout:
86 subprocess.call(cmd, shell=False, stdout=f_stdout,
87 stderr=subprocess.STDOUT)
89 def parse_refstack_result(self):
90 """Parse Refstact results."""
92 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
93 "refstack.log"), 'r') as logfile:
94 output = logfile.read()
96 for match in re.findall(r"Ran: (\d+) tests in (\d+\.\d{4}) sec.",
99 LOGGER.info("Ran: %s tests in %s sec.", num_tests, match[1])
100 for match in re.findall(r"(- Passed: )(\d+)", output):
101 num_success = match[1]
102 LOGGER.info("".join(match))
103 for match in re.findall(r"(- Skipped: )(\d+)", output):
104 num_skipped = match[1]
105 LOGGER.info("".join(match))
106 for match in re.findall(r"(- Failed: )(\d+)", output):
107 num_failures = match[1]
108 LOGGER.info("".join(match))
109 success_testcases = []
110 for match in re.findall(r"\{0\}(.*?)[. ]*ok", output):
111 success_testcases.append(match)
112 failed_testcases = []
113 for match in re.findall(r"\{0\}(.*?)[. ]*FAILED", output):
114 failed_testcases.append(match)
115 skipped_testcases = []
116 for match in re.findall(r"\{0\}(.*?)[. ]*SKIPPED:", output):
117 skipped_testcases.append(match)
119 num_executed = int(num_tests) - int(num_skipped)
122 self.result = 100 * int(num_success) / int(num_executed)
123 except ZeroDivisionError:
124 LOGGER.error("No test has been executed")
126 self.details = {"tests": int(num_tests),
127 "failures": int(num_failures),
128 "success": success_testcases,
129 "errors": failed_testcases,
130 "skipped": skipped_testcases}
134 LOGGER.info("Testcase %s success_rate is %s%%",
135 self.case_name, self.result)
137 @energy.enable_recording
138 def run(self, **kwargs):
140 Start RefstackClient testcase.
142 used for functest command line,
143 functest testcase run refstack_defcore
145 self.start_time = time.time()
147 if not os.path.exists(conf_utils.REFSTACK_RESULTS_DIR):
148 os.makedirs(conf_utils.REFSTACK_RESULTS_DIR)
151 tempestconf = TempestConf()
152 tempestconf.generate_tempestconf()
153 self.run_defcore_default()
154 self.parse_refstack_result()
155 res = testcase.TestCase.EX_OK
157 LOGGER.exception("Error with run")
158 res = testcase.TestCase.EX_RUN_ERROR
160 self.stop_time = time.time()
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)
170 def main(self, **kwargs):
172 Execute RefstackClient testcase manually.
174 used for manually running,
175 python refstack_client.py -c <tempest_conf_path>
176 --testlist <testlist_path>
177 can generate a reference refstack_tempest.conf by
178 python tempest_conf.py
181 self.confpath = kwargs['config']
182 self.testlist = kwargs['testlist']
183 except KeyError as exc:
184 LOGGER.error("Cannot run refstack client. Please check "
186 return self.EX_RUN_ERROR
189 self.run_defcore(self.confpath, self.testlist)
190 res = testcase.TestCase.EX_OK
191 except Exception as exc:
192 LOGGER.error('Error with run: %s', exc)
193 res = testcase.TestCase.EX_RUN_ERROR
198 class RefstackClientParser(object): # pylint: disable=too-few-public-methods
199 """Command line argument parser helper."""
202 """Initialize helper object."""
203 self.functest_test = pkg_resources.resource_filename(
204 'functest', 'opnfv_tests')
205 self.conf_path = pkg_resources.resource_filename(
207 'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
208 self.defcore_list = pkg_resources.resource_filename(
209 'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
210 self.confpath = os.path.join(self.functest_test,
212 self.defcorelist = os.path.join(self.functest_test,
214 self.parser = argparse.ArgumentParser()
215 self.parser.add_argument(
217 help='the file path of refstack_tempest.conf',
218 default=self.confpath)
219 self.parser.add_argument(
221 help='Specify the file path or URL of a test list text file. '
222 'This test list will contain specific test cases that '
224 default=self.defcorelist)
226 def parse_args(self, argv=None):
227 """Parse command line arguments."""
228 return vars(self.parser.parse_args(argv))
232 """Run RefstackClient testcase with CLI."""
233 logging.basicConfig()
234 refstackclient = RefstackClient()
235 parser = RefstackClientParser()
236 args = parser.parse_args(sys.argv[1:])
238 result = refstackclient.main(**args)
239 if result != testcase.TestCase.EX_OK:
242 return testcase.TestCase.EX_RUN_ERROR