Use mock instead of mox in clients test

Using mock instead of mox objects in tests for cinder, glance, nova.
Also scenario test was added for testing nova function "refresh_server".

Change-Id: Ic812efc1e8ef2fb3ef79d2dc6a9acc38798dbe87
This commit is contained in:
Sergey Kraynev 2015-02-26 08:29:49 -05:00
parent 5ded08aa19
commit 3e91822a73
3 changed files with 122 additions and 165 deletions

View File

@ -29,7 +29,7 @@ class CinderClientPluginTests(common.HeatTestCase):
""" """
def setUp(self): def setUp(self):
super(CinderClientPluginTests, self).setUp() super(CinderClientPluginTests, self).setUp()
self.cinder_client = self.m.CreateMockAnything() self.cinder_client = mock.MagicMock()
con = utils.dummy_context() con = utils.dummy_context()
c = con.clients c = con.clients
self.cinder_plugin = c.client_plugin('cinder') self.cinder_plugin = c.client_plugin('cinder')
@ -38,29 +38,22 @@ class CinderClientPluginTests(common.HeatTestCase):
def test_get_volume(self): def test_get_volume(self):
"""Tests the get_volume function.""" """Tests the get_volume function."""
volume_id = str(uuid.uuid4()) volume_id = str(uuid.uuid4())
my_volume = self.m.CreateMockAnything() my_volume = mock.MagicMock()
self.cinder_client.volumes = self.m.CreateMockAnything() self.cinder_client.volumes.get.return_value = my_volume
self.cinder_client.volumes.get(
volume_id).MultipleTimes().AndReturn(my_volume)
self.m.ReplayAll()
self.assertEqual(my_volume, self.cinder_plugin.get_volume(volume_id)) self.assertEqual(my_volume, self.cinder_plugin.get_volume(volume_id))
self.cinder_client.volumes.get.assert_called_once_with(volume_id)
self.m.VerifyAll()
def test_get_snapshot(self): def test_get_snapshot(self):
"""Tests the get_volume_snapshot function.""" """Tests the get_volume_snapshot function."""
snapshot_id = str(uuid.uuid4()) snapshot_id = str(uuid.uuid4())
my_snapshot = self.m.CreateMockAnything() my_snapshot = mock.MagicMock()
self.cinder_client.volume_snapshots = self.m.CreateMockAnything() self.cinder_client.volume_snapshots.get.return_value = my_snapshot
self.cinder_client.volume_snapshots.get(
snapshot_id).MultipleTimes().AndReturn(my_snapshot)
self.m.ReplayAll()
self.assertEqual(my_snapshot, self.assertEqual(my_snapshot,
self.cinder_plugin.get_volume_snapshot(snapshot_id)) self.cinder_plugin.get_volume_snapshot(snapshot_id))
self.cinder_client.volume_snapshots.get.assert_called_once_with(
self.m.VerifyAll() snapshot_id)
class VolumeConstraintTest(common.HeatTestCase): class VolumeConstraintTest(common.HeatTestCase):

View File

@ -31,99 +31,85 @@ class GlanceUtilsTests(common.HeatTestCase):
def setUp(self): def setUp(self):
super(GlanceUtilsTests, self).setUp() super(GlanceUtilsTests, self).setUp()
self.glance_client = self.m.CreateMockAnything() self.glance_client = mock.MagicMock()
con = utils.dummy_context() con = utils.dummy_context()
c = con.clients c = con.clients
self.glance_plugin = c.client_plugin('glance') self.glance_plugin = c.client_plugin('glance')
self.glance_plugin._client = self.glance_client self.glance_plugin._client = self.glance_client
self.my_image = mock.MagicMock()
def test_get_image_id(self): def test_get_image_id(self):
"""Tests the get_image_id function.""" """Tests the get_image_id function."""
my_image = self.m.CreateMockAnything()
img_id = str(uuid.uuid4()) img_id = str(uuid.uuid4())
img_name = 'myfakeimage' img_name = 'myfakeimage'
my_image.id = img_id self.my_image.id = img_id
my_image.name = img_name self.my_image.name = img_name
self.glance_client.images = self.m.CreateMockAnything() self.glance_client.images.get.return_value = self.my_image
self.glance_client.images.get(img_id).AndReturn(my_image) self.glance_client.images.list.side_effect = ([self.my_image], [])
filters = {'name': img_name}
self.glance_client.images.list(filters=filters).AndReturn([my_image])
filters = {'name': 'noimage'}
self.glance_client.images.list(filters=filters).AndReturn([])
self.m.ReplayAll()
self.assertEqual(img_id, self.glance_plugin.get_image_id(img_id)) self.assertEqual(img_id, self.glance_plugin.get_image_id(img_id))
self.assertEqual(img_id, self.glance_plugin.get_image_id(img_name)) self.assertEqual(img_id, self.glance_plugin.get_image_id(img_name))
self.assertRaises(exception.ImageNotFound, self.assertRaises(exception.ImageNotFound,
self.glance_plugin.get_image_id, 'noimage') self.glance_plugin.get_image_id, 'noimage')
self.m.VerifyAll()
calls = [mock.call(filters={'name': img_name}),
mock.call(filters={'name': 'noimage'})]
self.glance_client.images.get.assert_called_once_with(img_id)
self.glance_client.images.list.assert_has_calls(calls)
def test_get_image_id_by_name_in_uuid(self): def test_get_image_id_by_name_in_uuid(self):
"""Tests the get_image_id function by name in uuid.""" """Tests the get_image_id function by name in uuid."""
my_image = self.m.CreateMockAnything()
img_id = str(uuid.uuid4()) img_id = str(uuid.uuid4())
img_name = str(uuid.uuid4()) img_name = str(uuid.uuid4())
my_image.id = img_id self.my_image.id = img_id
my_image.name = img_name self.my_image.name = img_name
self.glance_client.images = self.m.CreateMockAnything() self.glance_client.images.get.side_effect = [
self.glance_client.images.get(img_name).AndRaise( glance_exceptions.HTTPNotFound()]
glance_exceptions.HTTPNotFound()) self.glance_client.images.list.return_value = [self.my_image]
filters = {'name': img_name}
self.glance_client.images.list(
filters=filters).MultipleTimes().AndReturn([my_image])
self.m.ReplayAll()
self.assertEqual(img_id, self.glance_plugin.get_image_id(img_name)) self.assertEqual(img_id, self.glance_plugin.get_image_id(img_name))
self.m.VerifyAll() self.glance_client.images.get.assert_called_once_with(img_name)
self.glance_client.images.list.assert_called_once_with(
filters={'name': img_name})
def test_get_image_id_glance_exception(self): def test_get_image_id_glance_exception(self):
"""Test get_image_id when glance raises an exception.""" """Test get_image_id when glance raises an exception."""
# Simulate HTTP exception # Simulate HTTP exception
self.glance_client.images = self.m.CreateMockAnything()
img_name = str(uuid.uuid4()) img_name = str(uuid.uuid4())
filters = {'name': img_name} self.glance_client.images.list.side_effect = [
self.glance_client.images.list(filters=filters).AndRaise( glance_exceptions.ClientException("Error")]
glance_exceptions.ClientException("Error"))
self.m.ReplayAll()
expected_error = "Error retrieving image list from glance: Error" expected_error = "Error retrieving image list from glance: Error"
e = self.assertRaises(exception.Error, e = self.assertRaises(exception.Error,
self.glance_plugin.get_image_id_by_name, self.glance_plugin.get_image_id_by_name,
img_name) img_name)
self.assertEqual(expected_error, six.text_type(e)) self.assertEqual(expected_error, six.text_type(e))
self.m.VerifyAll() self.glance_client.images.list.assert_called_once_with(
filters={'name': img_name})
def test_get_image_id_not_found(self): def test_get_image_id_not_found(self):
"""Tests the get_image_id function while image is not found.""" """Tests the get_image_id function while image is not found."""
my_image = self.m.CreateMockAnything()
img_name = str(uuid.uuid4()) img_name = str(uuid.uuid4())
my_image.name = img_name self.glance_client.images.get.side_effect = [
self.glance_client.images = self.m.CreateMockAnything() glance_exceptions.HTTPNotFound()]
self.glance_client.images.get(img_name).AndRaise( self.glance_client.images.list.return_value = []
glance_exceptions.HTTPNotFound())
filters = {'name': img_name}
self.glance_client.images.list(
filters=filters).MultipleTimes().AndReturn([])
self.m.ReplayAll()
self.assertRaises(exception.ImageNotFound, self.assertRaises(exception.ImageNotFound,
self.glance_plugin.get_image_id, img_name) self.glance_plugin.get_image_id, img_name)
self.m.VerifyAll() self.glance_client.images.get.assert_called_once_with(img_name)
self.glance_client.images.list.assert_called_once_with(
filters={'name': img_name})
def test_get_image_id_name_ambiguity(self): def test_get_image_id_name_ambiguity(self):
"""Tests the get_image_id function while name ambiguity .""" """Tests the get_image_id function while name ambiguity ."""
my_image = self.m.CreateMockAnything()
img_name = 'ambiguity_name' img_name = 'ambiguity_name'
my_image.name = img_name self.my_image.name = img_name
image_list = [my_image, my_image]
self.glance_client.images = self.m.CreateMockAnything() self.glance_client.images.list.return_value = [self.my_image,
filters = {'name': img_name} self.my_image]
self.glance_client.images.list(
filters=filters).MultipleTimes().AndReturn(image_list)
self.m.ReplayAll()
self.assertRaises(exception.PhysicalResourceNameAmbiguity, self.assertRaises(exception.PhysicalResourceNameAmbiguity,
self.glance_plugin.get_image_id, img_name) self.glance_plugin.get_image_id, img_name)
self.m.VerifyAll() self.glance_client.images.list.assert_called_once_with(
filters={'name': img_name})
class ImageConstraintTest(common.HeatTestCase): class ImageConstraintTest(common.HeatTestCase):

View File

@ -30,7 +30,7 @@ from heat.tests.v1_1 import fakes as fakes_v1_1
class NovaClientPluginTestCase(common.HeatTestCase): class NovaClientPluginTestCase(common.HeatTestCase):
def setUp(self): def setUp(self):
super(NovaClientPluginTestCase, self).setUp() super(NovaClientPluginTestCase, self).setUp()
self.nova_client = self.m.CreateMockAnything() self.nova_client = mock.MagicMock()
con = utils.dummy_context() con = utils.dummy_context()
c = con.clients c = con.clients
self.nova_plugin = c.client_plugin('nova') self.nova_plugin = c.client_plugin('nova')
@ -44,7 +44,7 @@ class NovaClientPluginTests(NovaClientPluginTestCase):
""" """
def test_get_ip(self): def test_get_ip(self):
my_image = self.m.CreateMockAnything() my_image = mock.MagicMock()
my_image.addresses = { my_image.addresses = {
'public': [{'version': 4, 'public': [{'version': 4,
'addr': '4.5.6.7'}, 'addr': '4.5.6.7'},
@ -69,61 +69,53 @@ class NovaClientPluginTests(NovaClientPluginTestCase):
"""Tests the get_flavor_id function.""" """Tests the get_flavor_id function."""
flav_id = str(uuid.uuid4()) flav_id = str(uuid.uuid4())
flav_name = 'X-Large' flav_name = 'X-Large'
my_flavor = self.m.CreateMockAnything() my_flavor = mock.MagicMock()
my_flavor.name = flav_name my_flavor.name = flav_name
my_flavor.id = flav_id my_flavor.id = flav_id
self.nova_client.flavors = self.m.CreateMockAnything() self.nova_client.flavors.list.return_value = [my_flavor]
self.nova_client.flavors.list().MultipleTimes().AndReturn([my_flavor])
self.m.ReplayAll()
self.assertEqual(flav_id, self.nova_plugin.get_flavor_id(flav_name)) self.assertEqual(flav_id, self.nova_plugin.get_flavor_id(flav_name))
self.assertEqual(flav_id, self.nova_plugin.get_flavor_id(flav_id)) self.assertEqual(flav_id, self.nova_plugin.get_flavor_id(flav_id))
self.assertRaises(exception.FlavorMissing, self.assertRaises(exception.FlavorMissing,
self.nova_plugin.get_flavor_id, 'noflavor') self.nova_plugin.get_flavor_id, 'noflavor')
self.m.VerifyAll() self.assertEqual(3, self.nova_client.flavors.list.call_count)
self.assertEqual([(), (), ()],
self.nova_client.flavors.list.call_args_list)
def test_get_keypair(self): def test_get_keypair(self):
"""Tests the get_keypair function.""" """Tests the get_keypair function."""
my_pub_key = 'a cool public key string' my_pub_key = 'a cool public key string'
my_key_name = 'mykey' my_key_name = 'mykey'
my_key = self.m.CreateMockAnything() my_key = mock.MagicMock()
my_key.public_key = my_pub_key my_key.public_key = my_pub_key
my_key.name = my_key_name my_key.name = my_key_name
self.nova_client.keypairs = self.m.CreateMockAnything() self.nova_client.keypairs.get.side_effect = [
self.nova_client.keypairs.get( my_key, nova_exceptions.NotFound(404)]
my_key_name).AndReturn(my_key)
self.nova_client.keypairs.get(
'notakey').AndRaise(nova_exceptions.NotFound(404))
self.m.ReplayAll()
self.assertEqual(my_key, self.nova_plugin.get_keypair(my_key_name)) self.assertEqual(my_key, self.nova_plugin.get_keypair(my_key_name))
self.assertRaises(exception.UserKeyPairMissing, self.assertRaises(exception.UserKeyPairMissing,
self.nova_plugin.get_keypair, 'notakey') self.nova_plugin.get_keypair, 'notakey')
self.m.VerifyAll() calls = [mock.call(my_key_name),
mock.call('notakey')]
self.nova_client.keypairs.get.assert_has_calls(calls)
def test_get_server(self): def test_get_server(self):
"""Tests the get_server function.""" """Tests the get_server function."""
my_server = self.m.CreateMockAnything() my_server = mock.MagicMock()
self.nova_client.servers = self.m.CreateMockAnything() self.nova_client.servers.get.side_effect = [
self.nova_client.servers.get('my_server').AndReturn(my_server) my_server, nova_exceptions.NotFound(404)]
self.nova_client.servers.get('idontexist').AndRaise(
nova_exceptions.NotFound(404))
self.m.ReplayAll()
self.assertEqual(my_server, self.nova_plugin.get_server('my_server')) self.assertEqual(my_server, self.nova_plugin.get_server('my_server'))
self.assertRaises(exception.ServerNotFound, self.assertRaises(exception.ServerNotFound,
self.nova_plugin.get_server, 'idontexist') self.nova_plugin.get_server, 'idontexist')
self.m.VerifyAll() calls = [mock.call('my_server'),
mock.call('idontexist')]
self.nova_client.servers.get.assert_has_calls(calls)
def test_get_network_id_by_label(self): def test_get_network_id_by_label(self):
"""Tests the get_net_id_by_label function.""" """Tests the get_net_id_by_label function."""
net = self.m.CreateMockAnything() net = mock.MagicMock()
net.id = str(uuid.uuid4()) net.id = str(uuid.uuid4())
self.nova_client.networks = self.m.CreateMockAnything() self.nova_client.networks.find.side_effect = [
self.nova_client.networks.find(label='net_label').AndReturn( net, nova_exceptions.NotFound(404),
net) nova_exceptions.NoUniqueMatch()]
self.nova_client.networks.find(label='idontexist').AndRaise(
nova_exceptions.NotFound(404))
self.nova_client.networks.find(label='notUnique').AndRaise(
nova_exceptions.NoUniqueMatch())
self.m.ReplayAll()
self.assertEqual(net.id, self.assertEqual(net.id,
self.nova_plugin.get_net_id_by_label('net_label')) self.nova_plugin.get_net_id_by_label('net_label'))
@ -138,21 +130,21 @@ class NovaClientPluginTests(NovaClientPluginTestCase):
expected = ('Multiple physical resources were found ' expected = ('Multiple physical resources were found '
'with name (notUnique)') 'with name (notUnique)')
self.assertIn(expected, six.text_type(exc)) self.assertIn(expected, six.text_type(exc))
self.m.VerifyAll() calls = [mock.call(label='net_label'),
mock.call(label='idontexist'),
mock.call(label='notUnique')]
self.nova_client.networks.find.assert_has_calls(calls)
def test_get_nova_network_id(self): def test_get_nova_network_id(self):
"""Tests the get_nova_network_id function.""" """Tests the get_nova_network_id function."""
net = self.m.CreateMockAnything() net = mock.MagicMock()
net.id = str(uuid.uuid4()) net.id = str(uuid.uuid4())
not_existent_net_id = str(uuid.uuid4()) not_existent_net_id = str(uuid.uuid4())
self.nova_client.networks = self.m.CreateMockAnything() self.nova_client.networks.get.side_effect = [
self.nova_client.networks.get(net.id).AndReturn(net) net, nova_exceptions.NotFound(404)]
self.nova_client.networks.get(not_existent_net_id).AndRaise( self.nova_client.networks.find.side_effect = [
nova_exceptions.NotFound(404)) nova_exceptions.NotFound(404)]
self.nova_client.networks.find(label=not_existent_net_id).AndRaise(
nova_exceptions.NotFound(404))
self.m.ReplayAll()
self.assertEqual(net.id, self.assertEqual(net.id,
self.nova_plugin.get_nova_network_id(net.id)) self.nova_plugin.get_nova_network_id(net.id))
exc = self.assertRaises( exc = self.assertRaises(
@ -162,7 +154,11 @@ class NovaClientPluginTests(NovaClientPluginTestCase):
not_existent_net_id) not_existent_net_id)
self.assertIn(expected, six.text_type(exc)) self.assertIn(expected, six.text_type(exc))
self.m.VerifyAll() calls = [mock.call(net.id),
mock.call(not_existent_net_id)]
self.nova_client.networks.get.assert_has_calls(calls)
self.nova_client.networks.find.assert_called_once_with(
label=not_existent_net_id)
def test_get_status(self): def test_get_status(self):
server = self.m.CreateMockAnything() server = self.m.CreateMockAnything()
@ -177,54 +173,36 @@ class NovaClientPluginTests(NovaClientPluginTestCase):
class NovaUtilsRefreshServerTests(NovaClientPluginTestCase): class NovaUtilsRefreshServerTests(NovaClientPluginTestCase):
msg = ("ClientException: The server has either erred or is "
"incapable of performing the requested operation.")
def test_successful_refresh(self): scenarios = [
server = self.m.CreateMockAnything() ('successful_refresh', dict(
server.get().AndReturn(None) value=None,
self.m.ReplayAll() e_raise=False)),
('overlimit_error', dict(
value=nova_exceptions.OverLimit(413, "limit reached"),
e_raise=False)),
('500_error', dict(
value=nova_exceptions.ClientException(500, msg),
e_raise=False)),
('503_error', dict(
value=nova_exceptions.ClientException(503, msg),
e_raise=False)),
('unhandled_exception', dict(
value=nova_exceptions.ClientException(501, msg),
e_raise=True)),
]
self.assertIsNone(self.nova_plugin.refresh_server(server)) def test_refresh(self):
self.m.VerifyAll() server = mock.MagicMock()
server.get.side_effect = [self.value]
def test_overlimit_error(self): if self.e_raise:
server = mock.Mock() self.assertRaises(nova_exceptions.ClientException,
server.get.side_effect = nova_exceptions.OverLimit( self.nova_plugin.refresh_server, server)
413, "limit reached") else:
self.assertIsNone(self.nova_plugin.refresh_server(server)) self.assertIsNone(self.nova_plugin.refresh_server(server))
server.get.assert_called_once_with()
def test_500_error(self):
server = self.m.CreateMockAnything()
msg = ("ClientException: The server has either erred or is "
"incapable of performing the requested operation.")
server.get().AndRaise(
nova_exceptions.ClientException(500, msg))
self.m.ReplayAll()
self.assertIsNone(self.nova_plugin.refresh_server(server))
self.m.VerifyAll()
def test_503_error(self):
server = self.m.CreateMockAnything()
msg = ("ClientException: The server has either erred or is "
"incapable of performing the requested operation.")
server.get().AndRaise(
nova_exceptions.ClientException(503, msg))
self.m.ReplayAll()
self.assertIsNone(self.nova_plugin.refresh_server(server))
self.m.VerifyAll()
def test_unhandled_exception(self):
server = self.m.CreateMockAnything()
msg = ("ClientException: The server has either erred or is "
"incapable of performing the requested operation.")
server.get().AndRaise(
nova_exceptions.ClientException(501, msg))
self.m.ReplayAll()
self.assertRaises(nova_exceptions.ClientException,
self.nova_plugin.refresh_server, server)
self.m.VerifyAll()
class NovaUtilsUserdataTests(NovaClientPluginTestCase): class NovaUtilsUserdataTests(NovaClientPluginTestCase):
@ -351,46 +329,46 @@ class FlavorConstraintTest(common.HeatTestCase):
def test_validate(self): def test_validate(self):
client = fakes_v1_1.FakeClient() client = fakes_v1_1.FakeClient()
self.stub_keystoneclient() self.stub_keystoneclient()
self.m.StubOutWithMock(nova.NovaClientPlugin, '_create') self.patchobject(nova.NovaClientPlugin, '_create', return_value=client)
nova.NovaClientPlugin._create().AndReturn(client) client.flavors = mock.MagicMock()
client.flavors = self.m.CreateMockAnything()
flavor = collections.namedtuple("Flavor", ["id", "name"]) flavor = collections.namedtuple("Flavor", ["id", "name"])
flavor.id = "1234" flavor.id = "1234"
flavor.name = "foo" flavor.name = "foo"
client.flavors.list().MultipleTimes().AndReturn([flavor]) client.flavors.list.return_value = [flavor]
self.m.ReplayAll()
constraint = nova.FlavorConstraint() constraint = nova.FlavorConstraint()
ctx = utils.dummy_context() ctx = utils.dummy_context()
self.assertFalse(constraint.validate("bar", ctx)) self.assertFalse(constraint.validate("bar", ctx))
self.assertTrue(constraint.validate("foo", ctx)) self.assertTrue(constraint.validate("foo", ctx))
self.assertTrue(constraint.validate("1234", ctx)) self.assertTrue(constraint.validate("1234", ctx))
nova.NovaClientPlugin._create.assert_called_once_with()
self.m.VerifyAll() self.assertEqual(3, client.flavors.list.call_count)
self.assertEqual([(), (), ()],
client.flavors.list.call_args_list)
class KeypairConstraintTest(common.HeatTestCase): class KeypairConstraintTest(common.HeatTestCase):
def test_validation(self): def test_validation(self):
client = fakes_v1_1.FakeClient() client = fakes_v1_1.FakeClient()
self.m.StubOutWithMock(nova.NovaClientPlugin, '_create') self.patchobject(nova.NovaClientPlugin, '_create', return_value=client)
nova.NovaClientPlugin._create().AndReturn(client) client.keypairs = mock.MagicMock()
client.keypairs = self.m.CreateMockAnything()
key = collections.namedtuple("Key", ["name"]) key = collections.namedtuple("Key", ["name"])
key.name = "foo" key.name = "foo"
client.keypairs.get('bar').AndRaise(fakes_v1_1.fake_exception()) client.keypairs.get.side_effect = [
client.keypairs.get(key.name).AndReturn(key) fakes_v1_1.fake_exception(), key]
self.m.ReplayAll()
constraint = nova.KeypairConstraint() constraint = nova.KeypairConstraint()
ctx = utils.dummy_context() ctx = utils.dummy_context()
self.assertFalse(constraint.validate("bar", ctx)) self.assertFalse(constraint.validate("bar", ctx))
self.assertTrue(constraint.validate("foo", ctx)) self.assertTrue(constraint.validate("foo", ctx))
self.assertTrue(constraint.validate("", ctx)) self.assertTrue(constraint.validate("", ctx))
nova.NovaClientPlugin._create.assert_called_once_with()
self.m.VerifyAll() calls = [mock.call('bar'),
mock.call(key.name)]
client.keypairs.get.assert_has_calls(calls)
class ConsoleUrlsTest(common.HeatTestCase): class ConsoleUrlsTest(common.HeatTestCase):