-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller_test.go
119 lines (104 loc) · 2.55 KB
/
controller_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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package resozyme
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-chi/chi"
)
func TestDispatcher_ServeHTTP(t *testing.T) {
r := chi.NewRouter()
dispatcher := &Dispatcher{
mux: r,
defaultRenderer: NewJSONRenderer(),
errorHandler: &ExposedErrorHandler{Renderer: NewJSONRenderer()},
logger: &NilLogger{},
debug: false,
prettyKey: "pretty",
}
dispatcher.SetDefaultRenderer(NewHALRenderer())
Route(r, "/hello", newHelloResource)
tests := []struct {
path string
method string
wantCode int
wantBody []byte
wantHeader http.Header
}{
{
"/hello",
http.MethodGet,
http.StatusOK,
[]byte(`{"_links":{"self":{"href":"/hello"}},"text":"Hello, World"}`),
http.Header{
"Content-Type": []string{"application/hal+json"},
},
},
{
"/hello",
http.MethodPost,
http.StatusCreated,
nil,
http.Header{
"Location": []string{"https://example.com/loc"},
},
},
{
"/hello",
http.MethodPut,
http.StatusMethodNotAllowed,
[]byte(`{"message":"Method Not Allowed"}`),
http.Header{
"Content-Type": []string{"application/json"},
},
},
{
"/hello",
http.MethodPatch,
http.StatusMethodNotAllowed,
[]byte(`{"message":"Method Not Allowed"}`),
http.Header{
"Content-Type": []string{"application/json"},
},
},
{
"/hello",
http.MethodDelete,
http.StatusMethodNotAllowed,
[]byte(`{"message":"Method Not Allowed"}`),
http.Header{
"Content-Type": []string{"application/json"},
},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.method, func(t *testing.T) {
t.Parallel()
r := httptest.NewRequest(tt.method, "http://example.com"+tt.path, nil)
w := httptest.NewRecorder()
dispatcher.ServeHTTP(w, r)
resp := w.Result()
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Unexpected error: got=%s", err)
}
if resp.StatusCode != tt.wantCode {
t.Fatalf("Unexpected code: got=%d, want=%d", resp.StatusCode, tt.wantCode)
}
if !bytes.Equal(body, tt.wantBody) {
t.Fatalf("Unexpected body: got=%s, want=%s", string(body), string(tt.wantBody))
}
if len(resp.Header) != len(tt.wantHeader) {
t.Fatalf("Unexpected header len: got=%d, want=%d", len(resp.Header), len(tt.wantHeader))
}
for key := range tt.wantHeader {
if resp.Header.Get(key) != tt.wantHeader.Get(key) {
t.Fatalf("Unexpected %s header: got=%s, want=%s", key, resp.Header.Get(key), tt.wantHeader.Get(key))
}
}
})
}
}