-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathapi_handler_test.go
77 lines (67 loc) · 1.53 KB
/
api_handler_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
package http
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"go.uber.org/zap"
)
func TestAPIHandler_NotFound(t *testing.T) {
type args struct {
method string
path string
}
type wants struct {
statusCode int
contentType string
body string
}
tests := []struct {
name string
args args
wants wants
}{
{
name: "path not found",
args: args{
method: "GET",
path: "/404",
},
wants: wants{
statusCode: http.StatusNotFound,
contentType: "application/json; charset=utf-8",
body: `
{
"code": "not found",
"message": "path not found"
}`,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := httptest.NewRequest(tt.args.method, tt.args.path, nil)
w := httptest.NewRecorder()
b := &APIBackend{
HTTPErrorHandler: ErrorHandler(0),
}
b.Logger = zap.NewNop()
h := NewAPIHandler(b)
h.ServeHTTP(w, r)
res := w.Result()
content := res.Header.Get("Content-Type")
body, _ := ioutil.ReadAll(res.Body)
if res.StatusCode != tt.wants.statusCode {
t.Errorf("%q. get %v, want %v", tt.name, res.StatusCode, tt.wants.statusCode)
}
if tt.wants.contentType != "" && content != tt.wants.contentType {
t.Errorf("%q. get %v, want %v", tt.name, content, tt.wants.contentType)
}
if eq, diff, err := jsonEqual(string(body), tt.wants.body); err != nil {
t.Errorf("%q, error unmarshaling json %v", tt.name, err)
} else if tt.wants.body != "" && !eq {
t.Errorf("%q. ***%s***", tt.name, diff)
}
})
}
}