-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_test.go
252 lines (238 loc) · 6.05 KB
/
client_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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package chttp
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
)
func TestClient_Method(t *testing.T) {
methods := [...]string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
}
type args struct {
path string
body [][]byte
}
tests := []struct {
name string
middlewares []Middleware
args args
want *http.Response
wantErr bool
}{
{
name: "default",
middlewares: nil,
args: args{
path: "/",
body: nil,
},
want: &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewBuffer(nil)),
ContentLength: 0,
},
wantErr: false,
},
{
name: "with body",
middlewares: nil,
args: args{
path: "/",
body: [][]byte{
[]byte("foo/bar"),
},
},
want: &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString("bar-baz")),
},
wantErr: false,
},
{
name: "error",
middlewares: []Middleware{
func(request *http.Request, next func(request *http.Request) (*http.Response, error)) (*http.Response, error) {
return nil, fmt.Errorf("test error")
},
},
args: args{
path: "/",
body: nil,
},
want: nil,
wantErr: true,
},
{
name: "broken url",
middlewares: nil,
args: args{
path: "invalid url",
body: nil,
},
want: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for _, method := range methods {
t.Run(method, func(t *testing.T) {
if method == http.MethodHead {
if len(tt.args.body) != 0 {
t.Skipf("HEAD method with body")
}
}
c := NewClient(nil)
c.With(tt.middlewares...)
url := "http://0.0.0.0:1234"
body := make([]byte, 0)
if tt.want != nil {
body, _ = io.ReadAll(tt.want.Body)
server := getTestServer(t, method, tt.args.path, tt.args.body, tt.want.StatusCode, body)
defer server.Close()
url = server.URL
}
got, err := c.Method(method)(context.TODO(), url+tt.args.path, tt.args.body...)
if (err != nil) != tt.wantErr {
t.Errorf("%s() error = %v, wantErr %v", method, err, tt.wantErr)
return
}
if tt.wantErr {
return
}
defer func() {
_ = got.Body.Close()
}()
equalResponses(t, got, body, tt.want.StatusCode)
})
}
})
}
}
func TestClient_With(t *testing.T) {
c := NewClient(nil)
var index int
for i := 0; i < 10; i++ {
c.With((func(i int) Middleware {
return func(request *http.Request, next func(request *http.Request) (*http.Response, error)) (*http.Response, error) {
if index != i {
t.Errorf("middleware called on wrong position: expected %d, actual %d", i, index)
}
index++
request.Header.Add("x-index", fmt.Sprintf("%d", i))
return next(request)
}
})(i))
}
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
values := request.Header.Values("x-index")
if !reflect.DeepEqual(values, []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}) {
t.Errorf("invalid value in headers: %v", values)
}
writer.WriteHeader(http.StatusOK)
}))
defer server.Close()
req, err := c.GET(context.TODO(), server.URL)
if err != nil {
t.Errorf("unexpected error: %s", err)
}
_ = req.Body.Close()
}
func TestClient_JSON(t *testing.T) {
body, _ := json.Marshal(123)
result, _ := json.Marshal(456)
server := getTestServer(t, http.MethodGet, "/", [][]byte{body}, http.StatusOK, result)
defer server.Close()
var res int
err := NewClient(nil).JSON().GET(context.TODO(), server.URL, 123, &res)
if err != nil {
t.Errorf("GET() error = %v", err)
return
}
if res != 456 {
t.Errorf("GET() wrong response \nactual: %v\n want: %v", res, 456)
}
}
func getTestServer(t *testing.T, method string, path string, bodies [][]byte, code int, result []byte) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if request.Method != method {
t.Errorf("invalid method: %v", request.Method)
}
if request.URL.Path != path {
t.Errorf("invalid path: %v", request.URL.Path)
}
data, err := io.ReadAll(request.Body)
_ = request.Body.Close()
if err != nil {
t.Errorf("error reading body: %s", err)
}
body := make([]byte, 0)
if len(bodies) > 0 {
body = bodies[0]
}
if !reflect.DeepEqual(data, body) {
t.Errorf("invalid body:\nActual: %q\nWantTo: %q", string(data), string(body))
}
writer.WriteHeader(code)
if result != nil {
_, err = writer.Write(result)
if err != nil {
t.Errorf("error writing result: %s", err)
}
}
}))
}
func equalResponses(t *testing.T, actual *http.Response, wantBody []byte, statusCode int) {
if statusCode != actual.StatusCode {
t.Errorf("http.Response: wrong StatusCode %d != %d", actual.StatusCode, statusCode)
return
}
var (
actualBody []byte
err error
)
if actual.Body != nil {
if actualBody, err = io.ReadAll(actual.Body); err != nil {
t.Errorf("http.Response error reading a actual.Body: %s", err)
return
}
}
if !reflect.DeepEqual(wantBody, actualBody) {
t.Errorf("http.Response: wrong Body \nActual: %s\nWantTo: %s", actualBody, wantBody)
}
}
func ExampleNewClient() {
client := NewClient(&http.Client{Timeout: 30 * time.Second})
client.With(func(request *http.Request, next func(request *http.Request) (*http.Response, error)) (*http.Response, error) {
log.Printf("before request: %s %s", request.Method, request.URL.String())
response, err := next(request)
log.Printf("after request: %s %s", request.Method, request.URL.String())
fmt.Print("from middleware -> ")
return response, err
})
response, err := client.HEAD(context.TODO(), "https://go.dev/")
if err != nil {
panic(err)
}
defer func() {
_ = response.Body.Close()
}()
fmt.Printf("status: %d", response.StatusCode)
// Output: from middleware -> status: 200
}