-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinder_test.go
100 lines (82 loc) · 2.1 KB
/
binder_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
package poteto
import (
"bytes"
"net/http/httptest"
"testing"
"github.com/poteto-go/poteto/constant"
)
func TestBind(t *testing.T) {
binder := NewBinder()
type User struct {
Name string `json:"name"`
Mail string `json:"mail"`
}
tests := []struct {
name string
body []byte
worked bool
expected User
}{
{
"Test Normal Case",
[]byte(`{"name":"test", "mail":"example"}`),
true,
User{Name: "test", Mail: "example"},
},
{
"Test Error Case",
[]byte(`{"name":"test",, "mail":"example"}`),
false,
User{Name: "test", Mail: "example"},
},
}
for _, it := range tests {
t.Run(it.name, func(t *testing.T) {
user := User{}
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "https://example.com", bytes.NewBufferString(string(it.body)))
req.Header.Set(constant.HEADER_CONTENT_TYPE, constant.APPLICATION_JSON)
ctx := NewContext(w, req).(*context)
err := binder.Bind(ctx, &user)
if err != nil {
if it.worked {
t.Errorf("unexpected error")
}
return
}
if !it.worked {
t.Errorf("unexpected not error")
return
}
if it.expected.Name != user.Name {
t.Errorf("Unmatched")
}
if it.expected.Mail != user.Mail {
t.Errorf("Unmatched")
}
})
}
}
func TestZeroLengthContentBind(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "https://example.com", bytes.NewBufferString(string(userJSON)))
req.ContentLength = 0
ctx := NewContext(w, req).(*context)
user := user{}
binder := NewBinder()
if err := binder.Bind(ctx, &user); err != nil {
t.Errorf("cannot go through")
}
}
func BenchmarkBind(b *testing.B) {
binder := NewBinder()
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "https://example.com", bytes.NewBufferString(string(userJSON)))
req.Header.Set(constant.HEADER_CONTENT_TYPE, constant.APPLICATION_JSON)
ctx := NewContext(w, req).(*context)
testUser := user{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
binder.Bind(ctx, &testUser)
}
}