-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_apiexceptions.py
227 lines (164 loc) · 6.8 KB
/
test_apiexceptions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""
test_apiexceptions
~~~~~~~~~~~~~~~~~~
Tests for Flask-APIExceptions extension and related functionality.
"""
import pytest
import flask
from flask import json, jsonify
from flask_apiexceptions import (
JSONExceptionHandler, ApiException, api_exception_handler, ApiError)
#pylint: disable=redefined-outer-name
@pytest.fixture
def app():
"""Flask application fixture."""
app = flask.Flask(__name__)
return app
def test_initialize_extension(app):
"""Ensure extension initialization happens as expected."""
assert 'apiexceptions' not in getattr(app, 'extensions', dict())
JSONExceptionHandler(app)
assert 'apiexceptions' in app.extensions
assert isinstance(app.extensions['apiexceptions'],
JSONExceptionHandler)
def test_deferred_init_app(app):
"""Deferred initialization test."""
assert 'apiexceptions' not in getattr(app, 'extensions', dict())
ext = JSONExceptionHandler()
ext.init_app(app)
assert 'apiexceptions' in app.extensions
assert isinstance(app.extensions['apiexceptions'],
JSONExceptionHandler)
def test_register_exception_type(app):
"""Register an exception type with the default handler."""
class CustomError(Exception):
"""Exception subclass for testing purposes."""
message = 'A custom error message'
@app.route('/testing')
def testing(): #pylint: disable=locally-disabled,unused-variable
"""Endpoint that simply raises an exception."""
raise CustomError()
ext = JSONExceptionHandler(app)
ext.register(code_or_exception=CustomError)
with app.app_context():
with app.test_client() as c:
rv = c.get('/testing')
assert rv.status_code == 500 # Default status code.
assert rv.headers['content-type'] == 'application/json'
assert json.loads(rv.data)['message'] == 'A custom error message'
def test_register_exception_code_and_handler(app):
"""Handle Flask 404s with JSONExceptionHandler."""
ext = JSONExceptionHandler(app)
ext.register(code_or_exception=404,
handler=JSONExceptionHandler.handle_404)
with app.app_context():
with app.test_client() as c:
rv = c.get('/notfound')
assert rv.status_code == 404
assert rv.headers['content-type'] == 'application/json'
assert json.loads(rv.data)['message'] == ('The resource at /notfound could'
' not be found.')
def test_register_exception_class_and_handler(app):
"""Custom exception handling."""
class CustomError(Exception):
"""Exception subclass with attributes."""
teapot_code = 418
special = {'foo': 'bar'}
def custom_handler(error):
"""Handler for custom exception subclass."""
response = jsonify(data=error.special)
response.status_code = error.teapot_code
return response
@app.route('/testing')
def testing(): #pylint: disable=locally-disabled,unused-variable
"""Endpoint to raise our custom exception."""
raise CustomError()
ext = JSONExceptionHandler(app)
ext.register(code_or_exception=CustomError, handler=custom_handler)
with app.app_context():
with app.test_client() as c:
rv = c.get('/testing')
assert rv.status_code == 418
assert rv.headers['content-type'] == 'application/json'
assert json.loads(rv.data)['data'] == CustomError.special
def test_api_exception_handler(app):
"""Use JSONExceptionHandler.api_exception_handler to capture ApiException
objects that are raised."""
@app.route('/custom')
def testing(): #pylint: disable=locally-disabled,unused-variable
"""Endpoint to raise our custom exception."""
error = ApiError(code='teapot', message='I am a little teapot.')
raise ApiException(status_code=418, error=error)
ext = JSONExceptionHandler(app)
ext.register(code_or_exception=ApiException, handler=api_exception_handler)
with app.app_context():
with app.test_client() as c:
rv = c.get('/custom')
assert rv.status_code == 418
assert rv.headers['content-type'] == 'application/json'
json_data = json.loads(rv.data)
assert json_data['errors'][0]['message'] == 'I am a little teapot.'
assert json_data['errors'][0]['code'] == 'teapot'
assert json_data['errors'][0]['info'] is None
def test_exception_auto_populate_error():
"""If no ApiError object is provided, create one by default in
ApiException."""
exc = ApiException(
status_code=418,
code='bad_inputs',
message='Something happened.',
info={'key': 'value'})
assert len(exc.errors) == 1
assert isinstance(exc.errors[0], ApiError)
assert exc.errors[0].code == 'bad_inputs'
assert exc.errors[0].message == 'Something happened.'
assert exc.errors[0].info == {'key': 'value'}
exc = ApiException(
status_code=418,
code='bad_inputs')
assert len(exc.errors) == 1
assert isinstance(exc.errors[0], ApiError)
assert exc.errors[0].code == 'bad_inputs'
assert exc.errors[0].message is None
assert exc.errors[0].info is None
exc = ApiException(
status_code=418,
message='Whoopsie! That is no good.')
assert len(exc.errors) == 1
assert isinstance(exc.errors[0], ApiError)
assert exc.errors[0].info is None
assert exc.errors[0].code is None
assert exc.errors[0].message == 'Whoopsie! That is no good.'
exc = ApiException(
status_code=418,
info={'key': 'value'})
assert len(exc.errors) == 1
assert isinstance(exc.errors[0], ApiError)
assert exc.errors[0].info == {'key': 'value'}
assert exc.errors[0].code is None
assert exc.errors[0].message is None
def test_api_exception_subclass_variations(app):
"""Subclass ApiException with class attribute descriptors."""
class CustomError(ApiException):
"""Subclass of ApiException with additional attributes."""
status_code = 418
message = "A class attribute exception message."
code = 'class-attribute'
info = {'foo': 'bar'}
@app.route('/testing')
def testing(): #pylint: disable=locally-disabled,unused-variable
"""Endpoint that simply raises our custom exception."""
raise CustomError()
ext = JSONExceptionHandler(app)
# Use the api_exception_handler since CustomError is a subclass of
# ApiException
ext.register(code_or_exception=CustomError, handler=api_exception_handler)
with app.app_context():
with app.test_client() as c:
rv = c.get('/testing')
assert rv.status_code == 418
assert rv.headers['content-type'] == 'application/json'
assert json.loads(rv.data)['errors'] == [
{'code': CustomError.code,
'message': CustomError.message,
'info': CustomError.info}]