From f7c0472cdc62a2fab4ad4bd87ffab0d95d258286 Mon Sep 17 00:00:00 2001 From: Markus Opolka Date: Fri, 19 Jun 2020 14:26:59 +0200 Subject: [PATCH] Add JSON parsing on HTTPError - Only if response contains JSON --- check_http_json.py | 6 +++++- test/test_main.py | 39 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/check_http_json.py b/check_http_json.py index 85f76a5..6b74bd9 100755 --- a/check_http_json.py +++ b/check_http_json.py @@ -609,7 +609,11 @@ def main(cliargs): json_data = response.read() except HTTPError as e: - nagios.append_unknown(" HTTPError[%s], url:%s" % (str(e.code), url)) + # Try to recover from HTTP Error, if there is JSON in the response + if "json" in e.info().get_content_subtype(): + json_data = e.read() + else: + nagios.append_unknown(" HTTPError[%s], url:%s" % (str(e.code), url)) except URLError as e: nagios.append_critical(" URLError[%s], url:%s" % (str(e.reason), url)) diff --git a/test/test_main.py b/test/test_main.py index 93edc70..47d77c7 100644 --- a/test/test_main.py +++ b/test/test_main.py @@ -50,7 +50,7 @@ class MainTest(unittest.TestCase): @mock.patch('builtins.print') @mock.patch('urllib.request.urlopen') - def test_main_with_error(self, mock_request, mock_print): + def test_main_with_parse_error(self, mock_request, mock_print): args = '-H localhost'.split(' ') mock_request.return_value = MockResponse(content='not JSON') @@ -58,5 +58,40 @@ class MainTest(unittest.TestCase): with self.assertRaises(SystemExit) as test: main(args) - # Returns Parser Error + self.assertTrue('Parser error' in str(mock_print.call_args)) self.assertEqual(test.exception.code, 3) + + @mock.patch('builtins.print') + def test_main_with_url_error(self, mock_print): + args = '-H localhost'.split(' ') + + with self.assertRaises(SystemExit) as test: + main(args) + + self.assertTrue('URLError' in str(mock_print.call_args)) + self.assertEqual(test.exception.code, 3) + + @mock.patch('builtins.print') + @mock.patch('urllib.request.urlopen') + def test_main_with_http_error_no_json(self, mock_request, mock_print): + args = '-H localhost'.split(' ') + + mock_request.return_value = MockResponse(content='not JSON', status_code=503) + + with self.assertRaises(SystemExit) as test: + main(args) + + self.assertTrue('Parser error' in str(mock_print.call_args)) + self.assertEqual(test.exception.code, 3) + + @mock.patch('builtins.print') + @mock.patch('urllib.request.urlopen') + def test_main_with_http_error_valid_json(self, mock_request, mock_print): + args = '-H localhost'.split(' ') + + mock_request.return_value = MockResponse(status_code=503) + + with self.assertRaises(SystemExit) as test: + main(args) + + self.assertEqual(test.exception.code, 0)