-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest_test.go
69 lines (66 loc) · 1.62 KB
/
request_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
package request
import (
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
)
func Test_decodeBody(t *testing.T) {
tests := []struct {
name string
r *http.Request
data interface{}
want interface{}
wantErr bool
}{
{
name: "missing content type",
r: httptest.NewRequest(http.MethodPost, "/", nil),
data: &struct{ Val string }{},
want: &struct{ Val string }{},
},
{
name: "decode json empty",
r: func() *http.Request {
r := httptest.NewRequest(http.MethodPost, "/", nil)
r.Header.Set("Content-Type", "application/json")
return r
}(),
data: &struct{ Val string }{},
want: &struct{ Val string }{},
},
{
name: "decode json",
r: func() *http.Request {
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"Val":"success"}`))
r.Header.Set("Content-Type", "application/json")
return r
}(),
data: &struct{ Val string }{},
want: &struct{ Val string }{Val: "success"},
},
{
name: "decode json failure",
r: func() *http.Request {
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`}{`))
r.Header.Set("Content-Type", "application/json")
return r
}(),
data: &struct{ Val string }{},
want: &struct{ Val string }{},
wantErr: true,
},
}
for i := range tests {
tt := tests[i]
t.Run(tt.name, func(t *testing.T) {
if err := decodeBody(tt.r, tt.data); (err != nil) != tt.wantErr {
t.Errorf("decodeBody() error = %v, wantErr %v", err, tt.wantErr)
}
if !reflect.DeepEqual(tt.data, tt.want) {
t.Errorf("decodeBody() = %v, want %v", tt.data, tt.want)
}
})
}
}