-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient_test.go
253 lines (212 loc) · 7.48 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
253
package golark
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
const (
driverID = "driv_123"
teamID = "team_123"
)
func TestHeaders(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userAgent := r.Header.Get("User-Agent")
if userAgent != "test user agent" {
t.Error("unexpected User-Agent value: " + userAgent)
}
fmt.Fprint(w, "{}")
}))
defer server.Close()
err := NewRequest(server.URL, "test", "123").
Headers(http.Header{"User-Agent": []string{"test user agent"}}).
Execute(&struct{}{})
if err != nil {
t.Error(err)
}
}
func TestCustomClient(t *testing.T) {
client := &http.Client{Timeout: time.Millisecond * 10}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Millisecond * 100)
fmt.Fprint(w, `{"test": "test server"}`)
}))
defer server.Close()
request := NewRequest(server.URL, "test", "123").WithClient(client)
url, err := request.ToURL()
if err != nil {
t.Error(err)
}
err = request.Execute(&struct{}{})
if err.Error() != fmt.Sprintf("Get %q: context deadline exceeded (Client.Timeout exceeded while awaiting headers)", url) {
t.Error("unexpected error: " + err.Error())
}
}
func TestNoTrailingSlash(t *testing.T) {
request := NewRequest("https://test.com/api", "team", teamID)
testURL(request, "https://test.com/api/team/team_123/", t)
request = NewRequest("https://test.com/api/", "team", teamID)
testURL(request, "https://test.com/api/team/team_123/", t)
}
func TestExpandOnly(t *testing.T) {
t.Parallel()
request := NewRequest("https://test.com/api/", "team", teamID).
Expand(NewField("nation_url").
Expand(NewField("eventoccurrence_urls"))).
Expand(NewField("driver_urls"))
testURL(request, "https://test.com/api/team/team_123/?fields_to_expand=driver_urls,nation_url,nation_url__eventoccurrence_urls", t)
}
func TestMultipleExpansion(t *testing.T) {
t.Parallel()
request := NewRequest("https://test.com/api/", "session-occurrence", "").
AddField(NewField("channel_urls").
WithSubField(NewField("self")).
WithSubField(NewField("name")).
WithSubField(NewField("driver_urls").
WithSubField(NewField("driver_racingnumber")).
WithSubField(NewField("team_url").
WithSubField(NewField("name")).
WithSubField(NewField("colour"))))).
WithFilter("year", NewFilter(GreaterThan, "2017"))
testURL(request, "https://test.com/api/session-occurrence/?fields=channel_urls,channel_urls__self,channel_urls__name,channel_urls__driver_urls,channel_urls__driver_urls__driver_racingnumber,channel_urls__driver_urls__team_url,channel_urls__driver_urls__team_url__name,channel_urls__driver_urls__team_url__colour&fields_to_expand=channel_urls,channel_urls__driver_urls,channel_urls__driver_urls__team_url&year__gt=2017", t)
}
func TestRequestFilter(t *testing.T) {
t.Parallel()
request := NewRequest("https://test.com/api/", "sets", "").
AddField(NewField("title")).
AddField(NewField("self")).
WithFilter("set_type_slug", NewFilter(Equals, "video"))
testURL(request, "https://test.com/api/sets/?fields=title,self&set_type_slug=video", t)
}
func TestOrder(t *testing.T) {
t.Parallel()
year := NewField("year")
request := NewRequest("https://test.com/api/", "race-season", "").
AddField(year).
AddField(NewField("name")).
AddField(NewField("self")).
OrderBy(year, Ascending)
testURL(request, "https://test.com/api/race-season/?fields=year,name,self&order=year", t)
request.OrderBy(year, Descending)
testURL(request, "https://test.com/api/race-season/?fields=year,name,self&order=-year", t)
}
func TestFieldFilter(t *testing.T) {
t.Parallel()
request := NewRequest("https://test.com/api/", "race-season", "").
AddField(NewField("year").
WithFilter(NewFilter(GreaterThan, "2017"))).
AddField(NewField("name")).
AddField(NewField("self"))
testURL(request, "https://test.com/api/race-season/?fields=year,name,self&year__gt=2017", t)
}
func TestExpandedField(t *testing.T) {
t.Parallel()
request := NewRequest("https://test.com/api/", "driver", driverID).
AddField(NewField("first_name")).
AddField(NewField("last_name")).
AddField(NewField("team_url").
WithSubField(NewField("name")).
WithSubField(NewField("colour"))).
AddField(NewField("driver_tla"))
testURL(request, "https://test.com/api/driver/driv_123/?fields=first_name%2Clast_name%2Cteam_url%2Cteam_url__colour%2Cteam_url__name%2Cdriver_tla&fields_to_expand=team_url", t)
}
func TestAllFields(t *testing.T) {
t.Parallel()
request := NewRequest("https://test.com/api/", "driver", driverID)
testURL(request, "https://test.com/api/driver/driv_123/", t)
}
func TestExecute(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"test": "test server"}`)
}))
err := NewRequest(server.URL, "test", "123").Execute(&struct{}{})
if err != nil {
t.Error("unexpected error: " + err.Error())
}
server.Close()
}
func TestContext(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second)
fmt.Fprint(w, `{"test": "test server"}`)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
defer cancel()
err := NewRequest(server.URL, "test", "123").WithContext(ctx).Execute(&struct{}{})
if !errors.Is(err, ctx.Err()) {
t.Error("expected timeout")
}
}
func TestServerError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
fmt.Fprint(w, `{"error": "test error"}`)
}))
err := NewRequest(server.URL, "test", "123").Execute(&struct{}{})
if !errors.Is(err, errHTTP) {
t.Error(err)
}
server.Close()
}
func testURL(r *Request, expectedURL string, t *testing.T) {
expected, err := url.Parse(expectedURL)
if err != nil {
t.Error("Invalid expected URL:", err)
}
actual, err := r.ToURL()
if err != nil {
t.Error("Error generating URL:", err)
}
if expected.Path != actual.Path {
t.Errorf("incorrect URL path\nexpected: %s\ngot: %s", expected.Path, actual.Path)
}
if expected.Host != actual.Host {
t.Errorf("incorrect host\nexpected: %s\ngot: %s", expected.Host, actual.Host)
}
if expected.Fragment != actual.Fragment {
t.Errorf("incorrect fragment\nexpected: %s\ngot: %s", expected.Fragment, actual.Fragment)
}
compareValues(expected.Query(), actual.Query(), t)
}
func compareCSV(expected, actual string, t *testing.T) {
expectedMap := make(map[string]int)
actualMap := make(map[string]int)
for _, expectedElem := range strings.Split(expected, ",") {
expectedMap[expectedElem]++
}
for _, actualElem := range strings.Split(actual, ",") {
actualMap[actualElem]++
}
for expectedKey, expectedVal := range expectedMap {
if actualMap[expectedKey] != expectedVal {
t.Error("URL does not contain", expectedKey)
}
}
for actualKey, actualVal := range actualMap {
if expectedMap[actualKey] != actualVal {
t.Error("URL contains unexpected value", actualKey)
}
}
}
func compareValues(expected, actual url.Values, t *testing.T) {
for expectedKey, expectedVal := range expected {
actualVal, ok := actual[expectedKey]
if !ok {
t.Error("URL does not contain query param", expectedKey)
} else {
compareCSV(expectedVal[0], actualVal[0], t)
}
}
for actualKey := range actual {
_, ok := expected[actualKey]
if !ok {
t.Error("URL contains unexpected query param", actualKey)
}
}
}