From e4801227bf90b8b55386e5b036324a39353313d4 Mon Sep 17 00:00:00 2001 From: Markus Opolka Date: Tue, 3 Mar 2020 15:02:09 +0100 Subject: [PATCH] Add boundary check for SubArrayElement function - Fixes Issue 34 --- check_http_json.py | 3 +++ test/test_check_http_json.py | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/check_http_json.py b/check_http_json.py index e4d70c3..3708266 100755 --- a/check_http_json.py +++ b/check_http_json.py @@ -108,6 +108,7 @@ def getSubArrayElement(self, key, data): index = int(key[key.find(self.arrayOpener) + 1:key.find(self.arrayCloser)]) remainingKey = key[key.find(self.arrayCloser + self.separator) + 2:] + if key.find(self.arrayCloser + self.separator) == -1: remainingKey = key[key.find(self.arrayCloser) + 1:] if subElemKey in data: @@ -115,6 +116,8 @@ def getSubArrayElement(self, key, data): return self.get(remainingKey, data[subElemKey][index]) else: return (None, 'not_found') + if index >= len(data): + return (None, 'not_found') else: if not subElemKey: return self.get(remainingKey, data[index]) diff --git a/test/test_check_http_json.py b/test/test_check_http_json.py index 678b998..c7d61f9 100644 --- a/test/test_check_http_json.py +++ b/test/test_check_http_json.py @@ -220,3 +220,26 @@ def test_separator(self): { "gauges": { "jvm.buffers.direct.capacity": [ {"value": 215415},{"value": 1235}]}}]''', WARNING_CODE) + + def test_array_with_missing_element(self): + """ + See https://github.com/drewkerrigan/nagios-http-json/issues/34 + """ + rules = RulesHelper() + + # This should simply work + data = '[{"Node": "there"}]' + self.check_data(rules.dash_q(['(0).Node,there']), data, OK_CODE) + + # This should warn us + data = '[{"Node": "othervalue"}]' + self.check_data(rules.dash_q(['(0).Node,there']), data, WARNING_CODE) + + # # This should not throw an IndexError + data = '[{"Node": "foobar"}]' + self.check_data(rules.dash_q(['(0).Node,foobar', '(1).Node,missing']), data, WARNING_CODE) + self.check_data(rules.dash_q(['(0).Node,foobar', '(1).Node,missing', '(2).Node,alsomissing']), data, WARNING_CODE) + + # This should not throw a KeyError + data = '{}' + self.check_data(rules.dash_q(['(0).Node,foobar', '(1).Node,missing']), data, WARNING_CODE)