Skip to content

Commit 8408240

Browse files
committed
Unit test for the IfMiddleware
1 parent eccbb51 commit 8408240

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

rest/if_test.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package rest
2+
3+
import (
4+
"github.com/ant0ine/go-json-rest/rest/test"
5+
"testing"
6+
)
7+
8+
func TestIfMiddleware(t *testing.T) {
9+
10+
api := NewApi()
11+
12+
// the middleware to test
13+
api.Use(&IfMiddleware{
14+
Condition: func(r *Request) bool {
15+
if r.URL.Path == "/true" {
16+
return true
17+
}
18+
return false
19+
},
20+
IfTrue: MiddlewareSimple(func(handler HandlerFunc) HandlerFunc {
21+
return func(w ResponseWriter, r *Request) {
22+
r.Env["TRUE_MIDDLEWARE"] = true
23+
handler(w, r)
24+
}
25+
}),
26+
IfFalse: MiddlewareSimple(func(handler HandlerFunc) HandlerFunc {
27+
return func(w ResponseWriter, r *Request) {
28+
r.Env["FALSE_MIDDLEWARE"] = true
29+
handler(w, r)
30+
}
31+
}),
32+
})
33+
34+
// a simple app
35+
api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
36+
w.WriteJson(r.Env)
37+
}))
38+
39+
// wrap all
40+
handler := api.MakeHandler()
41+
42+
recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/", nil))
43+
recorded.CodeIs(200)
44+
recorded.ContentTypeIsJson()
45+
recorded.BodyIs("{\"FALSE_MIDDLEWARE\":true}")
46+
47+
recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/true", nil))
48+
recorded.CodeIs(200)
49+
recorded.ContentTypeIsJson()
50+
recorded.BodyIs("{\"TRUE_MIDDLEWARE\":true}")
51+
}

0 commit comments

Comments
 (0)