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."""
18 from keystoneauth1.exceptions import auth_plugins
20 from robot.errors import DataError, RobotError
21 from robot.result import testcase as result_testcase
22 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
35 logging.disable(logging.CRITICAL)
38 self.visitor = odl.ODLResultVisitor()
41 self.assertFalse(self.visitor.get_data())
44 data = {'name': 'foo',
47 'starttime': "20161216 16:00:00.000",
48 'endtime': "20161216 16:00:01.000",
50 'text': 'Hello, World!',
52 test = result_testcase.TestCase(name=data['name'],
53 status=data['status'],
55 starttime=data['starttime'],
56 endtime=data['endtime'])
57 test.parent = mock.Mock()
58 config = {'name': data['parent'],
59 'criticality.test_is_critical.return_value': data[
61 test.parent.configure_mock(**config)
62 self.visitor.visit_test(test)
63 self.assertEqual(self.visitor.get_data(), [data])
66 class ODLTesting(unittest.TestCase):
68 """The super class which testing classes could inherit."""
69 # pylint: disable=missing-docstring
71 logging.disable(logging.CRITICAL)
73 _keystone_ip = "127.0.0.1"
74 _neutron_ip = "127.0.0.2"
75 _sdn_controller_ip = "127.0.0.3"
76 _os_auth_url = "http://{}:5000/v2.0".format(_keystone_ip)
77 _os_tenantname = "admin"
78 _os_username = "admin"
79 _os_password = "admin"
81 _odl_restconfport = "8181"
82 _odl_username = "admin"
83 _odl_password = "admin"
86 for var in ("INSTALLER_TYPE", "SDN_CONTROLLER", "SDN_CONTROLLER_IP"):
89 os.environ["OS_AUTH_URL"] = self._os_auth_url
90 os.environ["OS_USERNAME"] = self._os_username
91 os.environ["OS_PASSWORD"] = self._os_password
92 os.environ["OS_TENANT_NAME"] = self._os_tenantname
93 self.test = odl.ODLTests()
94 self.defaultargs = {'odlusername': self._odl_username,
95 'odlpassword': self._odl_password,
96 'neutronip': self._keystone_ip,
97 'osauthurl': self._os_auth_url,
98 'osusername': self._os_username,
99 'ostenantname': self._os_tenantname,
100 'ospassword': self._os_password,
101 'odlip': self._keystone_ip,
102 'odlwebport': self._odl_webport,
103 'odlrestconfport': self._odl_restconfport,
107 class ODLParseResultTesting(ODLTesting):
109 """The class testing ODLTests.parse_results()."""
110 # pylint: disable=missing-docstring
112 @mock.patch('robot.api.ExecutionResult', side_effect=DataError)
113 def test_raises_exc(self, mock_method):
114 with self.assertRaises(DataError):
115 self.test.parse_results()
116 mock_method.assert_called_once_with()
119 config = {'name': 'dummy', 'starttime': '20161216 16:00:00.000',
120 'endtime': '20161216 16:00:01.000', 'status': 'PASS'}
122 suite.configure_mock(**config)
123 with mock.patch('robot.api.ExecutionResult',
124 return_value=mock.Mock(suite=suite)):
125 self.test.parse_results()
126 self.assertEqual(self.test.criteria, config['status'])
127 self.assertEqual(self.test.start_time,
128 timestamp_to_secs(config['starttime']))
129 self.assertEqual(self.test.stop_time,
130 timestamp_to_secs(config['endtime']))
131 self.assertEqual(self.test.details,
132 {'description': config['name'], 'tests': []})
135 class ODLRobotTesting(ODLTesting):
137 """The class testing ODLTests.set_robotframework_vars()."""
138 # pylint: disable=missing-docstring
140 @mock.patch('fileinput.input', side_effect=Exception())
141 def test_set_vars_ko(self, mock_method):
142 self.assertFalse(self.test.set_robotframework_vars())
143 mock_method.assert_called_once_with(
144 os.path.join(odl.ODLTests.odl_test_repo,
145 'csit/variables/Variables.py'), inplace=True)
147 @mock.patch('fileinput.input', return_value=[])
148 def test_set_vars_empty(self, mock_method):
149 self.assertTrue(self.test.set_robotframework_vars())
150 mock_method.assert_called_once_with(
151 os.path.join(odl.ODLTests.odl_test_repo,
152 'csit/variables/Variables.py'), inplace=True)
154 @mock.patch('sys.stdout', new_callable=StringIO.StringIO)
155 def _test_set_vars(self, msg1, msg2, *args):
156 line = mock.MagicMock()
157 line.__iter__.return_value = [msg1]
158 with mock.patch('fileinput.input', return_value=line) as mock_method:
159 self.assertTrue(self.test.set_robotframework_vars())
160 mock_method.assert_called_once_with(
161 os.path.join(odl.ODLTests.odl_test_repo,
162 'csit/variables/Variables.py'), inplace=True)
163 self.assertEqual(args[0].getvalue(), "{}\n".format(msg2))
165 def test_set_vars_auth_default(self):
166 self._test_set_vars("AUTH = []",
167 "AUTH = [u'admin', u'admin']")
169 def test_set_vars_auth1(self):
170 self._test_set_vars("AUTH1 = []", "AUTH1 = []")
172 @mock.patch('sys.stdout', new_callable=StringIO.StringIO)
173 def test_set_vars_auth_foo(self, *args):
174 line = mock.MagicMock()
175 line.__iter__.return_value = ["AUTH = []"]
176 with mock.patch('fileinput.input', return_value=line) as mock_method:
177 self.assertTrue(self.test.set_robotframework_vars('foo', 'bar'))
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(),
182 "AUTH = [u'{}', u'{}']\n".format('foo', 'bar'))
185 class ODLMainTesting(ODLTesting):
187 """The class testing ODLTests.main()."""
188 # pylint: disable=missing-docstring
190 def _get_main_kwargs(self, key=None):
191 kwargs = {'odlusername': self._odl_username,
192 'odlpassword': self._odl_password,
193 'neutronip': self._neutron_ip,
194 'osauthurl': self._os_auth_url,
195 'osusername': self._os_username,
196 'ostenantname': self._os_tenantname,
197 'ospassword': self._os_password,
198 'odlip': self._sdn_controller_ip,
199 'odlwebport': self._odl_webport,
200 'odlrestconfport': self._odl_restconfport}
205 def _test_main(self, status, *args):
206 kwargs = self._get_main_kwargs()
207 self.assertEqual(self.test.main(**kwargs), status)
209 args[0].assert_called_once_with(
210 odl.ODLTests.res_dir)
212 variable = ['KEYSTONE:{}'.format(self._keystone_ip),
213 'NEUTRON:{}'.format(self._neutron_ip),
214 'OS_AUTH_URL:"{}"'.format(self._os_auth_url),
215 'OSUSERNAME:"{}"'.format(self._os_username),
216 'OSTENANTNAME:"{}"'.format(self._os_tenantname),
217 'OSPASSWORD:"{}"'.format(self._os_password),
218 'ODL_SYSTEM_IP:{}'.format(self._sdn_controller_ip),
219 'PORT:{}'.format(self._odl_webport),
220 'RESTCONFPORT:{}'.format(self._odl_restconfport)]
221 args[1].assert_called_once_with(
222 odl.ODLTests.basic_suite_dir,
223 odl.ODLTests.neutron_suite_dir,
225 output=os.path.join(odl.ODLTests.res_dir, 'output.xml'),
230 args[2].assert_called_with(
231 os.path.join(odl.ODLTests.res_dir, 'stdout.txt'))
233 def _test_no_keyword(self, key):
234 kwargs = self._get_main_kwargs(key)
235 self.assertEqual(self.test.main(**kwargs),
236 testcase.TestCase.EX_RUN_ERROR)
238 def test_no_odlusername(self):
239 self._test_no_keyword('odlusername')
241 def test_no_odlpassword(self):
242 self._test_no_keyword('odlpassword')
244 def test_no_neutronip(self):
245 self._test_no_keyword('neutronip')
247 def test_no_osauthurl(self):
248 self._test_no_keyword('osauthurl')
250 def test_no_osusername(self):
251 self._test_no_keyword('osusername')
253 def test_no_ostenantname(self):
254 self._test_no_keyword('ostenantname')
256 def test_no_ospassword(self):
257 self._test_no_keyword('ospassword')
259 def test_no_odlip(self):
260 self._test_no_keyword('odlip')
262 def test_no_odlwebport(self):
263 self._test_no_keyword('odlwebport')
265 def test_no_odlrestconfport(self):
266 self._test_no_keyword('odlrestconfport')
268 def test_set_vars_ko(self):
269 with mock.patch.object(self.test, 'set_robotframework_vars',
270 return_value=False) as mock_object:
271 self._test_main(testcase.TestCase.EX_RUN_ERROR)
272 mock_object.assert_called_once_with(
273 self._odl_username, self._odl_password)
275 @mock.patch('os.makedirs', side_effect=Exception)
276 def test_makedirs_exc(self, mock_method):
277 with mock.patch.object(self.test, 'set_robotframework_vars',
278 return_value=True), \
279 self.assertRaises(Exception):
280 self._test_main(testcase.TestCase.EX_RUN_ERROR,
283 @mock.patch('os.makedirs', side_effect=OSError)
284 def test_makedirs_oserror(self, mock_method):
285 with mock.patch.object(self.test, 'set_robotframework_vars',
287 self._test_main(testcase.TestCase.EX_RUN_ERROR,
290 @mock.patch('robot.run', side_effect=RobotError)
291 @mock.patch('os.makedirs')
292 def test_run_ko(self, *args):
293 with mock.patch.object(self.test, 'set_robotframework_vars',
294 return_value=True), \
295 mock.patch.object(odl, 'open', mock.mock_open(),
297 self.assertRaises(RobotError):
298 self._test_main(testcase.TestCase.EX_RUN_ERROR, *args)
300 @mock.patch('robot.run')
301 @mock.patch('os.makedirs')
302 def test_parse_results_ko(self, *args):
303 with mock.patch.object(self.test, 'set_robotframework_vars',
304 return_value=True), \
305 mock.patch.object(odl, 'open', mock.mock_open(),
307 mock.patch.object(self.test, 'parse_results',
308 side_effect=RobotError):
309 self._test_main(testcase.TestCase.EX_RUN_ERROR, *args)
311 @mock.patch('os.remove', side_effect=Exception)
312 @mock.patch('robot.run')
313 @mock.patch('os.makedirs')
314 def test_remove_exc(self, *args):
315 with mock.patch.object(self.test, 'set_robotframework_vars',
316 return_value=True), \
317 mock.patch.object(self.test, 'parse_results'), \
318 self.assertRaises(Exception):
319 self._test_main(testcase.TestCase.EX_OK, *args)
321 @mock.patch('os.remove')
322 @mock.patch('robot.run')
323 @mock.patch('os.makedirs')
324 def test_ok(self, *args):
325 with mock.patch.object(self.test, 'set_robotframework_vars',
326 return_value=True), \
327 mock.patch.object(odl, 'open', mock.mock_open(),
329 mock.patch.object(self.test, 'parse_results'):
330 self._test_main(testcase.TestCase.EX_OK, *args)
332 @mock.patch('os.remove')
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(odl, 'open', mock.mock_open(),
340 mock.patch.object(self.test, 'parse_results'):
341 self._test_main(testcase.TestCase.EX_OK, *args)
343 @mock.patch('os.remove')
344 @mock.patch('robot.run', return_value=1)
345 @mock.patch('os.makedirs')
346 def test_testcases_in_failure(self, *args):
347 with mock.patch.object(self.test, 'set_robotframework_vars',
348 return_value=True), \
349 mock.patch.object(odl, 'open', mock.mock_open(),
351 mock.patch.object(self.test, 'parse_results'):
352 self._test_main(testcase.TestCase.EX_OK, *args)
354 @mock.patch('os.remove', side_effect=OSError)
355 @mock.patch('robot.run')
356 @mock.patch('os.makedirs')
357 def test_remove_oserror(self, *args):
358 with mock.patch.object(self.test, 'set_robotframework_vars',
359 return_value=True), \
360 mock.patch.object(odl, 'open', mock.mock_open(),
362 mock.patch.object(self.test, 'parse_results'):
363 self._test_main(testcase.TestCase.EX_OK, *args)
366 class ODLRunTesting(ODLTesting):
368 """The class testing ODLTests.run()."""
369 # pylint: disable=missing-docstring
372 def _fake_url_for(cls, service_type='identity'):
373 if service_type == 'identity':
374 return "http://{}:5000/v2.0".format(
375 ODLTesting._keystone_ip)
376 elif service_type == 'network':
377 return "http://{}:9696".format(ODLTesting._neutron_ip)
381 def _test_no_env_var(self, var):
382 with mock.patch('functest.utils.openstack_utils.get_endpoint',
383 side_effect=self._fake_url_for):
385 self.assertEqual(self.test.run(),
386 testcase.TestCase.EX_RUN_ERROR)
388 def _test_run(self, status=testcase.TestCase.EX_OK,
389 exception=None, **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')
395 with mock.patch('functest.utils.openstack_utils.get_endpoint',
396 side_effect=self._fake_url_for):
398 self.test.main = mock.Mock(side_effect=exception)
400 self.test.main = mock.Mock(return_value=status)
401 self.assertEqual(self.test.run(), status)
402 self.test.main.assert_called_once_with(
403 odl.ODLTests.default_suites,
404 neutronip=self._neutron_ip,
405 odlip=odlip, odlpassword=self._odl_password,
406 odlrestconfport=odlrestconfport,
407 odlusername=self._odl_username, odlwebport=odlwebport,
408 osauthurl=self._os_auth_url,
409 ospassword=self._os_password, ostenantname=self._os_tenantname,
410 osusername=self._os_username)
412 def _test_multiple_suites(self, suites,
413 status=testcase.TestCase.EX_OK,
414 exception=None, **kwargs):
415 odlip = kwargs['odlip'] if 'odlip' in kwargs else '127.0.0.3'
416 odlwebport = kwargs['odlwebport'] if 'odlwebport' in kwargs else '8080'
417 odlrestconfport = (kwargs['odlrestconfport']
418 if 'odlrestconfport' in kwargs else '8181')
419 with mock.patch('functest.utils.openstack_utils.get_endpoint',
420 side_effect=self._fake_url_for):
422 self.test.main = mock.Mock(side_effect=exception)
424 self.test.main = mock.Mock(return_value=status)
425 self.assertEqual(self.test.run(suites=suites), status)
426 self.test.main.assert_called_once_with(
428 neutronip=self._neutron_ip,
429 odlip=odlip, odlpassword=self._odl_password,
430 odlrestconfport=odlrestconfport,
431 odlusername=self._odl_username, odlwebport=odlwebport,
432 osauthurl=self._os_auth_url,
433 ospassword=self._os_password, ostenantname=self._os_tenantname,
434 osusername=self._os_username)
437 with mock.patch('functest.utils.openstack_utils.get_endpoint',
438 side_effect=auth_plugins.MissingAuthPlugin()):
439 self.assertEqual(self.test.run(),
440 testcase.TestCase.EX_RUN_ERROR)
442 def test_no_os_auth_url(self):
443 self._test_no_env_var("OS_AUTH_URL")
445 def test_no_os_username(self):
446 self._test_no_env_var("OS_USERNAME")
448 def test_no_os_password(self):
449 self._test_no_env_var("OS_PASSWORD")
451 def test_no_os_tenant_name(self):
452 self._test_no_env_var("OS_TENANT_NAME")
454 def test_main_false(self):
455 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
456 self._test_run(testcase.TestCase.EX_RUN_ERROR,
457 odlip=self._sdn_controller_ip,
458 odlwebport=self._odl_webport)
460 def test_main_exc(self):
461 with self.assertRaises(Exception):
462 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
463 self._test_run(status=testcase.TestCase.EX_RUN_ERROR,
464 exception=Exception(),
465 odlip=self._sdn_controller_ip,
466 odlwebport=self._odl_webport)
468 def test_no_sdn_controller_ip(self):
469 with mock.patch('functest.utils.openstack_utils.get_endpoint',
470 side_effect=self._fake_url_for):
471 self.assertEqual(self.test.run(),
472 testcase.TestCase.EX_RUN_ERROR)
474 def test_without_installer_type(self):
475 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
476 self._test_run(testcase.TestCase.EX_OK,
477 odlip=self._sdn_controller_ip,
478 odlwebport=self._odl_webport)
480 def test_suites(self):
481 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
482 self._test_multiple_suites(
483 [odl.ODLTests.basic_suite_dir],
484 testcase.TestCase.EX_OK,
485 odlip=self._sdn_controller_ip,
486 odlwebport=self._odl_webport)
489 os.environ["INSTALLER_TYPE"] = "fuel"
490 self._test_run(testcase.TestCase.EX_OK,
491 odlip=self._neutron_ip, odlwebport='8282')
493 def test_apex_no_controller_ip(self):
494 with mock.patch('functest.utils.openstack_utils.get_endpoint',
495 side_effect=self._fake_url_for):
496 os.environ["INSTALLER_TYPE"] = "apex"
497 self.assertEqual(self.test.run(),
498 testcase.TestCase.EX_RUN_ERROR)
501 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
502 os.environ["INSTALLER_TYPE"] = "apex"
503 self._test_run(testcase.TestCase.EX_OK,
504 odlip=self._sdn_controller_ip, odlwebport='8081',
505 odlrestconfport='8081')
507 def test_netvirt_no_controller_ip(self):
508 with mock.patch('functest.utils.openstack_utils.get_endpoint',
509 side_effect=self._fake_url_for):
510 os.environ["INSTALLER_TYPE"] = "netvirt"
511 self.assertEqual(self.test.run(),
512 testcase.TestCase.EX_RUN_ERROR)
514 def test_netvirt(self):
515 os.environ["SDN_CONTROLLER_IP"] = self._sdn_controller_ip
516 os.environ["INSTALLER_TYPE"] = "netvirt"
517 self._test_run(testcase.TestCase.EX_OK,
518 odlip=self._sdn_controller_ip, odlwebport='8081',
519 odlrestconfport='8081')
521 def test_joid_no_controller_ip(self):
522 with mock.patch('functest.utils.openstack_utils.get_endpoint',
523 side_effect=self._fake_url_for):
524 os.environ["INSTALLER_TYPE"] = "joid"
525 self.assertEqual(self.test.run(),
526 testcase.TestCase.EX_RUN_ERROR)
529 os.environ["SDN_CONTROLLER"] = self._sdn_controller_ip
530 os.environ["INSTALLER_TYPE"] = "joid"
531 self._test_run(testcase.TestCase.EX_OK,
532 odlip=self._sdn_controller_ip, odlwebport='8080')
534 def test_compass(self):
535 os.environ["INSTALLER_TYPE"] = "compass"
536 self._test_run(testcase.TestCase.EX_OK,
537 odlip=self._neutron_ip, odlwebport='8181')
540 class ODLArgParserTesting(ODLTesting):
542 """The class testing ODLParser."""
543 # pylint: disable=missing-docstring
546 self.parser = odl.ODLParser()
547 super(ODLArgParserTesting, self).setUp()
549 def test_default(self):
550 self.assertEqual(self.parser.parse_args(), self.defaultargs)
552 def test_basic(self):
553 self.defaultargs['neutronip'] = self._neutron_ip
554 self.defaultargs['odlip'] = self._sdn_controller_ip
556 self.parser.parse_args(
557 ["--neutronip={}".format(self._neutron_ip),
558 "--odlip={}".format(self._sdn_controller_ip)]),
561 @mock.patch('sys.stderr', new_callable=StringIO.StringIO)
562 def test_fail(self, mock_method):
563 self.defaultargs['foo'] = 'bar'
564 with self.assertRaises(SystemExit):
565 self.parser.parse_args(["--foo=bar"])
566 mock_method.assert_called_once_with()
568 def _test_arg(self, arg, value):
569 self.defaultargs[arg] = value
571 self.parser.parse_args(["--{}={}".format(arg, value)]),
574 def test_odlusername(self):
575 self._test_arg('odlusername', 'foo')
577 def test_odlpassword(self):
578 self._test_arg('odlpassword', 'foo')
580 def test_osauthurl(self):
581 self._test_arg('osauthurl', 'http://127.0.0.4:5000/v2')
583 def test_neutronip(self):
584 self._test_arg('neutronip', '127.0.0.4')
586 def test_osusername(self):
587 self._test_arg('osusername', 'foo')
589 def test_ostenantname(self):
590 self._test_arg('ostenantname', 'foo')
592 def test_ospassword(self):
593 self._test_arg('ospassword', 'foo')
595 def test_odlip(self):
596 self._test_arg('odlip', '127.0.0.4')
598 def test_odlwebport(self):
599 self._test_arg('odlwebport', '80')
601 def test_odlrestconfport(self):
602 self._test_arg('odlrestconfport', '80')
604 def test_pushtodb(self):
605 self.defaultargs['pushtodb'] = True
606 self.assertEqual(self.parser.parse_args(["--{}".format('pushtodb')]),
609 def test_multiple_args(self):
610 self.defaultargs['neutronip'] = self._neutron_ip
611 self.defaultargs['odlip'] = self._sdn_controller_ip
613 self.parser.parse_args(
614 ["--neutronip={}".format(self._neutron_ip),
615 "--odlip={}".format(self._sdn_controller_ip)]),
619 if __name__ == "__main__":
620 unittest.main(verbosity=2)