Update untils_find_resource to support no unique matches error

Utils_find_resource function cannot raise a no-unique-match error
when manager (eg. image) has no find() function.
It just deletes the first match.

Change-Id: I0caa9d3985ce5c01ef418f62d3ee5677886e0240
This commit is contained in:
sunyajing 2016-06-17 10:57:22 +08:00
parent 4e3d973209
commit ce40687297
2 changed files with 41 additions and 3 deletions

View File

@ -431,6 +431,36 @@ class TestFindResource(test_utils.TestCase):
self.manager.get.assert_called_with(self.name)
self.manager.find.assert_called_with(name=self.name)
def test_find_resource_silly_resource_no_unique_match(self):
# We need a resource with no resource_class for this test, start fresh
self.manager = mock.Mock()
self.manager.get = mock.Mock(side_effect=Exception('Boom!'))
self.manager.find = mock.Mock(
side_effect=AttributeError(
"'Controller' object has no attribute 'find'",
)
)
silly_resource = FakeOddballResource(
None,
{'id': '12345', 'name': self.name},
loaded=True,
)
silly_resource_same = FakeOddballResource(
None,
{'id': 'abcde', 'name': self.name},
loaded=True,
)
self.manager.list = mock.Mock(return_value=[silly_resource,
silly_resource_same])
result = self.assertRaises(exceptions.CommandError,
utils.find_resource,
self.manager,
self.name)
self.assertEqual("More than one resource exists "
"with the name or ID 'legos'.", str(result))
self.manager.get.assert_called_with(self.name)
self.manager.find.assert_called_with(name=self.name)
def test_format_dict(self):
expected = "a='b', c='d', e='f'"
self.assertEqual(expected,

View File

@ -151,15 +151,23 @@ def find_resource(manager, name_or_id, **kwargs):
else:
pass
# for client with no find function
count = 0
for resource in manager.list():
# short circuit and return the first match
if (resource.get('id') == name_or_id or
resource.get('name') == name_or_id):
return resource
else:
count += 1
_resource = resource
if count == 0:
# we found no match, report back this error:
msg = _("Could not find resource %s")
raise exceptions.CommandError(msg % name_or_id)
elif count == 1:
return _resource
else:
# we found multiple matches, report back this error
msg = _("More than one resource exists with the name or ID '%s'.")
raise exceptions.CommandError(msg % name_or_id)
def format_dict(data):