-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathhttpin_test.go
192 lines (157 loc) · 4.63 KB
/
httpin_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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package httpin
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/ggicci/httpin/core"
"github.com/justinas/alice"
"github.com/stretchr/testify/assert"
)
type Pagination struct {
Page int `in:"form=page,page_index,index"`
PerPage int `in:"form=per_page,page_size"`
}
func testcasePagination1100() (*http.Request, *Pagination) {
r, _ := http.NewRequest("GET", "/", nil)
r.Form = url.Values{
"page": {"1"},
"per_page": {"100"},
}
return r, &Pagination{
Page: 1,
PerPage: 100,
}
}
func TestDecodeTo(t *testing.T) {
r, expected := testcasePagination1100()
func() {
input := &Pagination{}
err := DecodeTo(r, input) // pointer to a struct instance
assert.NoError(t, err)
assert.Equal(t, expected, input)
}()
func() {
input := Pagination{}
err := DecodeTo(r, &input) // addressable struct instance
assert.NoError(t, err)
assert.Equal(t, expected, &input)
}()
func() {
input := &Pagination{}
err := DecodeTo(r, &input) // pointer to pointer of struct instance
assert.NoError(t, err)
assert.Equal(t, expected, input)
}()
func() {
input := Pagination{}
err := DecodeTo(r, input) // non-pointer struct instance should fail
assert.ErrorContains(t, err, "invalid resolve target")
}()
}
func TestDecode(t *testing.T) {
r, expected := testcasePagination1100()
p, err := Decode[Pagination](r)
assert.NoError(t, err)
assert.Equal(t, expected, p)
}
func TestDecode_ErrNotAStruct(t *testing.T) {
r, _ := testcasePagination1100()
_, err := Decode[int](r)
assert.ErrorContains(t, err, "T must be a struct type")
_, err = Decode[*Pagination](r)
assert.ErrorContains(t, err, "T must be a struct type")
}
func TestDecode_ErrBuildResolverFailed(t *testing.T) {
r, _ := testcasePagination1100()
type Foo struct {
Name string `in:"nonexistent=foo"`
}
assert.Error(t, DecodeTo(r, &Foo{}))
v, err := Decode[Foo](r)
assert.Nil(t, v)
assert.Error(t, err)
}
func TestDecode_ErrDecodeFailure(t *testing.T) {
r, _ := http.NewRequest("GET", "/", nil)
r.Form = url.Values{
"page": {"1"},
"per_page": {"one-hundred"},
}
p := &Pagination{}
assert.Error(t, DecodeTo(r, p))
v, err := Decode[Pagination](r)
assert.Nil(t, v)
assert.Error(t, err)
}
type EchoInput struct {
Token string `in:"form=access_token;header=x-api-key;required"`
Saying string `in:"form=saying"`
}
func EchoHandler(rw http.ResponseWriter, r *http.Request) {
var input = r.Context().Value(Input).(*EchoInput)
json.NewEncoder(rw).Encode(input)
}
func TestNewInput_WithNil(t *testing.T) {
assert.Panics(t, func() {
NewInput(nil)
})
}
func TestNewInput_Success(t *testing.T) {
r, err := http.NewRequest("GET", "/", nil)
assert.NoError(t, err)
r.Header.Add("X-Api-Key", "abc")
var params = url.Values{}
params.Add("saying", "TO THINE OWE SELF BE TRUE")
r.URL.RawQuery = params.Encode()
rw := httptest.NewRecorder()
handler := alice.New(NewInput(EchoInput{})).ThenFunc(EchoHandler)
handler.ServeHTTP(rw, r)
assert.Equal(t, 200, rw.Code)
expected := `{"Token":"abc","Saying":"TO THINE OWE SELF BE TRUE"}` + "\n"
assert.Equal(t, expected, rw.Body.String())
}
func TestNewInput_ErrorHandledByDefaultErrorHandler(t *testing.T) {
r, err := http.NewRequest("GET", "/", nil)
assert.NoError(t, err)
var params = url.Values{}
params.Add("saying", "TO THINE OWE SELF BE TRUE")
r.URL.RawQuery = params.Encode()
rw := httptest.NewRecorder()
handler := alice.New(NewInput(EchoInput{})).ThenFunc(EchoHandler)
handler.ServeHTTP(rw, r)
var out map[string]any
assert.Nil(t, json.NewDecoder(rw.Body).Decode(&out))
assert.Equal(t, 422, rw.Code)
assert.Equal(t, "Token", out["field"])
assert.Equal(t, "required", out["directive"])
assert.Contains(t, out["error"], "missing required field")
}
func CustomErrorHandler(rw http.ResponseWriter, r *http.Request, err error) {
var invalidFieldError *core.InvalidFieldError
if errors.As(err, &invalidFieldError) {
rw.WriteHeader(http.StatusBadRequest) // status: 400
io.WriteString(rw, invalidFieldError.Error())
return
}
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) // status: 500
}
func TestNewRequest(t *testing.T) {
req, err := NewRequest("GET", "/products", &Pagination{
Page: 19,
PerPage: 50,
})
assert.NoError(t, err)
expected, _ := http.NewRequest("GET", "/products", nil)
expected.Body = io.NopCloser(strings.NewReader("page=19&per_page=50"))
expected.Header.Set("Content-Type", "application/x-www-form-urlencoded")
assert.Equal(t, expected, req)
}
func TestNewRequest_ErrNewFailure(t *testing.T) {
_, err := NewRequest("GET", "/products", 123)
assert.Error(t, err)
}