1import pytest 2 3from werkzeug.exceptions import default_exceptions, InternalServerError 4from flask_smorest import Api, abort 5 6 7class TestErrorHandler: 8 9 @pytest.mark.parametrize('code', default_exceptions) 10 def test_error_handler_on_abort(self, app, code): 11 12 client = app.test_client() 13 14 @app.route('/abort') 15 def test_abort(): 16 abort(code) 17 18 Api(app) 19 20 response = client.get('/abort') 21 assert response.status_code == code 22 assert response.json['code'] == code 23 assert response.json['status'] == default_exceptions[code]().name 24 25 def test_error_handler_on_unhandled_error(self, app): 26 27 client = app.test_client() 28 29 @app.route('/uncaught') 30 def test_uncaught(): 31 raise Exception('Oops, something really bad happened.') 32 33 Api(app) 34 35 response = client.get('/uncaught') 36 assert response.status_code == 500 37 assert response.json['code'] == 500 38 assert response.json['status'] == InternalServerError().name 39 40 def test_error_handler_payload(self, app): 41 42 client = app.test_client() 43 44 errors = { 45 'dimensions': ['Too tall', 'Too wide'], 46 'color': ['Too bright'] 47 } 48 messages = {'name': ['Too long'], 'age': ['Too young']} 49 50 @app.route('/message') 51 def test_message(): 52 abort(404, message='Resource not found') 53 54 @app.route('/messages') 55 def test_messages(): 56 abort(422, messages=messages, message='Validation issue') 57 58 @app.route('/errors') 59 def test_errors(): 60 abort(422, errors=errors, messages=messages, message='Wrong!') 61 62 @app.route('/headers') 63 def test_headers(): 64 abort(401, message='Access denied', 65 headers={'WWW-Authenticate': 'Basic realm="My Server"'}) 66 67 Api(app) 68 69 response = client.get('/message') 70 assert response.status_code == 404 71 assert response.json['message'] == 'Resource not found' 72 73 response = client.get('/messages') 74 assert response.status_code == 422 75 assert response.json['errors'] == messages 76 77 response = client.get('/errors') 78 assert response.status_code == 422 79 assert response.json['errors'] == errors 80 81 response = client.get('/headers') 82 assert response.status_code == 401 83 assert ( 84 response.headers['WWW-Authenticate'] == 'Basic realm="My Server"') 85 assert response.json['message'] == 'Access denied' 86