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 = constants.CONST.__getattribute__('dir_repo_odl_test')
70 neutron_suite_dir = os.path.join(odl_test_repo,
71 "csit/suites/openstack/neutron")
72 basic_suite_dir = os.path.join(odl_test_repo,
73 "csit/suites/integration/basic")
74 default_suites = [basic_suite_dir, neutron_suite_dir]
75 res_dir = os.path.join(
76 constants.CONST.__getattribute__('dir_results'), 'odl')
77 __logger = logging.getLogger(__name__)
80 def set_robotframework_vars(cls, odlusername="admin", odlpassword="admin"):
81 """Set credentials in csit/variables/Variables.py.
84 True if credentials are set.
87 odl_variables_files = os.path.join(cls.odl_test_repo,
88 'csit/variables/Variables.py')
90 for line in fileinput.input(odl_variables_files,
92 print(re.sub("AUTH = .*",
93 ("AUTH = [u'" + odlusername + "', u'" +
97 except Exception as ex: # pylint: disable=broad-except
98 cls.__logger.error("Cannot set ODL creds: %s", str(ex))
101 def parse_results(self):
102 """Parse output.xml and get the details in it."""
103 xml_file = os.path.join(self.res_dir, 'output.xml')
104 result = robot.api.ExecutionResult(xml_file)
105 visitor = ODLResultVisitor()
106 result.visit(visitor)
108 self.result = 100 * (
109 result.suite.statistics.critical.passed /
110 result.suite.statistics.critical.total)
111 except ZeroDivisionError:
112 self.__logger.error("No test has been run")
113 self.start_time = timestamp_to_secs(result.suite.starttime)
114 self.stop_time = timestamp_to_secs(result.suite.endtime)
116 self.details['description'] = result.suite.name
117 self.details['tests'] = visitor.get_data()
119 def run_suites(self, suites=None, **kwargs):
120 """Run the test suites
122 It has been designed to be called in any context.
123 It requires the following keyword arguments:
137 * set all RobotFramework_variables,
138 * create the output directories if required,
139 * get the results in output.xml,
140 * delete temporary files.
143 kwargs: Arbitrary keyword arguments.
146 EX_OK if all suites ran well.
147 EX_RUN_ERROR otherwise.
151 suites = self.default_suites
152 odlusername = kwargs['odlusername']
153 odlpassword = kwargs['odlpassword']
154 osauthurl = kwargs['osauthurl']
155 keystoneip = urllib.parse.urlparse(osauthurl).hostname
156 variables = ['KEYSTONE:' + keystoneip,
157 'NEUTRON:' + kwargs['neutronip'],
158 'OS_AUTH_URL:"' + osauthurl + '"',
159 'OSUSERNAME:"' + kwargs['osusername'] + '"',
160 'OSTENANTNAME:"' + kwargs['ostenantname'] + '"',
161 'OSPASSWORD:"' + kwargs['ospassword'] + '"',
162 'ODL_SYSTEM_IP:' + kwargs['odlip'],
163 'PORT:' + kwargs['odlwebport'],
164 'RESTCONFPORT:' + kwargs['odlrestconfport']]
165 except KeyError as ex:
166 self.__logger.error("Cannot run ODL testcases. Please check "
168 return self.EX_RUN_ERROR
169 if self.set_robotframework_vars(odlusername, odlpassword):
171 os.makedirs(self.res_dir)
172 except OSError as ex:
173 if ex.errno != errno.EEXIST:
174 self.__logger.exception(
175 "Cannot create %s", self.res_dir)
176 return self.EX_RUN_ERROR
177 output_dir = os.path.join(self.res_dir, 'output.xml')
179 robot.run(*suites, variable=variables, output=output_dir,
180 log='NONE', report='NONE', stdout=stream)
181 self.__logger.info("\n" + stream.getvalue())
182 self.__logger.info("ODL results were successfully generated")
185 self.__logger.info("ODL results were successfully parsed")
186 except RobotError as ex:
187 self.__logger.error("Run tests before publishing: %s",
189 return self.EX_RUN_ERROR
192 return self.EX_RUN_ERROR
194 def run(self, **kwargs):
195 """Run suites in OPNFV environment
197 It basically check env vars to call main() with the keywords
201 kwargs: Arbitrary keyword arguments.
204 EX_OK if all suites ran well.
205 EX_RUN_ERROR otherwise.
208 suites = self.default_suites
210 suites = kwargs["suites"]
213 neutron_url = op_utils.get_endpoint(service_type='network')
214 kwargs = {'neutronip': urllib.parse.urlparse(neutron_url).hostname}
215 kwargs['odlip'] = kwargs['neutronip']
216 kwargs['odlwebport'] = '8080'
217 kwargs['odlrestconfport'] = '8181'
218 kwargs['odlusername'] = 'admin'
219 kwargs['odlpassword'] = 'admin'
220 installer_type = None
221 if 'INSTALLER_TYPE' in os.environ:
222 installer_type = os.environ['INSTALLER_TYPE']
223 kwargs['osusername'] = os.environ['OS_USERNAME']
224 kwargs['ostenantname'] = os.environ['OS_TENANT_NAME']
225 kwargs['osauthurl'] = os.environ['OS_AUTH_URL']
226 kwargs['ospassword'] = os.environ['OS_PASSWORD']
227 if installer_type == 'fuel':
228 kwargs['odlwebport'] = '8282'
229 elif installer_type == 'apex' or installer_type == 'netvirt':
230 kwargs['odlip'] = os.environ['SDN_CONTROLLER_IP']
231 kwargs['odlwebport'] = '8081'
232 kwargs['odlrestconfport'] = '8081'
233 elif installer_type == 'joid':
234 kwargs['odlip'] = os.environ['SDN_CONTROLLER']
235 elif installer_type == 'compass':
236 kwargs['odlrestconfport'] = '8080'
237 elif installer_type == 'daisy':
238 kwargs['odlip'] = os.environ['SDN_CONTROLLER_IP']
239 kwargs['odlwebport'] = '8181'
240 kwargs['odlrestconfport'] = '8087'
242 kwargs['odlip'] = os.environ['SDN_CONTROLLER_IP']
243 except KeyError as ex:
244 self.__logger.error("Cannot run ODL testcases. "
245 "Please check env var: "
247 return self.EX_RUN_ERROR
248 except Exception: # pylint: disable=broad-except
249 self.__logger.exception("Cannot run ODL testcases.")
250 return self.EX_RUN_ERROR
252 return self.run_suites(suites, **kwargs)
255 class ODLParser(object): # pylint: disable=too-few-public-methods
256 """Parser to run ODL test suites."""
259 self.parser = argparse.ArgumentParser()
260 self.parser.add_argument(
261 '-n', '--neutronip', help='Neutron IP',
263 self.parser.add_argument(
264 '-k', '--osauthurl', help='OS_AUTH_URL as defined by OpenStack',
265 default='http://127.0.0.1:5000/v2.0')
266 self.parser.add_argument(
267 '-a', '--osusername', help='Username for OpenStack',
269 self.parser.add_argument(
270 '-b', '--ostenantname', help='Tenantname for OpenStack',
272 self.parser.add_argument(
273 '-c', '--ospassword', help='Password for OpenStack',
275 self.parser.add_argument(
276 '-o', '--odlip', help='OpenDaylight IP',
278 self.parser.add_argument(
279 '-w', '--odlwebport', help='OpenDaylight Web Portal Port',
281 self.parser.add_argument(
282 '-r', '--odlrestconfport', help='OpenDaylight RESTConf Port',
284 self.parser.add_argument(
285 '-d', '--odlusername', help='Username for ODL',
287 self.parser.add_argument(
288 '-e', '--odlpassword', help='Password for ODL',
290 self.parser.add_argument(
291 '-p', '--pushtodb', help='Push results to DB',
294 def parse_args(self, argv=None):
297 It can call sys.exit if arguments are incorrect.
300 the arguments from cmdline
304 return vars(self.parser.parse_args(argv))
309 logging.basicConfig()
312 args = parser.parse_args(sys.argv[1:])
314 result = odl.run_suites(ODLTests.default_suites, **args)
315 if result != testcase.TestCase.EX_OK:
318 return odl.push_to_db()
321 except Exception: # pylint: disable=broad-except
322 return testcase.TestCase.EX_RUN_ERROR