From 2b5fcd60c4b5ca37e347657879a28af011729dbd Mon Sep 17 00:00:00 2001 From: Dan Florea Date: Fri, 8 Mar 2013 14:15:54 -0800 Subject: [PATCH] Catch KeyError exception as early as possible when there is no matching data on the server. When the server does not have any data matching the requested response_key, it can still return successfully. A subsequent lookup in the returned data throws a KeyError exception. The simple fix for this is to catch the KeyError exception and return an empty list. An empty list, rather than None, is required because the calling code expects an iterable. The exception is caught as early as possible after the server returns from the GET request. The end result is that the CLI user sees an empty result when the requested data doesn't exist on the server. Prior to this fix the keyError exception was propagated all the way to the user, causing a confusing message to be printed. Also added associated unit test. Fixes bug #1111972 Change-Id: I88ba658f8be7e7edf255ef9f7d83ba87f36f4efc --- ceilometerclient/common/base.py | 5 ++++- tests/v1/test_samples.py | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/ceilometerclient/common/base.py b/ceilometerclient/common/base.py index c29ac18..02ecdae 100644 --- a/ceilometerclient/common/base.py +++ b/ceilometerclient/common/base.py @@ -56,7 +56,10 @@ class Manager(object): obj_class = self.resource_class if response_key: - data = body[response_key] + try: + data = body[response_key] + except KeyError: + return [] else: data = body return [obj_class(self, res, loaded=True) for res in data if res] diff --git a/tests/v1/test_samples.py b/tests/v1/test_samples.py index ab7dc08..88da953 100644 --- a/tests/v1/test_samples.py +++ b/tests/v1/test_samples.py @@ -111,6 +111,12 @@ fixtures = { ]}, ), }, + '/v1/meters': { + 'GET': ( + {}, + {'meters': []}, + ), + }, } @@ -120,6 +126,14 @@ class SampleManagerTest(unittest.TestCase): self.api = utils.FakeAPI(fixtures) self.mgr = ceilometerclient.v1.meters.SampleManager(self.api) + def test_list_all(self): + samples = list(self.mgr.list(counter_name=None)) + expect = [ + ('GET', '/v1/meters', {}, None), + ] + self.assertEqual(self.api.calls, expect) + self.assertEqual(len(samples), 0) + def test_list_by_source(self): samples = list(self.mgr.list(source='openstack', counter_name='this'))