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 from __future__ import division
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
27 """ logging configuration """
28 logger = logging.getLogger(__name__)
31 class RefstackClient(testcase.OSGCTestCase):
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(
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,
45 self.defcorelist = pkg_resources.resource_filename(
46 'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
48 def run_defcore(self, conf, testlist):
49 logger.debug("Generating test case list...")
51 cmd = ("refstack-client test -c {0} -v --test-list {1}"
52 .format(conf, testlist))
53 ft_utils.execute_command(cmd)
55 def run_defcore_default(self):
56 logger.debug("Generating test case list...")
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)
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")))
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+')
76 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
77 stderr=subprocess.STDOUT, bufsize=1)
80 for line in iter(p.stdout.readline, b''):
83 if re.search("\} tempest\.", line):
84 logger.info(line.replace('\n', ''))
91 def parse_refstack_result(self):
93 with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
94 "refstack.log"), 'r') as logfile:
95 output = logfile.read()
97 for match in re.findall("Ran: (\d+) tests in (\d+\.\d{4}) sec.",
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 + ", "
120 num_executed = int(num_tests) - int(num_skipped)
123 self.result = 100 * int(num_success) / int(num_executed)
124 except ZeroDivisionError:
125 logger.error("No test has been executed")
127 self.details = {"tests": int(num_tests),
128 "failures": int(num_failures),
129 "success": success_testcases,
130 "errors": failed_testcases,
131 "skipped": skipped_testcases}
135 logger.info("Testcase %s success_rate is %s%%"
136 % (self.case_name, self.result))
139 '''used for functest command line,
140 functest testcase run refstack_defcore'''
141 self.start_time = time.time()
143 if not os.path.exists(conf_utils.REFSTACK_RESULTS_DIR):
144 os.makedirs(conf_utils.REFSTACK_RESULTS_DIR)
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
156 self.stop_time = time.time()
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)
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
174 self.confpath = kwargs['config']
175 self.testlist = kwargs['testlist']
176 except KeyError as e:
177 logger.error("Cannot run refstack client. Please check "
179 return self.EX_RUN_ERROR
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
191 class RefstackClientParser(object):
194 self.FUNCTEST_TEST = pkg_resources.resource_filename(
195 'functest', 'opnfv_tests')
196 self.CONF_PATH = pkg_resources.resource_filename(
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,
203 self.defcorelist = os.path.join(self.FUNCTEST_TEST,
205 self.parser = argparse.ArgumentParser()
206 self.parser.add_argument(
208 help='the file path of refstack_tempest.conf',
209 default=self.confpath)
210 self.parser.add_argument(
212 help='Specify the file path or URL of a test list text file. '
213 'This test list will contain specific test cases that '
215 default=self.defcorelist)
217 def parse_args(self, argv=[]):
218 return vars(self.parser.parse_args(argv))
221 if __name__ == '__main__':
222 logging.basicConfig()
223 refstackclient = RefstackClient()
224 parser = RefstackClientParser()
225 args = parser.parse_args(sys.argv[1:])
227 result = refstackclient.main(**args)
228 if result != testcase.TestCase.EX_OK:
231 sys.exit(testcase.TestCase.EX_RUN_ERROR)