1
1
# coding: utf8
2
2
from __future__ import unicode_literals
3
- from flask import abort , make_response , request
3
+ from flask import abort , make_response , request , jsonify
4
4
from flask_api .decorators import set_renderers
5
5
from flask_api import exceptions , renderers , status , FlaskAPI
6
6
import json
@@ -19,6 +19,30 @@ class JSONVersion2(renderers.JSONRenderer):
19
19
media_type = 'application/json; api-version="2.0"'
20
20
21
21
22
+ # This is being used to test issue #58, source is taken from flask apierrors doc page
23
+ class InvalidUsage (Exception ):
24
+ status_code = 400
25
+
26
+ def __init__ (self , message , status_code = None , payload = None ):
27
+ Exception .__init__ (self )
28
+ self .message = message
29
+ if status_code is not None :
30
+ self .status_code = status_code
31
+ self .payload = payload
32
+
33
+ def to_dict (self ):
34
+ rv = dict (self .payload or ())
35
+ rv ['message' ] = self .message
36
+ return rv
37
+
38
+
39
+ @app .errorhandler (InvalidUsage )
40
+ def handle_invalid_usage (error ):
41
+ response = jsonify (error .to_dict ())
42
+ response .status_code = error .status_code
43
+ return response
44
+
45
+
22
46
@app .route ('/set_status_and_headers/' )
23
47
def set_status_and_headers ():
24
48
headers = {'Location' : 'http://example.com/456' }
@@ -43,6 +67,16 @@ def api_exception():
43
67
raise exceptions .PermissionDenied ()
44
68
45
69
70
+ @app .route ('/custom_exception/' )
71
+ def custom_exception ():
72
+ raise InvalidUsage ('Invalid usage test.' , status_code = 410 )
73
+
74
+
75
+ @app .route ('/custom_exception_no_code/' )
76
+ def custom_exception_no_status_code ():
77
+ raise InvalidUsage ('Invalid usage test.' )
78
+
79
+
46
80
@app .route ('/abort_view/' )
47
81
def abort_view ():
48
82
abort (status .HTTP_403_FORBIDDEN )
@@ -95,6 +129,18 @@ def test_api_exception(self):
95
129
expected = '{"message": "You do not have permission to perform this action."}'
96
130
self .assertEqual (response .get_data ().decode ('utf8' ), expected )
97
131
132
+ def test_custom_exception (self ):
133
+ with app .test_client () as client :
134
+ response = client .get ('/custom_exception/' )
135
+ self .assertEqual (response .status_code , status .HTTP_410_GONE )
136
+ self .assertEqual (response .content_type , 'application/json' )
137
+
138
+ def test_custom_exception_default_code (self ):
139
+ with app .test_client () as client :
140
+ response = client .get ('/custom_exception_no_code/' )
141
+ self .assertEqual (response .status_code , status .HTTP_400_BAD_REQUEST )
142
+ self .assertEqual (response .content_type , 'application/json' )
143
+
98
144
def test_abort_view (self ):
99
145
with app .test_client () as client :
100
146
response = client .get ('/abort_view/' )
0 commit comments