3 # Copyright (c) 2016 Orange and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 """Define classes required to run ODL suites.
12 It has been designed for any context. But helpers are given for
13 running test suites in OPNFV environment.
19 from __future__ import division
30 from robot.errors import RobotError
32 from robot.utils.robottime import timestamp_to_secs
33 from six import StringIO
34 from six.moves import urllib
36 from functest.core import testcase
37 from functest.utils import constants
38 import functest.utils.openstack_utils as op_utils
40 __author__ = "Cedric Ollivier <cedric.ollivier@orange.com>"
43 class ODLResultVisitor(robot.api.ResultVisitor):
44 """Visitor to get result details."""
49 def visit_test(self, test):
51 output['name'] = test.name
52 output['parent'] = test.parent.name
53 output['status'] = test.status
54 output['starttime'] = test.starttime
55 output['endtime'] = test.endtime
56 output['critical'] = test.critical
57 output['text'] = test.message
58 output['elapsedtime'] = test.elapsedtime
59 self._data.append(output)
62 """Get the details of the result."""
66 class ODLTests(testcase.TestCase):
67 """ODL test runner."""
69 odl_test_repo = os.path.join(
70 constants.CONST.__getattribute__('dir_repos'), 'odl_test')
71 neutron_suite_dir = os.path.join(odl_test_repo,
72 "csit/suites/openstack/neutron")
73 basic_suite_dir = os.path.join(odl_test_repo,
74 "csit/suites/integration/basic")
75 default_suites = [basic_suite_dir, neutron_suite_dir]
76 res_dir = os.path.join(
77 constants.CONST.__getattribute__('dir_results'), 'odl')
78 __logger = logging.getLogger(__name__)
81 def set_robotframework_vars(cls, odlusername="admin", odlpassword="admin"):
82 """Set credentials in csit/variables/Variables.py.
85 True if credentials are set.
88 odl_variables_files = os.path.join(cls.odl_test_repo,
89 'csit/variables/Variables.py')
91 for line in fileinput.input(odl_variables_files,
93 print(re.sub("AUTH = .*",
94 ("AUTH = [u'" + odlusername + "', u'" +
98 except Exception as ex: # pylint: disable=broad-except
99 cls.__logger.error("Cannot set ODL creds: %s", str(ex))
102 def parse_results(self):
103 """Parse output.xml and get the details in it."""
104 xml_file = os.path.join(self.res_dir, 'output.xml')
105 result = robot.api.ExecutionResult(xml_file)
106 visitor = ODLResultVisitor()
107 result.visit(visitor)
109 self.result = 100 * (
110 result.suite.statistics.critical.passed /
111 result.suite.statistics.critical.total)
112 except ZeroDivisionError:
113 self.__logger.error("No test has been run")
114 self.start_time = timestamp_to_secs(result.suite.starttime)
115 self.stop_time = timestamp_to_secs(result.suite.endtime)
117 self.details['description'] = result.suite.name
118 self.details['tests'] = visitor.get_data()
120 def main(self, suites=None, **kwargs):
121 """Run the test suites
123 It has been designed to be called in any context.
124 It requires the following keyword arguments:
138 * set all RobotFramework_variables,
139 * create the output directories if required,
140 * get the results in output.xml,
141 * delete temporary files.
144 kwargs: Arbitrary keyword arguments.
147 EX_OK if all suites ran well.
148 EX_RUN_ERROR otherwise.
152 suites = self.default_suites
153 odlusername = kwargs['odlusername']
154 odlpassword = kwargs['odlpassword']
155 osauthurl = kwargs['osauthurl']
156 keystoneip = urllib.parse.urlparse(osauthurl).hostname
157 variables = ['KEYSTONE:' + keystoneip,
158 'NEUTRON:' + kwargs['neutronip'],
159 'OS_AUTH_URL:"' + osauthurl + '"',
160 'OSUSERNAME:"' + kwargs['osusername'] + '"',
161 'OSTENANTNAME:"' + kwargs['ostenantname'] + '"',
162 'OSPASSWORD:"' + kwargs['ospassword'] + '"',
163 'ODL_SYSTEM_IP:' + kwargs['odlip'],
164 'PORT:' + kwargs['odlwebport'],
165 'RESTCONFPORT:' + kwargs['odlrestconfport']]
166 except KeyError as ex:
167 self.__logger.error("Cannot run ODL testcases. Please check "
169 return self.EX_RUN_ERROR
170 if self.set_robotframework_vars(odlusername, odlpassword):
172 os.makedirs(self.res_dir)
173 except OSError as ex:
174 if ex.errno != errno.EEXIST:
175 self.__logger.exception(
176 "Cannot create %s", self.res_dir)
177 return self.EX_RUN_ERROR
178 output_dir = os.path.join(self.res_dir, 'output.xml')
180 robot.run(*suites, variable=variables, output=output_dir,
181 log='NONE', report='NONE', stdout=stream)
182 self.__logger.info("\n" + stream.getvalue())
183 self.__logger.info("ODL results were successfully generated")
186 self.__logger.info("ODL results were successfully parsed")
187 except RobotError as ex:
188 self.__logger.error("Run tests before publishing: %s",
190 return self.EX_RUN_ERROR
193 return self.EX_RUN_ERROR
195 def run(self, **kwargs):
196 """Run suites in OPNFV environment
198 It basically check env vars to call main() with the keywords
202 kwargs: Arbitrary keyword arguments.
205 EX_OK if all suites ran well.
206 EX_RUN_ERROR otherwise.
209 suites = self.default_suites
211 suites = kwargs["suites"]
214 neutron_url = op_utils.get_endpoint(service_type='network')
215 kwargs = {'neutronip': urllib.parse.urlparse(neutron_url).hostname}
216 kwargs['odlip'] = kwargs['neutronip']
217 kwargs['odlwebport'] = '8080'
218 kwargs['odlrestconfport'] = '8181'
219 kwargs['odlusername'] = 'admin'
220 kwargs['odlpassword'] = 'admin'
221 installer_type = None
222 if 'INSTALLER_TYPE' in os.environ:
223 installer_type = os.environ['INSTALLER_TYPE']
224 kwargs['osusername'] = os.environ['OS_USERNAME']
225 kwargs['ostenantname'] = os.environ['OS_TENANT_NAME']
226 kwargs['osauthurl'] = os.environ['OS_AUTH_URL']
227 kwargs['ospassword'] = os.environ['OS_PASSWORD']
228 if installer_type == 'fuel':
229 kwargs['odlwebport'] = '8282'
230 elif installer_type == 'apex' or installer_type == 'netvirt':
231 kwargs['odlip'] = os.environ['SDN_CONTROLLER_IP']
232 kwargs['odlwebport'] = '8081'
233 kwargs['odlrestconfport'] = '8081'
234 elif installer_type == 'joid':
235 kwargs['odlip'] = os.environ['SDN_CONTROLLER']
236 elif installer_type == 'compass':
237 kwargs['odlwebport'] = '8181'
239 kwargs['odlip'] = os.environ['SDN_CONTROLLER_IP']
240 except KeyError as ex:
241 self.__logger.error("Cannot run ODL testcases. "
242 "Please check env var: "
244 return self.EX_RUN_ERROR
245 except Exception: # pylint: disable=broad-except
246 self.__logger.exception("Cannot run ODL testcases.")
247 return self.EX_RUN_ERROR
249 return self.main(suites, **kwargs)
252 class ODLParser(object): # pylint: disable=too-few-public-methods
253 """Parser to run ODL test suites."""
256 self.parser = argparse.ArgumentParser()
257 self.parser.add_argument(
258 '-n', '--neutronip', help='Neutron IP',
260 self.parser.add_argument(
261 '-k', '--osauthurl', help='OS_AUTH_URL as defined by OpenStack',
262 default='http://127.0.0.1:5000/v2.0')
263 self.parser.add_argument(
264 '-a', '--osusername', help='Username for OpenStack',
266 self.parser.add_argument(
267 '-b', '--ostenantname', help='Tenantname for OpenStack',
269 self.parser.add_argument(
270 '-c', '--ospassword', help='Password for OpenStack',
272 self.parser.add_argument(
273 '-o', '--odlip', help='OpenDaylight IP',
275 self.parser.add_argument(
276 '-w', '--odlwebport', help='OpenDaylight Web Portal Port',
278 self.parser.add_argument(
279 '-r', '--odlrestconfport', help='OpenDaylight RESTConf Port',
281 self.parser.add_argument(
282 '-d', '--odlusername', help='Username for ODL',
284 self.parser.add_argument(
285 '-e', '--odlpassword', help='Password for ODL',
287 self.parser.add_argument(
288 '-p', '--pushtodb', help='Push results to DB',
291 def parse_args(self, argv=None):
294 It can call sys.exit if arguments are incorrect.
297 the arguments from cmdline
301 return vars(self.parser.parse_args(argv))
304 if __name__ == '__main__':
305 logging.basicConfig()
308 ARGS = PARSER.parse_args(sys.argv[1:])
310 RESULT = ODL.main(ODLTests.default_suites, **ARGS)
311 if RESULT != testcase.TestCase.EX_OK:
314 sys.exit(ODL.push_to_db())
315 except Exception: # pylint: disable=broad-except
316 sys.exit(testcase.TestCase.EX_RUN_ERROR)