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 the classes required to fully cover odl."""
17 from keystoneauth1.exceptions import auth_plugins
19 from robot.errors import DataError, RobotError
20 from robot.result import model
21 from robot.utils.robottime import timestamp_to_secs
24 from functest.core import testcase
25 from functest.opnfv_tests.sdn.odl import odl
27 __author__ = "Cedric Ollivier <cedric.ollivier@orange.com>"
30 class ODLVisitorTesting(unittest.TestCase):
32 """The class testing ODLResultVisitor."""
33 # pylint: disable=missing-docstring
36 self.visitor = odl.ODLResultVisitor()
39 self.assertFalse(self.visitor.get_data())
42 data = {'name': 'foo',
45 'starttime': "20161216 16:00:00.000",
46 'endtime': "20161216 16:00:01.000",
48 'text': 'Hello, World!',
50 test = model.TestCase(
51 name=data['name'], status=data['status'], message=data['text'],
52 starttime=data['starttime'], endtime=data['endtime'])
53 test.parent = mock.Mock()
54 config = {'name': data['parent'],
55 'criticality.test_is_critical.return_value': data[
57 test.parent.configure_mock(**config)
58 self.visitor.visit_test(test)
59 self.assertEqual(self.visitor.get_data(), [data])
62 class ODLTesting(unittest.TestCase):
64 """The super class which testing classes could inherit."""
65 # pylint: disable=missing-docstring
67 logging.disable(logging.CRITICAL)
69 _keystone_ip = "127.0.0.1"
70 _neutron_ip = "127.0.0.2"
71 _sdn_controller_ip = "127.0.0.3"
72 _os_auth_url = "http://{}:5000/v2.0".format(_keystone_ip)
73 _os_tenantname = "admin"
74 _os_username = "admin"
75 _os_password = "admin"
77 _odl_restconfport = "8181"
78 _odl_username = "admin"
79 _odl_password = "admin"
82 for var in ("INSTALLER_TYPE", "SDN_CONTROLLER", "SDN_CONTROLLER_IP"):
85 os.environ["OS_AUTH_URL"] = self._os_auth_url
86 os.environ["OS_USERNAME"] = self._os_username
87 os.environ["OS_PASSWORD"] = self._os_password
88 os.environ["OS_TENANT_NAME"] = self._os_tenantname
89 self.test = odl.ODLTests(case_name='odl', project_name='functest')
90 self.defaultargs = {'odlusername': self._odl_username,
91 'odlpassword': self._odl_password,
92 'neutronip': self._keystone_ip,
93 'osauthurl': self._os_auth_url,
94 'osusername': self._os_username,
95 'ostenantname': self._os_tenantname,
96 'ospassword': self._os_password,
97 'odlip': self._keystone_ip,
98 'odlwebport': self._odl_webport,
99 'odlrestconfport': self._odl_restconfport,
103 class ODLParseResultTesting(ODLTesting):
105 """The class testing ODLTests.parse_results()."""
106 # pylint: disable=missing-docstring
108 _config = {'name': 'dummy', 'starttime': '20161216 16:00:00.000',
109 'endtime': '20161216 16:00:01.000'}
111 @mock.patch('robot.api.ExecutionResult', side_effect=DataError)
112 def test_raises_exc(self, mock_method):
113 with self.assertRaises(DataError):
114 self.test.parse_results()
115 mock_method.assert_called_once_with(
116 os.path.join(odl.ODLTests.res_dir, 'output.xml'))
118 def _test_result(self, config, result):
120 suite.configure_mock(**config)
121 with mock.patch('robot.api.ExecutionResult',
122 return_value=mock.Mock(suite=suite)):
123 self.test.parse_results()
124 self.assertEqual(self.test.result, result)
125 self.assertEqual(self.test.start_time,
126 timestamp_to_secs(config['starttime']))
127 self.assertEqual(self.test.stop_time,
128 timestamp_to_secs(config['endtime']))
129 self.assertEqual(self.test.details,
130 {'description': config['name'], 'tests': []})
132 def test_null_passed(self):
133 self._config.update({'statistics.critical.passed': 0,
134 'statistics.critical.total': 20})
135 self._test_result(self._config, 0)
137 def test_no_test(self):
138 self._config.update({'statistics.critical.passed': 20,
139 'statistics.critical.total': 0})
140 self._test_result(self._config, 0)
142 def test_half_success(self):
143 self._config.update({'statistics.critical.passed': 10,
144 'statistics.critical.total': 20})
145 self._test_result(self._config, 50)
147 def test_success(self):
148 self._config.update({'statistics.critical.passed': 20,
149 'statistics.critical.total': 20})
150 self._test_result(self._config, 100)
153 class ODLRobotTesting(ODLTesting):
155 """The class testing ODLTests.set_robotframework_vars()."""
156 # pylint: disable=missing-docstring
158 @mock.patch('fileinput.input', side_effect=Exception())
159 def test_set_vars_ko(self, mock_method):
160 self.assertFalse(self.test.set_robotframework_vars())
161 mock_method.assert_called_once_with(
162 os.path.join(odl.ODLTests.odl_test_repo,
163 'csit/variables/Variables.py'), inplace=True)
165 @mock.patch('fileinput.input', return_value=[])
166 def test_set_vars_empty(self, mock_method):
167 self.assertTrue(self.test.set_robotframework_vars())
168 mock_method.assert_called_once_with(
169 os.path.join(odl.ODLTests.odl_test_repo,
170 'csit/variables/Variables.py'), inplace=True)
172 @mock.patch('sys.stdout', new_callable=six.StringIO)
173 def _test_set_vars(self, msg1, msg2, *args):
174 line = mock.MagicMock()
175 line.__iter__.return_value = [msg1]
176 with mock.patch('fileinput.input', return_value=line) as mock_method:
177 self.assertTrue(self.test.set_robotframework_vars())
178 mock_method.assert_called_once_with(
179 os.path.join(odl.ODLTests.odl_test_repo,
180 'csit/variables/Variables.py'), inplace=True)
181 self.assertEqual(args[0].getvalue(), "{}\n".format(msg2))
183 def test_set_vars_auth_default(self):
184 self._test_set_vars("AUTH = []",
185 "AUTH = [u'admin', u'admin']")
187 def test_set_vars_auth1(self):
188 self._test_set_vars("AUTH1 = []", "AUTH1 = []")
190 @mock.patch('sys.stdout', new_callable=six.StringIO)
191 def test_set_vars_auth_foo(self, *args):
192 line = mock.MagicMock()
193 line.__iter__.return_value = ["AUTH = []"]
194 with mock.patch('fileinput.input', return_value=line) as mock_method:
195 self.assertTrue(self.test.set_robotframework_vars('foo', 'bar'))
196 mock_method.assert_called_once_with(
197 os.path.join(odl.ODLTests.odl_test_repo,
198 'csit/variables/Variables.py'), inplace=True)
199 self.assertEqual(args[0].getvalue(),
200 "AUTH = [u'{}', u'{}']\n".format('foo', 'bar'))
203 class ODLMainTesting(ODLTesting):
205 """The class testing ODLTests.run_suites()."""
206 # pylint: disable=missing-docstring
208 def _get_run_suites_kwargs(self, key=None):
209 kwargs = {'odlusername': self._odl_username,
210 'odlpassword': self._odl_password,
211 'neutronip': self._neutron_ip,
212 'osauthurl': self._os_auth_url,
213 'osusername': self._os_username,
214 'ostenantname': self._os_tenantname,
215 'ospassword': self._os_password,
216 'odlip': self._sdn_controller_ip,
217 'odlwebport': self._odl_webport,
218 'odlrestconfport': self._odl_restconfport}
223 def _test_run_suites(self, status, *args):
224 kwargs = self._get_run_suites_kwargs()
225 self.assertEqual(self.test.run_suites(**kwargs), status)
227 args[0].assert_called_once_with(
228 odl.ODLTests.res_dir)
230 variable = ['KEYSTONE:{}'.format(self._keystone_ip),
231 'NEUTRON:{}'.format(self._neutron_ip),
232 'OS_AUTH_URL:"{}"'.format(self._os_auth_url),
233 'OSUSERNAME:"{}"'.format(self._os_username),
234 'OSTENANTNAME:"{}"'.format(self._os_tenantname),
235 'OSPASSWORD:"{}"'.format(self._os_password),
236 'ODL_SYSTEM_IP:{}'.format(self._sdn_controller_ip),
237 'PORT:{}'.format(self._odl_webport),
238 'RESTCONFPORT:{}'.format(self._odl_restconfport)]
239 args[1].assert_called_once_with(
240 odl.ODLTests.basic_suite_dir,
241 odl.ODLTests.neutron_suite_dir,
243 output=os.path.join(odl.ODLTests.res_dir, 'output.xml'),
248 args[2].assert_called_with(
249 os.path.join(odl.ODLTests.res_dir, 'stdout.txt'))
251 def _test_no_keyword(self, key):
252 kwargs = self._get_run_suites_kwargs(key)
253 self.assertEqual(self.test.run_suites(**kwargs),
254 testcase.TestCase.EX_RUN_ERROR)
256 def test_no_odlusername(self):
257 self._test_no_keyword('odlusername')
259 def test_no_odlpassword(self):
260 self._test_no_keyword('odlpassword')
262 def test_no_neutronip(self):
263 self._test_no_keyword('neutronip')
265 def test_no_osauthurl(self):
266 self._test_no_keyword('osauthurl')
268 def test_no_osusername(self):
269 self._test_no_keyword('osusername')
271 def test_no_ostenantname(self):
272 self._test_no_keyword('ostenantname')
274 def test_no_ospassword(self):
275 self._test_no_keyword('ospassword')
277 def test_no_odlip(self):
278 self._test_no_keyword('odlip')
280 def test_no_odlwebport(self):
281 self._test_no_keyword('odlwebport')
283 def test_no_odlrestconfport(self):
284 self._test_no_keyword('odlrestconfport')
286 def test_set_vars_ko(self):
287 with mock.patch.object(self.test, 'set_robotframework_vars',
288 return_value=False) as mock_object:
289 self._test_run_suites(testcase.TestCase.EX_RUN_ERROR)
290 mock_object.assert_called_once_with(
291 self._odl_username, self._odl_password)
293 @mock.patch('os.makedirs', side_effect=Exception)
294 def test_makedirs_exc(self, mock_method):
295 with mock.patch.object(self.test, 'set_robotframework_vars',
296 return_value=True), \
297 self.assertRaises(Exception):
298 self._test_run_suites(testcase.TestCase.EX_RUN_ERROR,
301 @mock.patch('os.makedirs', side_effect=OSError)
302 def test_makedirs_oserror(self, mock_method):
303 with mock.patch.object(self.test, 'set_robotframework_vars',
305 self._test_run_suites(testcase.TestCase.EX_RUN_ERROR,
308 @mock.patch('robot.run', side_effect=RobotError)
309 @mock.patch('os.makedirs')
310 def test_run_ko(self, *args):
311 with mock.patch.object(self.test, 'set_robotframework_vars',
312 return_value=True), \
313 self.assertRaises(RobotError):
314 self._test_run_suites(testcase.TestCase.EX_RUN_ERROR, *args)
316 @mock.patch('robot.run')
317 @mock.patch('os.makedirs')
318 def test_parse_results_ko(self, *args):
319 with mock.patch.object(self.test, 'set_robotframework_vars',
320 return_value=True), \
321 mock.patch.object(self.test, 'parse_results',
322 side_effect=RobotError):
323 self._test_run_suites(testcase.TestCase.EX_RUN_ERROR, *args)
325 @mock.patch('robot.run')
326 @mock.patch('os.makedirs')
327 def test_ok(self, *args):
328 with mock.patch.object(self.test, 'set_robotframework_vars',
329 return_value=True), \
330 mock.patch.object(self.test, 'parse_results'):
331 self._test_run_suites(testcase.TestCase.EX_OK, *args)
333 @mock.patch('robot.run')
334 @mock.patch('os.makedirs', side_effect=OSError(errno.EEXIST, ''))
335 def test_makedirs_oserror17(self, *args):
336 with mock.patch.object(self.test, 'set_robotframework_vars',
337 return_value=True), \
338 mock.patch.object(self.test, 'parse_results'):
339 self._test_run_suites(testcase.TestCase.EX_OK, *args)
341 @mock.patch('robot.run', return_value=1)
342 @mock.patch('os.makedirs')
343 def test_testcases_in_failure(self, *args):
344 with mock.patch.object(self.test, 'set_robotframework_vars',
345 return_value=True), \
346 mock.patch.object(self.test, 'parse_results'):
347 self._test_run_suites(testcase.TestCase.EX_OK, *args)
350 class ODLRunTesting(ODLTesting):
352 """The class testing ODLTests.run()."""
353 # pylint: disable=missing-docstring
355 def _test_no_env_var(self, var):
356 with mock.patch('functest.utils.openstack_utils.get_endpoint',
357 return_value="http://{}:9696".format(
358 ODLTesting._neutron_ip)):
360 self.assertEqual(self.test.run(),
361 testcase.TestCase.EX_RUN_ERROR)
363 def _test_run(self, status=testcase.TestCase.EX_OK,
364 exception=None, **kwargs):
365 odlip = kwargs['odlip'] if 'odlip' in kwargs else '127.0.0.3'
366 odlwebport = kwargs['odlwebport'] if 'odlwebport' in kwargs else '8080'
367 odlrestconfport = (kwargs['odlrestconfport']
368 if 'odlrestconfport' in kwargs else '8181')
370 with mock.patch('functest.utils.openstack_utils.get_endpoint',
371 return_value="http://{}:9696".format(
372 ODLTesting._neutron_ip)):
374 self.test.run_suites = mock.Mock(side_effect=exception)
376 self.test.run_suites = mock.Mock(return_value=status)
377 self.assertEqual(self.test.run(), status)
378 self.test.run_suites.assert_called_once_with(
379 odl.ODLTests.default_suites,
380 neutronip=self._neutron_ip,
381 odlip=odlip, odlpassword=self._odl_password,
382 odlrestconfport=odlrestconfport,
383 odlusername=self._odl_username, odlwebport=odlwebport,
384 osauthurl=self._os_auth_url,
385 ospassword=self._os_password, ostenantname=self._os_tenantname,
386 osusername=self._os_username)
388 def _test_multiple_suites(self, suites,
389 status=testcase.TestCase.EX_OK, **kwargs):
390 odlip = kwargs['odlip'] if 'odlip' in kwargs else '127.0.0.3'
391 odlwebport = kwargs['odlwebport'] if 'odlwebport' in kwargs else '8080'
392 odlrestconfport = (kwargs['odlrestconfport']
393 if 'odlrestconfport' in kwargs else '8181')
394 with mock.patch('functest.utils.openstack_utils.get_endpoint',
395 return_value="http://{}:9696".format(
396 ODLTesting._neutron_ip)):
397 self.test.run_suites = mock.Mock(return_value=status)
398 self.assertEqual(self.test.run(suites=suites), status)
399 self.test.run_suites.assert_called_once_with(
401 neutronip=self._neutron_ip,
402 odlip=odlip, odlpassword=self._odl_password,
403 odlrestconfport=odlrestconfport,
404 odlusername=self._odl_username, odlwebport=odlwebport,
405 osauthurl=self._os_auth_url,
406 ospassword=self._os_password, ostenantname=self._os_tenantname,
407 osusername=self._os_username)
410 with mock.patch('functest.utils.openstack_utils.get_endpoint',
411 side_effect=auth_plugins.MissingAuthPlugin()):
412 self.assertEqual(self.test.run(),
413 testcase.TestCase.EX_RUN_ERROR)
415 def test_no_os_auth_url(self):
416 self._test_no_env_var("OS_AUTH_URL")
418 def test_no_os_username(self):
419 self._test_no_env_var("OS_USERNAME")
421 def test_no_os_password(self):
422 self._test_no_env_var("OS_PASSWORD")
424 def test_no_os_tenant_name(self):
425 self._test_no_env_var("OS_TENANT_NAME")
427 def test_run_suites_false(self):
428 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
429 self._test_run(testcase.TestCase.EX_RUN_ERROR,
430 odlip=self._sdn_controller_ip,
431 odlwebport=self._odl_webport)
433 def test_run_suites_exc(self):
434 with self.assertRaises(Exception):
435 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
436 self._test_run(status=testcase.TestCase.EX_RUN_ERROR,
437 exception=Exception(),
438 odlip=self._sdn_controller_ip,
439 odlwebport=self._odl_webport)
441 def test_no_sdn_controller_ip(self):
442 with mock.patch('functest.utils.openstack_utils.get_endpoint',
443 return_value="http://{}:9696".format(
444 ODLTesting._neutron_ip)):
445 self.assertEqual(self.test.run(),
446 testcase.TestCase.EX_RUN_ERROR)
448 def test_without_installer_type(self):
449 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
450 self._test_run(testcase.TestCase.EX_OK,
451 odlip=self._sdn_controller_ip,
452 odlwebport=self._odl_webport)
454 def test_suites(self):
455 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
456 self._test_multiple_suites(
457 [odl.ODLTests.basic_suite_dir],
458 testcase.TestCase.EX_OK,
459 odlip=self._sdn_controller_ip,
460 odlwebport=self._odl_webport)
463 os.environ["INSTALLER_TYPE"] = "fuel"
464 self._test_run(testcase.TestCase.EX_OK,
465 odlip=self._neutron_ip, odlwebport='8181',
466 odlrestconfport='8282')
468 def test_apex_no_controller_ip(self):
469 with mock.patch('functest.utils.openstack_utils.get_endpoint',
470 return_value="http://{}:9696".format(
471 ODLTesting._neutron_ip)):
472 os.environ["INSTALLER_TYPE"] = "apex"
473 self.assertEqual(self.test.run(),
474 testcase.TestCase.EX_RUN_ERROR)
477 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
478 os.environ["INSTALLER_TYPE"] = "apex"
479 self._test_run(testcase.TestCase.EX_OK,
480 odlip=self._sdn_controller_ip, odlwebport='8081',
481 odlrestconfport='8081')
483 def test_netvirt_no_controller_ip(self):
484 with mock.patch('functest.utils.openstack_utils.get_endpoint',
485 return_value="http://{}:9696".format(
486 ODLTesting._neutron_ip)):
487 os.environ["INSTALLER_TYPE"] = "netvirt"
488 self.assertEqual(self.test.run(),
489 testcase.TestCase.EX_RUN_ERROR)
491 def test_netvirt(self):
492 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
493 os.environ["INSTALLER_TYPE"] = "netvirt"
494 self._test_run(testcase.TestCase.EX_OK,
495 odlip=self._sdn_controller_ip, odlwebport='8081',
496 odlrestconfport='8081')
498 def test_joid_no_controller_ip(self):
499 with mock.patch('functest.utils.openstack_utils.get_endpoint',
500 return_value="http://{}:9696".format(
501 ODLTesting._neutron_ip)):
502 os.environ["INSTALLER_TYPE"] = "joid"
503 self.assertEqual(self.test.run(),
504 testcase.TestCase.EX_RUN_ERROR)
507 os.environ["SDN_CONTROLLER"] = self._sdn_controller_ip
508 os.environ["INSTALLER_TYPE"] = "joid"
509 self._test_run(testcase.TestCase.EX_OK,
510 odlip=self._sdn_controller_ip, odlwebport='8080')
512 def test_compass(self):
513 os.environ["INSTALLER_TYPE"] = "compass"
514 self._test_run(testcase.TestCase.EX_OK,
515 odlip=self._neutron_ip, odlrestconfport='8080')
517 def test_daisy_no_controller_ip(self):
518 with mock.patch('functest.utils.openstack_utils.get_endpoint',
519 return_value="http://{}:9696".format(
520 ODLTesting._neutron_ip)):
521 os.environ["INSTALLER_TYPE"] = "daisy"
522 self.assertEqual(self.test.run(),
523 testcase.TestCase.EX_RUN_ERROR)
525 def test_daisy(self):
526 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
527 os.environ["INSTALLER_TYPE"] = "daisy"
528 self._test_run(testcase.TestCase.EX_OK,
529 odlip=self._sdn_controller_ip, odlwebport='8181',
530 odlrestconfport='8087')
533 class ODLArgParserTesting(ODLTesting):
535 """The class testing ODLParser."""
536 # pylint: disable=missing-docstring
539 self.parser = odl.ODLParser()
540 super(ODLArgParserTesting, self).setUp()
542 def test_default(self):
543 self.assertEqual(self.parser.parse_args(), self.defaultargs)
545 def test_basic(self):
546 self.defaultargs['neutronip'] = self._neutron_ip
547 self.defaultargs['odlip'] = self._sdn_controller_ip
549 self.parser.parse_args(
550 ["--neutronip={}".format(self._neutron_ip),
551 "--odlip={}".format(self._sdn_controller_ip)]),
554 @mock.patch('sys.stderr', new_callable=six.StringIO)
555 def test_fail(self, mock_method):
556 self.defaultargs['foo'] = 'bar'
557 with self.assertRaises(SystemExit):
558 self.parser.parse_args(["--foo=bar"])
559 self.assertTrue(mock_method.getvalue().startswith("usage:"))
561 def _test_arg(self, arg, value):
562 self.defaultargs[arg] = value
564 self.parser.parse_args(["--{}={}".format(arg, value)]),
567 def test_odlusername(self):
568 self._test_arg('odlusername', 'foo')
570 def test_odlpassword(self):
571 self._test_arg('odlpassword', 'foo')
573 def test_osauthurl(self):
574 self._test_arg('osauthurl', 'http://127.0.0.4:5000/v2')
576 def test_neutronip(self):
577 self._test_arg('neutronip', '127.0.0.4')
579 def test_osusername(self):
580 self._test_arg('osusername', 'foo')
582 def test_ostenantname(self):
583 self._test_arg('ostenantname', 'foo')
585 def test_ospassword(self):
586 self._test_arg('ospassword', 'foo')
588 def test_odlip(self):
589 self._test_arg('odlip', '127.0.0.4')
591 def test_odlwebport(self):
592 self._test_arg('odlwebport', '80')
594 def test_odlrestconfport(self):
595 self._test_arg('odlrestconfport', '80')
597 def test_pushtodb(self):
598 self.defaultargs['pushtodb'] = True
599 self.assertEqual(self.parser.parse_args(["--{}".format('pushtodb')]),
602 def test_multiple_args(self):
603 self.defaultargs['neutronip'] = self._neutron_ip
604 self.defaultargs['odlip'] = self._sdn_controller_ip
606 self.parser.parse_args(
607 ["--neutronip={}".format(self._neutron_ip),
608 "--odlip={}".format(self._sdn_controller_ip)]),
612 if __name__ == "__main__":
613 logging.disable(logging.CRITICAL)
614 unittest.main(verbosity=2)