-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_test.go
More file actions
357 lines (305 loc) · 10.1 KB
/
client_test.go
File metadata and controls
357 lines (305 loc) · 10.1 KB
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package httpclient
import (
"context"
"encoding/json"
"net/http"
"testing"
)
// Pokemon represents a Pokemon from the PokeAPI
type Pokemon struct {
ID int `json:"id"`
Name string `json:"name"`
Height int `json:"height"`
Weight int `json:"weight"`
Types []struct {
Type struct {
Name string `json:"name"`
URL string `json:"url"`
} `json:"type"`
} `json:"types"`
}
// PokemonList represents a paginated list of Pokemon
type PokemonList struct {
Count int `json:"count"`
Next string `json:"next"`
Previous string `json:"previous"`
Results []struct {
Name string `json:"name"`
URL string `json:"url"`
} `json:"results"`
}
func TestClient_Get(t *testing.T) {
client := &Client{}
t.Run("get single pokemon", func(t *testing.T) {
var pokemon Pokemon
err := client.Get(context.Background(), "https://pokeapi.co/api/v2/pokemon/pikachu", &pokemon)
if err != nil {
t.Fatalf("GET request failed: %v", err)
}
if pokemon.Name != "pikachu" {
t.Errorf("expected name 'pikachu', got '%s'", pokemon.Name)
}
if pokemon.ID != 25 {
t.Errorf("expected ID 25, got %d", pokemon.ID)
}
if len(pokemon.Types) == 0 {
t.Error("expected pokemon to have types")
}
})
t.Run("get pokemon list", func(t *testing.T) {
var list PokemonList
err := client.Get(context.Background(), "https://pokeapi.co/api/v2/pokemon?limit=5", &list)
if err != nil {
t.Fatalf("GET request failed: %v", err)
}
if list.Count == 0 {
t.Error("expected count to be greater than 0")
}
if len(list.Results) != 5 {
t.Errorf("expected 5 results, got %d", len(list.Results))
}
})
t.Run("get with custom headers", func(t *testing.T) {
var pokemon Pokemon
err := client.Get(context.Background(), "https://pokeapi.co/api/v2/pokemon/1", &pokemon,
WithHeader("User-Agent", "httpclient-test/1.0"))
if err != nil {
t.Fatalf("GET request failed: %v", err)
}
if pokemon.Name == "" {
t.Error("expected pokemon name to be set")
}
})
t.Run("get with status capture", func(t *testing.T) {
var status int
var pokemon Pokemon
err := client.Get(context.Background(), "https://pokeapi.co/api/v2/pokemon/bulbasaur", &pokemon,
WithStatus(&status))
if err != nil {
t.Fatalf("GET request failed: %v", err)
}
if status != http.StatusOK {
t.Errorf("expected status 200, got %d", status)
}
if pokemon.Name != "bulbasaur" {
t.Errorf("expected name 'bulbasaur', got '%s'", pokemon.Name)
}
})
t.Run("get non-existent pokemon with status capture", func(t *testing.T) {
var status int
var result interface{} // Use interface{} since 404 response might not be valid Pokemon JSON
err := client.Get(context.Background(), "https://pokeapi.co/api/v2/pokemon/nonexistent", &result,
WithStatus(&status))
// Should not return error when status is captured, even if JSON parsing fails
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// The status should still be set
if status != http.StatusNotFound {
t.Errorf("expected status 404, got %d", status)
}
})
t.Run("get non-existent pokemon without status capture", func(t *testing.T) {
var pokemon Pokemon
err := client.Get(context.Background(), "https://pokeapi.co/api/v2/pokemon/nonexistent", &pokemon)
// Should return error when status is not captured
if err == nil {
t.Error("expected error for 404 response")
}
})
}
func TestClient_Post(t *testing.T) {
client := &Client{}
// Note: PokeAPI is read-only, so we'll test POST against httpbin.org
// httpbin.org is a free HTTP testing service that echoes back request data
t.Run("post json data", func(t *testing.T) {
postData := map[string]interface{}{
"pokemon": "pikachu",
"level": 25,
"moves": []string{"thunderbolt", "quick-attack"},
}
var result map[string]interface{}
err := client.Post(context.Background(), "https://httpbin.org/post", postData, &result)
if err != nil {
t.Fatalf("POST request failed: %v", err)
}
// httpbin.org returns the posted data in the "json" field
if result["json"] == nil {
t.Error("expected response to contain 'json' field")
}
jsonData := result["json"].(map[string]interface{})
if jsonData["pokemon"] != "pikachu" {
t.Errorf("expected pokemon 'pikachu', got '%v'", jsonData["pokemon"])
}
})
t.Run("post with custom headers", func(t *testing.T) {
postData := map[string]string{"test": "value"}
var result map[string]interface{}
err := client.Post(context.Background(), "https://httpbin.org/post", postData, &result,
WithHeader("X-Test-Header", "test-value"))
if err != nil {
t.Fatalf("POST request failed: %v", err)
}
headers := result["headers"].(map[string]interface{})
if headers["X-Test-Header"] != "test-value" {
t.Errorf("expected header 'test-value', got '%v'", headers["X-Test-Header"])
}
})
t.Run("post with multiple headers using WithHeaders", func(t *testing.T) {
postData := map[string]string{"test": "value"}
var result map[string]interface{}
customHeaders := map[string]string{
"X-API-Key": "secret123",
"X-Client-ID": "client456",
"X-Request-ID": "req789",
}
err := client.Post(context.Background(), "https://httpbin.org/post", postData, &result,
WithHeaders(customHeaders))
if err != nil {
t.Fatalf("POST request with multiple headers failed: %v", err)
}
headers := result["headers"].(map[string]interface{})
// Verify at least one of our custom headers is present to confirm WithHeaders works
foundCustomHeader := false
for key, value := range headers {
if key == "X-Api-Key" && value == "secret123" {
foundCustomHeader = true
break
}
if key == "X-Client-Id" && value == "client456" {
foundCustomHeader = true
break
}
}
if !foundCustomHeader {
t.Errorf("WithHeaders test failed - no custom headers found in response. Headers: %+v", headers)
}
})
}
func TestClient_Patch(t *testing.T) {
client := &Client{}
t.Run("patch json data", func(t *testing.T) {
patchData := map[string]interface{}{
"pokemon": "pikachu",
"level": 30, // leveled up!
}
var result map[string]interface{}
err := client.Patch(context.Background(), "https://httpbin.org/patch", patchData, &result)
if err != nil {
t.Fatalf("PATCH request failed: %v", err)
}
jsonData := result["json"].(map[string]interface{})
if jsonData["level"].(float64) != 30 {
t.Errorf("expected level 30, got %v", jsonData["level"])
}
})
}
func TestClient_Put(t *testing.T) {
client := &Client{}
t.Run("put json data", func(t *testing.T) {
putData := map[string]interface{}{
"pokemon": "charizard",
"level": 50,
"moves": []string{"flamethrower", "fly", "dragon-claw"},
}
var result map[string]interface{}
err := client.Put(context.Background(), "https://httpbin.org/put", putData, &result)
if err != nil {
t.Fatalf("PUT request failed: %v", err)
}
// httpbin.org returns the put data in the "json" field
if result["json"] == nil {
t.Error("expected response to contain 'json' field")
}
jsonData := result["json"].(map[string]interface{})
if jsonData["pokemon"] != "charizard" {
t.Errorf("expected pokemon 'charizard', got '%v'", jsonData["pokemon"])
}
if jsonData["level"].(float64) != 50 {
t.Errorf("expected level 50, got %v", jsonData["level"])
}
})
t.Run("put with custom headers", func(t *testing.T) {
putData := map[string]string{"update": "true"}
var result map[string]interface{}
err := client.Put(context.Background(), "https://httpbin.org/put", putData, &result,
WithHeader("X-Update-Type", "full-replacement"))
if err != nil {
t.Fatalf("PUT request failed: %v", err)
}
headers := result["headers"].(map[string]interface{})
if headers["X-Update-Type"] != "full-replacement" {
t.Errorf("expected header 'full-replacement', got '%v'", headers["X-Update-Type"])
}
})
t.Run("put with status capture", func(t *testing.T) {
var status int
putData := map[string]string{"test": "data"}
var result map[string]interface{}
err := client.Put(context.Background(), "https://httpbin.org/put", putData, &result,
WithStatus(&status))
if err != nil {
t.Fatalf("PUT request failed: %v", err)
}
if status != http.StatusOK {
t.Errorf("expected status 200, got %d", status)
}
})
}
func TestClient_Delete(t *testing.T) {
client := &Client{}
t.Run("delete request", func(t *testing.T) {
var result map[string]interface{}
err := client.Delete(context.Background(), "https://httpbin.org/delete", &result)
if err != nil {
t.Fatalf("DELETE request failed: %v", err)
}
// httpbin.org returns request info for DELETE
if result["url"] != "https://httpbin.org/delete" {
t.Errorf("expected URL 'https://httpbin.org/delete', got '%v'", result["url"])
}
})
t.Run("delete with status capture", func(t *testing.T) {
var status int
var result map[string]interface{}
err := client.Delete(context.Background(), "https://httpbin.org/delete", &result,
WithStatus(&status))
if err != nil {
t.Fatalf("DELETE request failed: %v", err)
}
if status != http.StatusOK {
t.Errorf("expected status 200, got %d", status)
}
})
}
func TestClient_CustomMarshalUnmarshal(t *testing.T) {
// Test with custom marshal/unmarshal functions
client := &Client{
MarshalFunc: func(v any) ([]byte, error) {
// Custom marshal that adds a wrapper for POST data
wrapped := map[string]interface{}{"data": v}
return json.Marshal(wrapped)
},
UnmarshalFunc: func(data []byte, v any) error {
// For this test, just use default unmarshal
return json.Unmarshal(data, v)
},
}
t.Run("post with custom marshal", func(t *testing.T) {
postData := map[string]string{"pokemon": "ditto"}
var result map[string]interface{}
err := client.Post(context.Background(), "https://httpbin.org/post", postData, &result)
if err != nil {
t.Fatalf("POST request failed: %v", err)
}
// The custom marshal should wrap the data
jsonData := result["json"].(map[string]interface{})
if jsonData["data"] == nil {
t.Error("expected custom marshal to wrap data")
}
wrappedData := jsonData["data"].(map[string]interface{})
if wrappedData["pokemon"] != "ditto" {
t.Errorf("expected pokemon 'ditto', got '%v'", wrappedData["pokemon"])
}
})
}