-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_test.go
245 lines (213 loc) · 8.72 KB
/
api_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
package httpclient
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"
gocmp "github.com/google/go-cmp/cmp"
"gotest.tools/v3/assert"
"gotest.tools/v3/assert/cmp"
)
func Test_NewAPI(t *testing.T) {
api := NewAPI(nil, url.URL{})
assert.Check(t, cmp.DeepEqual(api, &API{
client: nil,
serverAddress: url.URL{},
defaultRequestHeaders: make(http.Header),
defaultResponseHandlers: make(ResponseStatusHandlers),
defaultResponseBodySizeReadLimit: 65536,
}, gocmp.AllowUnexported(API{})))
api = NewAPI(http.DefaultClient, url.URL{Scheme: "http", Host: "localhost"})
assert.Check(t, cmp.DeepEqual(api, &API{
client: http.DefaultClient,
serverAddress: url.URL{Scheme: "http", Host: "localhost"},
defaultRequestHeaders: make(http.Header),
defaultResponseHandlers: make(ResponseStatusHandlers),
defaultResponseBodySizeReadLimit: 65536,
}, gocmp.AllowUnexported(API{})))
}
func Test_API_Clone(t *testing.T) {
original := &API{
client: http.DefaultClient,
serverAddress: url.URL{
Scheme: "http",
User: url.UserPassword("foo", "bar"),
Host: "localhost",
Path: "/foo",
},
defaultRequestHeaders: map[string][]string{"hello": {"world"}},
defaultResponseHandlers: map[int]ResponseHandler{503: func(*http.Response) error { return nil }},
defaultResponseBodySizeReadLimit: 58968,
}
clone := original.Clone()
assert.Check(t, cmp.DeepEqual(original, clone, // object are deeply equal
gocmp.AllowUnexported(API{}, url.Userinfo{}),
gocmp.FilterPath(
func(path gocmp.Path) bool { return path.GoString() == "{*httpclient.API}.defaultResponseHandlers[503]" },
gocmp.Comparer(func(a, b ResponseHandler) bool { return a != nil && b != nil }),
),
))
assert.Check(t, original != clone) // but pointers must be different
assert.Check(t, &original.defaultRequestHeaders != &clone.defaultRequestHeaders) // same for maps
assert.Check(t, &original.defaultResponseHandlers != &clone.defaultResponseHandlers) // same for maps
assert.Check(t, original.serverAddress.User != clone.serverAddress.User) // same for url attributes that also are pointers
}
func Test_API_URL(t *testing.T) {
t.Run("", func(t *testing.T) {
api := NewAPI(http.DefaultClient, url.URL{
Scheme: "http",
Host: "localhost",
})
endpointURL := api.URL("/foo/bar")
assert.Equal(t, "http://localhost/foo/bar", endpointURL.String())
})
t.Run("every fields are cloned", func(t *testing.T) {
serverURL, err := url.Parse("https://foo@localhost:8080")
assert.NilError(t, err)
api := NewAPI(http.DefaultClient, *serverURL)
endpointURL := api.URL("/foo/bar")
assert.Check(t, serverURL.User != endpointURL.User)
assert.Check(t, *serverURL.User == *endpointURL.User)
})
}
func Test_API_Method(t *testing.T) {
type ctxKey string
httpServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
assert.Check(t, r.URL.Path == "/foo/bar")
rw.Header().Set("hello", r.Header.Get("hello"))
rw.Header().Set("method", r.Method)
rw.WriteHeader(http.StatusOK)
}))
defer httpServer.Close()
httpServerURL, err := url.Parse(httpServer.URL)
assert.NilError(t, err)
api := NewAPI(httpServer.Client(), *httpServerURL).
WithRequestHeaders(http.Header{"hello": []string{"world"}}).
WithRequestOverrideFunc(func(req *http.Request) (*http.Request, error) {
return req.WithContext(context.WithValue(req.Context(), ctxKey("key"), "value")), nil
})
for httpMethod, apiMethod := range map[string]func(string) *RequestBuilder{
http.MethodHead: api.Head,
http.MethodGet: api.Get,
http.MethodPost: api.Post,
http.MethodPut: api.Put,
http.MethodPatch: api.Patch,
http.MethodDelete: api.Delete,
// http.MethodConnect do not have an API method, yet ?
// http.MethodOptions do not have an API method, yet ?
// http.MethodTrace do not have an API method, yet ?
} {
httpMethod, apiMethod := httpMethod, apiMethod
t.Run(httpMethod, func(t *testing.T) {
t.Run("run with defaults", func(t *testing.T) {
assert.NilError(t, api.
Do(context.Background(), apiMethod("/foo/bar")).
OnStatus(http.StatusOK, func(resp *http.Response) error {
assert.Check(t, resp.Header.Get("hello") == "world", "header 'hello' should be set by default")
assert.Check(t, resp.Header.Get("method") == httpMethod)
assert.Check(t, resp.Request.Context().Value(ctxKey("key")).(string) == "value")
return nil
}).
Error(),
)
})
t.Run("make sure all api defaults are set in builder and not after building", func(t *testing.T) {
t.Run("client should be overridable", func(t *testing.T) {
defer func() {
panicked := recover()
assert.Check(t, panicked != nil, "client should have been overridden with nil, creating a panic")
}()
assert.NilError(t, api.Execute(context.Background(), apiMethod("/foo/bar").Client(nil)))
})
t.Run("headers defaults should be overridable", func(t *testing.T) {
assert.NilError(t, api.
Do(context.Background(), apiMethod("/foo/bar").SetHeader("hello", "notworld")).
OnStatus(http.StatusOK, func(resp *http.Response) error {
assert.Check(t, resp.Header.Get("hello") == "notworld", "header 'hello' should have been overridden")
return nil
}).
Error(),
)
})
t.Run("request override func should be overridable", func(t *testing.T) {
assert.NilError(t, api.
Clone().
Do(context.Background(), apiMethod("/foo/bar").
SetOverrideFunc(func(req *http.Request) (*http.Request, error) {
return req.WithContext(context.WithValue(req.Context(), ctxKey("key"), "notvalue")), nil
}),
).
OnStatus(http.StatusOK, func(resp *http.Response) error {
assert.Check(t, resp.Request.Context().Value(ctxKey("key")).(string) == "notvalue")
return nil
}).
Error(),
)
})
})
})
}
}
func Test_API_Do(t *testing.T) {
httpServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("hello", r.Header.Get("hello"))
rw.Header().Set("method", r.Method)
if r.URL.Path == "/teapot" {
rw.WriteHeader(http.StatusTeapot)
} else {
rw.WriteHeader(http.StatusOK)
}
}))
defer httpServer.Close()
httpServerURL, err := url.Parse(httpServer.URL)
assert.NilError(t, err)
api := NewAPI(httpServer.Client(), *httpServerURL).
WithRequestHeaders(http.Header{"hello": []string{"world"}}).
WithResponseHandler(http.StatusTeapot, func(*http.Response) error { return nil }).
WithResponseBodySizeReadLimit(121212)
t.Run("should not set defaults in request", func(t *testing.T) {
t.Run("client", func(t *testing.T) {
defer func() {
panicked := recover()
assert.Check(t, panicked != nil, "default client is non-nil, but request chose a nil client, creating a panic")
}()
_ = api.Do(context.Background(), NewRequest(http.MethodGet, httpServerURL.String()).Client(nil))
})
t.Run("header", func(t *testing.T) {
assert.NilError(t, api.
Do(context.Background(), NewRequest(http.MethodGet, httpServerURL.String()).SetHeader("hello", "notworld")).
OnStatus(http.StatusOK, func(resp *http.Response) error {
assert.Check(t, resp.Header.Get("hello") == "notworld")
return nil
}).
Error(),
)
})
})
t.Run("should set defaults in response", func(t *testing.T) {
t.Run("max body read size", func(t *testing.T) {
assert.Equal(t, int64(121212), api.Do(context.Background(), NewRequest(http.MethodGet, httpServerURL.String())).bodySizeReadLimit)
})
t.Run("status not handled by default", func(t *testing.T) {
assert.ErrorContains(t, api.Do(context.Background(), api.Get("/")).Error(), "unhandled request status")
})
t.Run("status handled by default", func(t *testing.T) {
assert.NilError(t, api.Do(context.Background(), api.Get("/teapot")).Error())
})
})
}
func Test_API_Execute(t *testing.T) {
httpServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(http.StatusOK) }))
defer httpServer.Close()
httpServerURL, err := url.Parse(httpServer.URL)
assert.NilError(t, err)
t.Run("request and response are handled with default", func(t *testing.T) {
api := NewAPI(httpServer.Client(), *httpServerURL).WithResponseHandler(http.StatusOK, func(*http.Response) error { return nil })
assert.NilError(t, api.Execute(context.Background(), api.Get("/")))
})
t.Run("request and response are handled with default", func(t *testing.T) {
api := NewAPI(httpServer.Client(), *httpServerURL)
assert.ErrorContains(t, api.Execute(context.Background(), api.Get("/")), "unhandled request status")
})
}