Merge "Update untils_find_resource to support no unique matches error"

This commit is contained in:
Jenkins 2016-06-22 21:01:28 +00:00 committed by Gerrit Code Review
commit 977c0be753
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

@ -152,15 +152,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):