forked from emicklei/go-restful
-
Notifications
You must be signed in to change notification settings - Fork 0
/
container_test.go
61 lines (56 loc) · 1.74 KB
/
container_test.go
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
package restful
import (
"net/http"
"net/http/httptest"
"testing"
)
// go test -v -test.run TestContainer_computeAllowedMethods ...restful
func TestContainer_computeAllowedMethods(t *testing.T) {
wc := NewContainer()
ws1 := new(WebService).Path("/users")
ws1.Route(ws1.GET("{i}").To(dummy))
ws1.Route(ws1.POST("{i}").To(dummy))
wc.Add(ws1)
httpRequest, _ := http.NewRequest("GET", "http://api.his.com/users/1", nil)
rreq := Request{Request: httpRequest}
m := wc.computeAllowedMethods(&rreq)
if len(m) != 2 {
t.Errorf("got %d expected 2 methods, %v", len(m), m)
}
}
func TestContainer_HandleWithFilter(t *testing.T) {
prefilterCalled := false
postfilterCalled := false
httpHandlerCalled := false
wc := NewContainer()
wc.Filter(func(request *Request, response *Response, chain *FilterChain) {
prefilterCalled = true
chain.ProcessFilter(request, response)
})
wc.HandleWithFilter("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
httpHandlerCalled = true
w.Write([]byte("ok"))
}))
wc.Filter(func(request *Request, response *Response, chain *FilterChain) {
postfilterCalled = true
chain.ProcessFilter(request, response)
})
recorder := httptest.NewRecorder()
request, _ := http.NewRequest("GET", "/", nil)
wc.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Errorf("unexpected code %d", recorder.Code)
}
if recorder.Body.String() != "ok" {
t.Errorf("unexpected body %s", recorder.Body.String())
}
if !prefilterCalled {
t.Errorf("filter added before calling HandleWithFilter wasn't called")
}
if !postfilterCalled {
t.Errorf("filter added after calling HandleWithFilter wasn't called")
}
if !httpHandlerCalled {
t.Errorf("handler added by calling HandleWithFilter wasn't called")
}
}