-
Notifications
You must be signed in to change notification settings - Fork 4
/
handlers_test.go
49 lines (38 loc) · 1 KB
/
handlers_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
package powermux
import (
"bytes"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestRoute_MethodNotAllowed(t *testing.T) {
// new route
r := newRoute()
// add a GET and DELETE handler
r.Get(http.NotFoundHandler())
r.Delete(http.NotFoundHandler())
ex := &routeExecution{}
// Try for a POST handler
r.getHandler(http.MethodPost, ex)
if ex.handler == nil {
t.Fatal("Nil handler returned")
}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString("Hello"))
ex.handler.ServeHTTP(rec, req)
if rec.Code != http.StatusMethodNotAllowed {
t.Error("Wrong method returned")
}
allows := strings.Split(rec.HeaderMap.Get("Allow"), ", ")
allowedMethods := make(map[string]bool)
for _, allow := range allows {
allowedMethods[allow] = true
}
if !allowedMethods[http.MethodGet] || !allowedMethods[http.MethodDelete] {
t.Error("Did not allow all required methods")
}
if len(allowedMethods) > 2 {
t.Error("Excessive methods allowed")
}
}