37 Commits

Author SHA1 Message Date
Markus Opolka
dfcdf4d872 Rework JsonHelper.get() to work with bracket in keys 2024-03-22 16:19:43 +01:00
Markus Opolka
ce9c5fdada Merge pull request #85 from drewkerrigan/extend-tests
Extend tests for array syntax
2024-03-22 15:52:10 +01:00
Markus Opolka
27c710b2ea Extend tests for array syntax 2024-03-22 15:45:25 +01:00
Markus Opolka
dddf8432d6 Merge pull request #80 from mho21/master
disabled check_hostname to prevent error message when setting CERT_NONE
2022-10-04 16:26:06 +02:00
Markus Hof
739c093702 disabled check_hostname to prevent error message when setting CERT_NONE 2022-10-04 16:04:12 +02:00
Markus Opolka
46271c961b Bump version to 2.1.2 2022-09-15 15:25:38 +02:00
Markus Opolka
49b338bdb6 Merge pull request #79 from drewkerrigan/feature/http-method
Add CLI Flag to change HTTP method
2022-09-15 15:22:48 +02:00
Markus Opolka
9f41fc491e Add CLI flag to change HTTP method 2022-09-09 17:28:35 +02:00
Markus Opolka
3a22b712ab Fix deprecation of PROTOCOL_TLS 2022-09-09 17:26:23 +02:00
Markus Opolka
9626fc4464 Merge pull request #78 from drewkerrigan/docs/update-repo
Update Makefile and Workflows
2022-09-08 10:09:43 +02:00
Markus Opolka
c54a0040a0 Update pylint config 2022-09-08 10:08:39 +02:00
Markus Opolka
ffd96dd59f Update GitHub Workflow 2022-09-08 10:04:20 +02:00
Markus Opolka
0572c2f494 Update Makefile
- Use python from venv
2022-09-08 10:01:23 +02:00
Markus Opolka
2e6eaeea59 Merge pull request #77 from K0nne/patch-1
fix missing type conversion for --data
2022-09-08 09:59:28 +02:00
K0nne
428a5a6d3a fix missing type conversion for --data
The parameter --data is handled as type string, but the method urlopen() only accepts the datatype byte.
Before this fix you will get: "TypeError: POST data should be  bytes, an iterable of bytes, or a filer object. It cannot be of type str."
This PR solves this.
2022-07-27 13:30:25 +02:00
Markus Opolka
e3ac06864d Merge pull request #68 from ccin2p3/feature/load_default_ca_certs
[TLS] Always load system default C.A files
2021-01-22 10:39:33 +01:00
Rémi Ferrand
63542f3226 If TLS is enabled, context now loads the system default C.A files
* This allows system wide deployed C.A to be used without any further
  configuration.
2021-01-21 12:02:41 +01:00
Markus Opolka
cdb2474ee0 Update README 2020-11-24 20:27:40 +01:00
Markus Opolka
2821a1ae66 Merge pull request #66 from drewkerrigan/array-bug
Fix conditional check on empty data.
2020-09-14 10:36:14 +02:00
Markus Opolka
831bfdf97b Merge pull request #65 from alesc/patch-1
Update icinga2_check_command_definition.conf
2020-09-12 08:21:01 +02:00
alesc
f612277772 Update icinga2_check_command_definition.conf
small error in icinga2 conf definition, --key_metricS does not exist --key_metric does.
2020-09-11 10:18:02 +02:00
Markus Opolka
1f440e0ff5 Fix conditional check on empty data.
Fixes issue #64
2020-07-15 08:07:16 +02:00
Markus Opolka
c23ebac77a Merge pull request #63 from drewkerrigan/v2-1
Release 2.1
2020-07-03 09:58:55 +02:00
Markus Opolka
a014944981 Merge pull request #62 from drewkerrigan/key-equals-empty
Add handling of empty JSON return values
2020-07-03 09:04:53 +02:00
Markus Opolka
47a37556ba Merge branch 'v2-1' into key-equals-empty 2020-07-03 09:03:21 +02:00
Markus Opolka
41279cad2c Merge pull request #60 from drewkerrigan/http-json
Parse JSON on HTTPError, if JSON in response
2020-07-03 09:02:14 +02:00
Markus Opolka
f7c0472cdc Add JSON parsing on HTTPError
- Only if response contains JSON
2020-07-02 11:35:23 +02:00
Markus Opolka
25fb340bbb Add handling of empty JSON return values
- Will now throw a CRITICAL
2020-06-26 10:39:37 +02:00
Markus Opolka
47bdea7fc5 Add spaces to debug output 2020-06-26 10:31:20 +02:00
Markus Opolka
866a12ea07 Add JSON parsing on HTTPError
- Only if response contains JSON
2020-06-19 14:26:59 +02:00
Markus Opolka
d1e585b2dd Adjust pylint for new function 2020-06-19 13:16:07 +02:00
Markus Opolka
941afeed89 Move main entrypoint to own function for simpler testing 2020-06-19 13:12:51 +02:00
Markus Opolka
b9a583f281 Add Makefile and requirements.txt for easier testing 2020-06-19 13:12:48 +02:00
Markus Opolka
4c89a8a93d Update README 2020-04-03 11:53:00 +02:00
Markus Opolka
73557b3657 Merge pull request #58 from bb-Ricardo/next-release
added icinga2 command definitions
2020-04-03 11:50:29 +02:00
Ricardo Bartels
aad2376ac0 added missing cli args for V2.0 2020-04-02 08:39:42 +02:00
Ricardo Bartels
26a1b3dbe8 added icinga2 command definitions 2019-05-10 11:21:34 +02:00
11 changed files with 383 additions and 65 deletions

View File

@@ -7,21 +7,20 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
matrix: matrix:
python-version: [3.6, 3.7, 3.8] python-version: [3.8, 3,9]
name: GitHub Action name: GitHub Action
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v2 uses: actions/checkout@v2
- name: Install dependencies
run: |
python -m pip install -r requirements-dev.txt
- name: Lint - name: Lint
run: | run: |
pip3 install --upgrade pip wheel setuptools make lint
pip3 install pylint
python3 -m pylint check_http_json.py
- name: Unit Test - name: Unit Test
run: | run: |
python3 -m unittest discover make test
- name: Coverage - name: Coverage
run: | run: |
pip3 install coverage make coverage
python3 -m coverage run -m unittest discover
python3 -m coverage report -m --include check_http_json.py

View File

@@ -1,5 +1,21 @@
# pylint config # pylint config
[MESSAGES CONTROL]
disable=line-too-long, redefined-outer-name, too-many-arguments, too-many-instance-attributes, fixme, invalid-name, superfluous-parens, missing-function-docstring, missing-module-docstring, multiple-imports, no-else-return, too-many-return-statements
[MASTER] [MASTER]
ignore-patterns=^test.* ignore-patterns=^test.*
[MESSAGES CONTROL]
disable=fixme,
consider-using-f-string,
invalid-name,
line-too-long,
missing-function-docstring,
missing-module-docstring,
multiple-imports,
no-else-return,
redefined-outer-name,
superfluous-parens,
too-many-locals,
too-many-arguments,
too-many-branches,
too-many-instance-attributes,
too-many-return-statements,
too-many-statements

9
Makefile Normal file
View File

@@ -0,0 +1,9 @@
.PHONY: lint test coverage
lint:
python -m pylint check_http_json.py
test:
python -m unittest discover
coverage:
python -m coverage run -m unittest discover
python -m coverage report -m --include check_http_json.py

View File

@@ -20,7 +20,7 @@ Executing `./check_http_json.py -h` will yield the following details:
usage: check_http_json.py [-h] [-d] [-s] -H HOST [-k] [-V] [--cacert CACERT] usage: check_http_json.py [-h] [-d] [-s] -H HOST [-k] [-V] [--cacert CACERT]
[--cert CERT] [--key KEY] [-P PORT] [-p PATH] [--cert CERT] [--key KEY] [-P PORT] [-p PATH]
[-t TIMEOUT] [-B AUTH] [-D DATA] [-A HEADERS] [-t TIMEOUT] [-B AUTH] [-D DATA] [-A HEADERS]
[-f SEPARATOR] [-f FIELD_SEPARATOR] [-F VALUE_SEPARATOR]
[-w [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]]] [-w [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]]]
[-c [KEY_THRESHOLD_CRITICAL [KEY_THRESHOLD_CRITICAL ...]]] [-c [KEY_THRESHOLD_CRITICAL [KEY_THRESHOLD_CRITICAL ...]]]
[-e [KEY_LIST [KEY_LIST ...]]] [-e [KEY_LIST [KEY_LIST ...]]]
@@ -38,7 +38,7 @@ Generic Nagios plugin which checks json values from a given endpoint against
argument specified rules and determines the status and performance data for argument specified rules and determines the status and performance data for
that service. that service.
Version: 2.0.0 (2020-03-22) Version: 2.1.2 (2022-09-15)
optional arguments: optional arguments:
-h, --help show this help message and exit -h, --help show this help message and exit
@@ -46,6 +46,8 @@ optional arguments:
-s, --ssl use TLS to connect to remote host -s, --ssl use TLS to connect to remote host
-H HOST, --host HOST remote host to query -H HOST, --host HOST remote host to query
-k, --insecure do not check server SSL certificate -k, --insecure do not check server SSL certificate
-X {GET,POST}, --request {GET,POST}
Specifies a custom request method to use when communicating with the HTTP server
-V, --version print version of this plugin -V, --version print version of this plugin
--cacert CACERT SSL CA certificate --cacert CACERT SSL CA certificate
--cert CERT SSL client certificate --cert CERT SSL client certificate
@@ -62,6 +64,8 @@ optional arguments:
-f SEPARATOR, --field_separator SEPARATOR -f SEPARATOR, --field_separator SEPARATOR
JSON Field separator, defaults to "."; Select element JSON Field separator, defaults to "."; Select element
in an array with "(" ")" in an array with "(" ")"
-F SEPARATOR, --value_separator SEPARATOR
JSON Value separator, defaults to ":";
-w [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]], --warning [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]] -w [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]], --warning [KEY_THRESHOLD_WARNING [KEY_THRESHOLD_WARNING ...]]
Warning threshold for these values Warning threshold for these values
(key1[>alias],WarnRange key2[>alias],WarnRange). (key1[>alias],WarnRange key2[>alias],WarnRange).
@@ -208,7 +212,7 @@ More info about Nagios Range format and Units of Measure can be found at [https:
### Requirements ### Requirements
* Python 3 * Python 3.6+
### Configuration ### Configuration
@@ -243,7 +247,10 @@ define command{
``` ```
More info about options in Usage. ## Icinga2 configuration
The Icinga2 command definition can be found here: (contrib/icinga2_check_command_definition.conf)
## License ## License

View File

@@ -24,8 +24,8 @@ WARNING_CODE = 1
CRITICAL_CODE = 2 CRITICAL_CODE = 2
UNKNOWN_CODE = 3 UNKNOWN_CODE = 3
__version__ = '2.0.0' __version__ = '2.1.2'
__version_date__ = '2020-03-22' __version_date__ = '2022-09-15'
class NagiosHelper: class NagiosHelper:
""" """
@@ -152,28 +152,33 @@ class JsonHelper:
(Element.Key.NestedKey). Returns (None, 'not_found') if not found (Element.Key.NestedKey). Returns (None, 'not_found') if not found
""" """
if temp_data: if temp_data != '':
data = temp_data data = temp_data
else: else:
data = self.data data = self.data
if len(key) <= 0: if len(key) <= 0:
return data return data
if key.find(self.separator) != -1 and \
key.find(self.arrayOpener) != -1:
if key.find(self.separator) != -1 and key.find(self.arrayOpener) != -1:
if key.find(self.separator) < key.find(self.arrayOpener): if key.find(self.separator) < key.find(self.arrayOpener):
return self.getSubElement(key, data) return self.getSubElement(key, data)
else: else:
return self.getSubArrayElement(key, data) return self.getSubArrayElement(key, data)
else:
if key.find(self.separator) != -1: if key.find(self.separator) != -1:
return self.getSubElement(key, data) return self.getSubElement(key, data)
else:
if key.find(self.arrayOpener) != -1: if key.find(self.arrayOpener) != -1:
# If we got an arrayOpener but the next char is not [0-9] or * then it might just be a string
# This isn't optimal since this 'update (foobar)(0)' still won't work
if key[key.find(self.arrayOpener)+1].isnumeric() or key[key.find(self.arrayOpener)+1] == "*":
return self.getSubArrayElement(key, data) return self.getSubArrayElement(key, data)
else:
if isinstance(data, dict) and key in data: if isinstance(data, dict) and key in data:
return data[key] return data[key]
else:
return (None, 'not_found') return (None, 'not_found')
def expandKey(self, key, keys): def expandKey(self, key, keys):
@@ -225,9 +230,9 @@ class JsonRuleProcessor:
if self.rules.value_separator: if self.rules.value_separator:
value_separator = self.rules.value_separator value_separator = self.rules.value_separator
self.helper = JsonHelper(self.data, separator, value_separator) self.helper = JsonHelper(self.data, separator, value_separator)
debugPrint(rules_args.debug, "rules:%s" % rules_args) debugPrint(rules_args.debug, "rules: %s" % rules_args)
debugPrint(rules_args.debug, "separator:%s" % separator) debugPrint(rules_args.debug, "separator: %s" % separator)
debugPrint(rules_args.debug, "value_separator:%s" % value_separator) debugPrint(rules_args.debug, "value_separator: %s" % value_separator)
self.metric_list = self.expandKeys(self.rules.metric_list) self.metric_list = self.expandKeys(self.rules.metric_list)
self.key_threshold_warning = self.expandKeys( self.key_threshold_warning = self.expandKeys(
self.rules.key_threshold_warning) self.rules.key_threshold_warning)
@@ -346,6 +351,8 @@ class JsonRuleProcessor:
def checkCritical(self): def checkCritical(self):
failure = '' failure = ''
if not self.data:
failure = " Empty JSON data."
if self.key_threshold_critical is not None: if self.key_threshold_critical is not None:
failure += self.checkThresholds(self.key_threshold_critical) failure += self.checkThresholds(self.key_threshold_critical)
if self.key_value_list_critical is not None: if self.key_value_list_critical is not None:
@@ -424,10 +431,12 @@ def parseArgs(args):
parser.add_argument('-s', '--ssl', action='store_true', parser.add_argument('-s', '--ssl', action='store_true',
help='use TLS to connect to remote host') help='use TLS to connect to remote host')
parser.add_argument('-H', '--host', dest='host', parser.add_argument('-H', '--host', dest='host',
required=not ('-V' in sys.argv or '--version' in sys.argv), required=not ('-V' in args or '--version' in args),
help='remote host to query') help='remote host to query')
parser.add_argument('-k', '--insecure', action='store_true', parser.add_argument('-k', '--insecure', action='store_true',
help='do not check server SSL certificate') help='do not check server SSL certificate')
parser.add_argument('-X', '--request', dest='method', default='GET', choices=['GET', 'POST'],
help='Specifies a custom request method to use when communicating with the HTTP server')
parser.add_argument('-V', '--version', action='store_true', parser.add_argument('-V', '--version', action='store_true',
help='print version of this plugin') help='print version of this plugin')
parser.add_argument('--cacert', parser.add_argument('--cacert',
@@ -524,10 +533,12 @@ def debugPrint(debug_flag, message, pretty_flag=False):
print(message) print(message)
# Program entry point def main(cliargs):
if __name__ == "__main__": """
Main entrypoint for CLI
"""
args = parseArgs(sys.argv[1:]) args = parseArgs(cliargs)
nagios = NagiosHelper() nagios = NagiosHelper()
context = None context = None
@@ -538,14 +549,16 @@ if __name__ == "__main__":
if args.ssl: if args.ssl:
url = "https://%s" % args.host url = "https://%s" % args.host
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.options |= ssl.OP_NO_SSLv2 context.options |= ssl.OP_NO_SSLv2
context.options |= ssl.OP_NO_SSLv3 context.options |= ssl.OP_NO_SSLv3
if args.insecure: if args.insecure:
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE context.verify_mode = ssl.CERT_NONE
else: else:
context.verify_mode = ssl.CERT_OPTIONAL context.verify_mode = ssl.CERT_OPTIONAL
context.load_default_certs()
if args.cacert: if args.cacert:
try: try:
context.load_verify_locations(args.cacert) context.load_verify_locations(args.cacert)
@@ -582,7 +595,7 @@ if __name__ == "__main__":
json_data = '' json_data = ''
try: try:
req = urllib.request.Request(url) req = urllib.request.Request(url, method=args.method)
req.add_header("User-Agent", "check_http_json") req.add_header("User-Agent", "check_http_json")
if args.auth: if args.auth:
authbytes = str(args.auth).encode() authbytes = str(args.auth).encode()
@@ -594,19 +607,26 @@ if __name__ == "__main__":
for header in headers: for header in headers:
req.add_header(header, headers[header]) req.add_header(header, headers[header])
if args.timeout and args.data: if args.timeout and args.data:
databytes = str(args.data).encode()
response = urllib.request.urlopen(req, timeout=args.timeout, response = urllib.request.urlopen(req, timeout=args.timeout,
data=args.data, context=context) data=databytes, context=context)
elif args.timeout: elif args.timeout:
response = urllib.request.urlopen(req, timeout=args.timeout, response = urllib.request.urlopen(req, timeout=args.timeout,
context=context) context=context)
elif args.data: elif args.data:
response = urllib.request.urlopen(req, data=args.data, context=context) databytes = str(args.data).encode()
response = urllib.request.urlopen(req, data=databytes, context=context)
else: else:
# pylint: disable=consider-using-with
response = urllib.request.urlopen(req, context=context) response = urllib.request.urlopen(req, context=context)
json_data = response.read() json_data = response.read()
except HTTPError as e: except HTTPError as e:
# 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)) nagios.append_unknown(" HTTPError[%s], url:%s" % (str(e.code), url))
except URLError as e: except URLError as e:
nagios.append_critical(" URLError[%s], url:%s" % (str(e.reason), url)) nagios.append_critical(" URLError[%s], url:%s" % (str(e.reason), url))
@@ -630,4 +650,9 @@ if __name__ == "__main__":
print(nagios.getMessage()) print(nagios.getMessage())
sys.exit(nagios.getCode()) sys.exit(nagios.getCode())
if __name__ == "__main__":
# Program entry point
main(sys.argv[1:])
#EOF #EOF

View File

@@ -0,0 +1,106 @@
object CheckCommand "http_json" {
import "plugin-check-command"
command = [ PluginDir + "/check_http_json.py" ]
arguments = {
"--host" = {
value = "$address$"
description = "Hostname or address of the interface to query"
required = true
}
"--port" = {
value = "$http_json_port$"
description = "TCP port number"
}
"--path" = {
value = "$http_json_path$"
description = "URL path to query (i.e.: /v1/service/xyz)"
}
"--timeout" = {
value = "$http_json_timeout$"
description = "Connection timeout (seconds)"
}
"--basic-auth" = {
value = "$http_json_basic_auth$"
description = "Basic auth string 'username:password'"
}
"--ssl" = {
set_if = "$http_json_ssl$"
description = "use TLS to connect to remote host"
}
"--insecure" = {
set_if = "$http_json_insecure$"
description = "do not check server SSL certificate"
}
"--cacert" = {
value = "$http_json_cacert_file$"
description = "path of cacert file to validate server cert"
}
"--cert" = {
value = "$http_json_cert_file$"
description = "client certificate in PEM format"
}
"--key" = {
value = "$http_json_key_file$"
description = "client certificate key file in PEM format ( if not bundled into the cert )"
}
"--data" = {
value = "$http_json_post_data$"
description = "the http payload to send as a POST"
}
"--headers" = {
value = "$http_json_headers$"
description = "additional http headers in JSON format to send with the request"
}
"--field_separator" = {
value = "$http_json_field_separator$"
description = "JSON Field separator, defaults to '.'; Select element in an array with '(' ')'"
}
"--value_separator" = {
value = "$http_json_value_separator$"
description = "JSON Value separator, defaults to ':'"
}
"--warning" = {
value = "$http_json_warning$"
description = "Warning threshold for these values, WarningRange is in the format [@]start:end"
}
"--critical" = {
value = "$http_json_critical$"
description = "Critical threshold for these values, CriticalRange is in the format [@]start:end"
}
"--key_exists" = {
value = "$http_json_key_exists$"
description = "Checks existence of these keys to determine status. Return warning if key is not present."
}
"--key_exists_critical" = {
value = "$http_json_key_exists_critical$"
description = "Checks existence of these keys to determine status. Return critical if key is not present."
}
"--key_equals" = {
value = "$http_json_key_equals$"
description = "Checks equality of these keys and values. Return warning if equality check fails"
}
"--key_equals_critical" = {
value = "$http_json_key_equals_critical$"
description = "Checks equality of these keys and values. Return critical if equality check fails"
}
"--key_equals_unknown" = {
value = "$http_json_key_equals_unknown$"
description = "Checks equality of these keys and values. Return unknown if equality check fails"
}
"--key_not_equals" = {
value = "$http_json_key_not_equals$"
description = "Checks equality of these keys and values (key[>alias],value key2,value2) to determine status. Multiple key values can be delimited with colon (key,value1:value2). Return warning if equality check succeeds."
}
"--key_not_equals_critical" = {
value = "$http_json_key_not_equals_critical$"
description = "Checks equality of these keys and values (key[>alias],value key2,value2) to determine status. Multiple key values can be delimited with colon (key,value1:value2). Return critical if equality check succeeds."
}
"--key_metric" = {
value = "$http_json_key_metric$"
description = "Gathers the values of these keys"
}
}
}

2
requirements-dev.txt Normal file
View File

@@ -0,0 +1,2 @@
coverage==6.4.4
pylint==2.15.2

2
test/requirements.txt Normal file
View File

@@ -0,0 +1,2 @@
coverage==5.0.3
pylint==2.4.4

View File

@@ -110,6 +110,14 @@ class UtilTest(unittest.TestCase):
self.check_data(RulesHelper().dash_U(['metric,0']), self.check_data(RulesHelper().dash_U(['metric,0']),
'{"metric": 3}', UNKNOWN_CODE) '{"metric": 3}', UNKNOWN_CODE)
def test_array(self):
self.check_data(RulesHelper().dash_q(['foo(0),bar']),
'{"foo": ["bar"]}', OK_CODE)
self.check_data(RulesHelper().dash_q(['foo(0),foo']),
'{"foo": ["bar"]}', WARNING_CODE)
self.check_data(RulesHelper().dash_Q(['foo(1),bar']),
'{"foo": ["bar"]}', CRITICAL_CODE)
def test_exists(self): def test_exists(self):
self.check_data(RulesHelper().dash_e(['nothere']), self.check_data(RulesHelper().dash_e(['nothere']),
'{"metric": 5}', WARNING_CODE) '{"metric": 5}', WARNING_CODE)
@@ -256,7 +264,7 @@ class UtilTest(unittest.TestCase):
# This should not throw a KeyError # This should not throw a KeyError
data = '{}' data = '{}'
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']), data, CRITICAL_CODE)
def test_subelem(self): def test_subelem(self):
@@ -274,3 +282,50 @@ class UtilTest(unittest.TestCase):
self.check_data(rules.dash_E(['(*).capacity.value.too_deep']), data, CRITICAL_CODE) self.check_data(rules.dash_E(['(*).capacity.value.too_deep']), data, CRITICAL_CODE)
# Should not throw keyerror # Should not throw keyerror
self.check_data(rules.dash_E(['foo']), data, CRITICAL_CODE) self.check_data(rules.dash_E(['foo']), data, CRITICAL_CODE)
def test_empty_key_value_array(self):
"""
https://github.com/drewkerrigan/nagios-http-json/issues/61
"""
rules = RulesHelper()
# This should simply work
data = '[{"update_status": "finished"},{"update_status": "finished"}]'
self.check_data(rules.dash_q(['(*).update_status,finished']), data, OK_CODE)
# This should warn us
data = '[{"update_status": "finished"},{"update_status": "failure"}]'
self.check_data(rules.dash_q(['(*).update_status,finished']), data, WARNING_CODE)
# This should throw an error
data = '[]'
self.check_data(rules.dash_q(['(*).update_status,warn_me']), data, CRITICAL_CODE)
def test_bracket_in_key(self):
"""
https://github.com/drewkerrigan/nagios-http-json/issues/76
"""
rules = RulesHelper()
# This should work
data = '[{"update status": "failure"}]'
self.check_data(rules.dash_q(['(*).update status,failure']), data, OK_CODE)
data = '[{"update (status)": "failure"}]'
self.check_data(rules.dash_q(['(*).update (status),failure']), data, OK_CODE)
data = '[{"update (((status)": "failure"}]'
self.check_data(rules.dash_q(['(*).update (((status),failure']), data, OK_CODE)
data = '[{"update )status)": "failure"}]'
self.check_data(rules.dash_q(['(*).update )status),failure']), data, OK_CODE)
data = '[{"update (status": "failure"}]'
self.check_data(rules.dash_q(['(*).update (status),failure']), data, WARNING_CODE)
# Does not yet work
# data = '{"update (foobar)": ["bar"]}'
# self.check_data(rules.dash_q(['update (foobar)(0),bar']), data, OK_CODE)

44
test/test_cli.py Normal file
View File

@@ -0,0 +1,44 @@
#!/usr/bin/env python3
import unittest
import unittest.mock as mock
import sys
import os
sys.path.append('..')
from check_http_json import debugPrint
class CLITest(unittest.TestCase):
"""
Tests for CLI
"""
def setUp(self):
"""
Defining the exitcodes
"""
self.exit_0 = 0 << 8
self.exit_1 = 1 << 8
self.exit_2 = 2 << 8
self.exit_3 = 3 << 8
def test_debugprint(self):
with mock.patch('builtins.print') as mock_print:
debugPrint(True, 'debug')
mock_print.assert_called_once_with('debug')
def test_debugprint_pprint(self):
with mock.patch('check_http_json.pprint') as mock_pprint:
debugPrint(True, 'debug', True)
mock_pprint.assert_called_once_with('debug')
def test_cli_without_params(self):
command = '/usr/bin/env python3 check_http_json.py > /dev/null 2>&1'
status = os.system(command)
self.assertEqual(status, self.exit_2)

View File

@@ -8,37 +8,90 @@ import os
sys.path.append('..') sys.path.append('..')
from check_http_json import debugPrint from check_http_json import main
class MockResponse():
def __init__(self, status_code=200, content='{"foo": "bar"}'):
self.status_code = status_code
self.content = content
def read(self):
return self.content
class MainTest(unittest.TestCase): class MainTest(unittest.TestCase):
""" """
Tests for main Tests for Main
""" """
def setUp(self): @mock.patch('builtins.print')
""" def test_main_version(self, mock_print):
Defining the exitcodes args = ['--version']
"""
self.exit_0 = 0 << 8 with self.assertRaises(SystemExit) as test:
self.exit_1 = 1 << 8 main(args)
self.exit_2 = 2 << 8
self.exit_3 = 3 << 8
def test_debugprint(self): mock_print.assert_called_once()
with mock.patch('builtins.print') as mock_print: self.assertEqual(test.exception.code, 0)
debugPrint(True, 'debug')
mock_print.assert_called_once_with('debug')
def test_debugprint_pprint(self): @mock.patch('builtins.print')
with mock.patch('check_http_json.pprint') as mock_pprint: @mock.patch('urllib.request.urlopen')
debugPrint(True, 'debug', True) def test_main_with_ssl(self, mock_request, mock_print):
mock_pprint.assert_called_once_with('debug') args = '-H localhost --ssl'.split(' ')
def test_cli_without_params(self): mock_request.return_value = MockResponse()
command = '/usr/bin/env python3 check_http_json.py > /dev/null 2>&1' with self.assertRaises(SystemExit) as test:
status = os.system(command) main(args)
self.assertEqual(status, self.exit_2) self.assertEqual(test.exception.code, 0)
@mock.patch('builtins.print')
@mock.patch('urllib.request.urlopen')
def test_main_with_parse_error(self, mock_request, mock_print):
args = '-H localhost'.split(' ')
mock_request.return_value = MockResponse(content='not JSON')
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')
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)