-
Notifications
You must be signed in to change notification settings - Fork 0
/
methodhandler_test.go
67 lines (59 loc) · 2.11 KB
/
methodhandler_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
62
63
64
65
66
67
// +build impl
package dispel
import (
"net/http"
"net/http/httptest"
"testing"
)
func newRequest(tb testing.TB, method, url string) *http.Request {
req, err := http.NewRequest(method, url, nil)
if err != nil {
tb.Fatal(err)
}
return req
}
func TestMethodHandler(t *testing.T) {
var (
ok = "ok\n"
notAllowed = http.StatusText(http.StatusMethodNotAllowed) + "\n"
okHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte(ok))
})
)
tests := []struct {
req *http.Request
handler http.Handler
code int
allow string // Contents of the Allow header
body string
}{
// No handlers
{newRequest(t, "GET", "/foo"), MethodHandler{}, http.StatusMethodNotAllowed, "", notAllowed},
{newRequest(t, "OPTIONS", "/foo"), MethodHandler{}, http.StatusOK, "", ""},
// A single handler
{newRequest(t, "GET", "/foo"), MethodHandler{Get: okHandler}, http.StatusOK, "", ok},
{newRequest(t, "POST", "/foo"), MethodHandler{Get: okHandler}, http.StatusMethodNotAllowed, "GET", notAllowed},
// Multiple handlers
{newRequest(t, "GET", "/foo"), MethodHandler{Get: okHandler, Post: okHandler}, http.StatusOK, "", ok},
{newRequest(t, "POST", "/foo"), MethodHandler{Get: okHandler, Post: okHandler}, http.StatusOK, "", ok},
{newRequest(t, "DELETE", "/foo"), MethodHandler{Get: okHandler, Post: okHandler}, http.StatusMethodNotAllowed, "GET, POST", notAllowed},
{newRequest(t, "OPTIONS", "/foo"), MethodHandler{Get: okHandler, Post: okHandler}, http.StatusOK, "GET, POST", ""},
// Override OPTIONS
{newRequest(t, "OPTIONS", "/foo"), MethodHandler{Options: okHandler}, http.StatusOK, "", ok},
}
for _, test := range tests {
rec := httptest.NewRecorder()
test.handler.ServeHTTP(rec, test.req)
if test.code != rec.Code {
t.Errorf("Expected %d, got %d", test.code, rec.Code)
}
if test.req.Method == "OPTIONS" {
if test.allow != rec.HeaderMap.Get("Allow") {
t.Errorf("Expected %q, got %q", test.allow, rec.HeaderMap.Get("Allow"))
}
}
if test.body != rec.Body.String() {
t.Errorf("Expected %q, got %q", test.body, rec.Body.String())
}
}
}