Merge "Fix Prometheus fetcher error"

This commit is contained in:
Zuul 2019-06-06 07:50:48 +00:00 committed by Gerrit Code Review
commit f68cf6fad2
2 changed files with 42 additions and 35 deletions

View File

@ -126,22 +126,16 @@ class PrometheusFetcher(fetcher.BaseFetcher):
scope_ids = [ scope_ids = [
item['metric'][scope_attribute] for item in result item['metric'][scope_attribute] for item in result
if item['metric'][scope_attribute] if scope_attribute in item['metric'].keys()
] ]
except KeyError as e: except KeyError:
missing_key = e.args[0] msg = (
if missing_key in ['data', 'result', 'metric']: 'Unexpected Prometheus server response '
msg = ( '"{}" for "{}"'
'Unexpected Prometheus server response ' ).format(
'"{}" for "{}"' res,
).format( query,
res, )
query,
)
else:
msg = '"{}" not found in Prometheus server response'.format(
missing_key
)
raise PrometheusFetcherError(msg) raise PrometheusFetcherError(msg)
# Returning unique ids # Returning unique ids

View File

@ -60,6 +60,39 @@ class PrometheusFetcherTest(tests.TestCase):
self.fetcher.get_tenants() self.fetcher.get_tenants()
mock_get.assert_called_once_with(query) mock_get.assert_called_once_with(query)
def test_get_tenants(self):
response = mock.patch(
'cloudkitty.common.prometheus_client.PrometheusClient.get_instant',
return_value={
'data': {
'result': [
{
'metric': {},
'value': [42, 1337],
},
{
'metric': {'namespace': 'scope_id1'},
'value': [42, 1337],
},
{
'metric': {'namespace': 'scope_id2'},
'value': [42, 1337],
},
{
'metric': {'namespace': 'scope_id3'},
'value': [42, 1337],
},
]
}
},
)
with response:
scopes = self.fetcher.get_tenants()
self.assertItemsEqual(scopes, [
'scope_id1', 'scope_id2', 'scope_id3',
])
def test_get_tenants_raises_exception(self): def test_get_tenants_raises_exception(self):
no_response = mock.patch( no_response = mock.patch(
'cloudkitty.common.prometheus_client.PrometheusClient.get_instant', 'cloudkitty.common.prometheus_client.PrometheusClient.get_instant',
@ -73,26 +106,6 @@ class PrometheusFetcherTest(tests.TestCase):
) )
def test_get_tenants_raises_exception2(self): def test_get_tenants_raises_exception2(self):
no_response = mock.patch(
'cloudkitty.common.prometheus_client.PrometheusClient.get_instant',
return_value={
'data': {
'result': [{
'metric': {
'foo': 'bar'
}
}]
}
},
)
with no_response:
self.assertRaises(
prometheus.PrometheusFetcherError,
self.fetcher.get_tenants,
)
def test_get_tenants_raises_exception3(self):
invalid_response = mock.patch( invalid_response = mock.patch(
'cloudkitty.common.prometheus_client.PrometheusClient.get_instant', 'cloudkitty.common.prometheus_client.PrometheusClient.get_instant',
side_effect=PrometheusResponseError, side_effect=PrometheusResponseError,