@@ -6,6 +6,29 @@ import (
6
6
"github.com/ant0ine/go-json-rest/rest/test"
7
7
)
8
8
9
+ func CustomError (r * Request , error string , code int ) interface {} {
10
+ // r = nil when using test requests
11
+ var header string
12
+ switch code {
13
+ case 400 :
14
+ header = "Bad Input"
15
+ break
16
+ case 404 :
17
+ header = "Not Found"
18
+ break
19
+ default :
20
+ header = "API Error"
21
+ }
22
+
23
+ return map [string ]interface {}{
24
+ "error" : map [string ]interface {}{
25
+ "header" : header ,
26
+ "code" : code ,
27
+ "message" : error ,
28
+ },
29
+ }
30
+ }
31
+
9
32
func TestResponseNotIndent (t * testing.T ) {
10
33
11
34
writer := responseWriter {
@@ -24,7 +47,7 @@ func TestResponseNotIndent(t *testing.T) {
24
47
}
25
48
}
26
49
27
- // The following tests could instantiate only the reponseWriter ,
50
+ // The following tests could instantiate only the responseWriter ,
28
51
// but using the Api object allows to use the rest/test utilities,
29
52
// and make the tests easier to write.
30
53
@@ -54,6 +77,24 @@ func TestErrorResponse(t *testing.T) {
54
77
recorded .BodyIs ("{\" Error\" :\" test\" }" )
55
78
}
56
79
80
+ func TestCustomErrorResponse (t * testing.T ) {
81
+
82
+ api := NewApi ()
83
+ ErrorFunc = CustomError
84
+
85
+ api .SetApp (AppSimple (func (w ResponseWriter , r * Request ) {
86
+ Error (w , "test" , 500 )
87
+ }))
88
+
89
+ recorded := test .RunRequest (t , api .MakeHandler (), test .MakeSimpleRequest ("GET" , "http://localhost/" , nil ))
90
+ recorded .CodeIs (500 )
91
+ recorded .ContentTypeIsJson ()
92
+ recorded .BodyIs (`{"error":{"code":500,"header":"API Error","message":"test"}}` )
93
+
94
+ // reset the package variable to not effect other tests
95
+ ErrorFunc = nil
96
+ }
97
+
57
98
func TestNotFoundResponse (t * testing.T ) {
58
99
59
100
api := NewApi ()
@@ -66,3 +107,21 @@ func TestNotFoundResponse(t *testing.T) {
66
107
recorded .ContentTypeIsJson ()
67
108
recorded .BodyIs ("{\" Error\" :\" Resource not found\" }" )
68
109
}
110
+
111
+ func TestCustomNotFoundResponse (t * testing.T ) {
112
+
113
+ api := NewApi ()
114
+ ErrorFunc = CustomError
115
+
116
+ api .SetApp (AppSimple (func (w ResponseWriter , r * Request ) {
117
+ NotFound (w , r )
118
+ }))
119
+
120
+ recorded := test .RunRequest (t , api .MakeHandler (), test .MakeSimpleRequest ("GET" , "http://localhost/" , nil ))
121
+ recorded .CodeIs (404 )
122
+ recorded .ContentTypeIsJson ()
123
+ recorded .BodyIs (`{"error":{"code":404,"header":"Not Found","message":"Resource not found"}}` )
124
+
125
+ // reset the package variable to not effect other tests
126
+ ErrorFunc = nil
127
+ }
0 commit comments