From 798a72cb730bd4afa0d1e17202f1ccc9a1e697e2 Mon Sep 17 00:00:00 2001 From: Ruben van Staveren Date: Mon, 14 Mar 2022 15:38:38 +0100 Subject: [PATCH] Gracefully handle FileNotFoundError exceptions --- jail2ban/__init__.py | 8 ++++++++ tests/test_flush.py | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/jail2ban/__init__.py b/jail2ban/__init__.py index dec322c..889963d 100644 --- a/jail2ban/__init__.py +++ b/jail2ban/__init__.py @@ -139,6 +139,14 @@ def create_app(): app.logger.fatal(error) return jsonify({'error': str(error)}), 500 + @app.errorhandler(FileNotFoundError) + def filenotfound_err(error): + ''' + Show a json parsable error if the value is illegal + ''' + app.logger.fatal(error) + return jsonify({'error': str(error)}), 500 + @auth.error_handler def auth_error(): app.logger.error('Access Denied') diff --git a/tests/test_flush.py b/tests/test_flush.py index 8f1ef37..6ea877e 100644 --- a/tests/test_flush.py +++ b/tests/test_flush.py @@ -52,3 +52,19 @@ def test_wrong_method(client, mocker): headers={"Authorization": "Basic " + valid_credentials}) assert response.status_code == 405 + + +def test_filenotfound(app, mocker): + + app.config.update({ + "AUTHFILE": '../tests/nonexistent-users-test.txt' + }) + + client = app.test_client() + + valid_credentials = base64.b64encode(b"test.example.com:testpassword").decode("utf-8") + name = 'nonexistent' + response = client.get(f"/flush/{name}", + headers={"Authorization": "Basic " + valid_credentials}) + + assert response.status_code == 500