|
| 1 | +from flask import Flask |
| 2 | +from labthings.server.exceptions import JSONExceptionHandler |
| 3 | +import json |
| 4 | +import pytest |
| 5 | + |
| 6 | + |
| 7 | +@pytest.fixture |
| 8 | +def client(): |
| 9 | + app = Flask(__name__) |
| 10 | + app.config["TESTING"] = True |
| 11 | + |
| 12 | + with app.test_client() as client: |
| 13 | + yield client |
| 14 | + |
| 15 | + |
| 16 | +@pytest.fixture |
| 17 | +def app(): |
| 18 | + app = Flask(__name__) |
| 19 | + app.config["TESTING"] = True |
| 20 | + return app |
| 21 | + |
| 22 | + |
| 23 | +def test_registering_handler(app): |
| 24 | + error_handler = JSONExceptionHandler() |
| 25 | + error_handler.init_app(app) |
| 26 | + |
| 27 | + |
| 28 | +def test_http_exception(app): |
| 29 | + from werkzeug.exceptions import NotFound |
| 30 | + |
| 31 | + error_handler = JSONExceptionHandler(app) |
| 32 | + |
| 33 | + # Test a 404 HTTPException |
| 34 | + response = error_handler.std_handler(NotFound()) |
| 35 | + |
| 36 | + response_json = json.dumps(response[0]) |
| 37 | + assert ( |
| 38 | + response_json |
| 39 | + == '{"code": 404, "message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.", "name": "NotFound"}' |
| 40 | + ) |
| 41 | + |
| 42 | + assert response[1] == 404 |
| 43 | + |
| 44 | + |
| 45 | +def test_generic_exception(app): |
| 46 | + error_handler = JSONExceptionHandler(app) |
| 47 | + |
| 48 | + # Test a 404 HTTPException |
| 49 | + response = error_handler.std_handler(RuntimeError("Exception message")) |
| 50 | + |
| 51 | + response_json = json.dumps(response[0]) |
| 52 | + assert ( |
| 53 | + response_json |
| 54 | + == '{"code": 500, "message": "Exception message", "name": "RuntimeError"}' |
| 55 | + ) |
| 56 | + |
| 57 | + assert response[1] == 500 |
| 58 | + |
| 59 | + |
| 60 | +def test_blank_exception(app): |
| 61 | + error_handler = JSONExceptionHandler(app) |
| 62 | + |
| 63 | + e = Exception() |
| 64 | + e.message = None |
| 65 | + |
| 66 | + # Test a 404 HTTPException |
| 67 | + response = error_handler.std_handler(e) |
| 68 | + |
| 69 | + response_json = json.dumps(response[0]) |
| 70 | + assert response_json == '{"code": 500, "message": "None", "name": "Exception"}' |
| 71 | + |
| 72 | + assert response[1] == 500 |
0 commit comments