-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_test.go
More file actions
241 lines (218 loc) · 6.01 KB
/
client_test.go
File metadata and controls
241 lines (218 loc) · 6.01 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
package loops
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
func TestDo_RetryResetsBody(t *testing.T) {
origSleep := sleep
sleep = func(time.Duration) {}
defer func() { sleep = origSleep }()
var bodies []string
var attempts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
bodies = append(bodies, string(b))
n := attempts.Add(1)
if n == 1 {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
}
}))
defer server.Close()
client := NewClient("test-key", WithBaseURL(server.URL))
req, _ := client.newRequest(http.MethodPost, "/", bytes.NewReader([]byte(`{"hello":"world"}`)))
resp, err := client.do(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
if attempts.Load() != 2 {
t.Fatalf("expected 2 attempts, got %d", attempts.Load())
}
for i, body := range bodies {
if body != `{"hello":"world"}` {
t.Errorf("attempt %d body = %q, want non-empty JSON", i+1, body)
}
}
}
func TestNewRequest(t *testing.T) {
client := NewClient("test-key", WithBaseURL("https://example.com/api/v1"))
tests := []struct {
name string
method string
path string
}{
{"GET", http.MethodGet, "/api-key"},
{"POST", http.MethodPost, "/some-resource"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := client.newRequest(tt.method, tt.path, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Method != tt.method {
t.Errorf("method = %q, want %q", req.Method, tt.method)
}
wantURL := "https://example.com/api/v1" + tt.path
if req.URL.String() != wantURL {
t.Errorf("url = %q, want %q", req.URL.String(), wantURL)
}
wantAuth := "Bearer test-key"
if got := req.Header.Get("Authorization"); got != wantAuth {
t.Errorf("Authorization = %q, want %q", got, wantAuth)
}
if got := req.Header.Get("User-Agent"); got != fmt.Sprintf("loops-go/%s", Version) {
t.Errorf("User-Agent = %q, want %q", got, fmt.Sprintf("loops-go/%s", Version))
}
})
}
}
func TestWithUserAgent(t *testing.T) {
client := NewClient("test-key", WithBaseURL("https://example.com/api/v1"), WithUserAgent("loops-cli/1.2.3"))
req, err := client.newRequest(http.MethodGet, "/api-key", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := req.Header.Get("User-Agent"); got != "loops-cli/1.2.3" {
t.Errorf("User-Agent = %q, want %q", got, "loops-cli/1.2.3")
}
}
func TestNewRequest_InvalidURL(t *testing.T) {
client := NewClient("test-key", WithBaseURL("://bad-url"))
_, err := client.newRequest(http.MethodGet, "/path", nil)
if err == nil {
t.Error("expected error for invalid URL, got nil")
}
}
func TestErrorFromResponse(t *testing.T) {
tests := []struct {
name string
statusCode int
body string
wantMessage string
}{
{
name: "reads error field",
statusCode: http.StatusBadRequest,
body: `{"error":"something went wrong"}`,
wantMessage: "something went wrong",
},
{
name: "falls back to message field",
statusCode: http.StatusBadRequest,
body: `{"message":"something went wrong"}`,
wantMessage: "something went wrong",
},
{
name: "prefers error over message",
statusCode: http.StatusBadRequest,
body: `{"error":"error field","message":"message field"}`,
wantMessage: "error field",
},
{
name: "falls back to generic when body is empty",
statusCode: http.StatusBadRequest,
body: ``,
wantMessage: "unexpected status: 400",
},
{
name: "falls back to generic when fields are absent",
statusCode: http.StatusBadRequest,
body: `{"success":false}`,
wantMessage: "unexpected status: 400",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.statusCode)
w.Write([]byte(tt.body))
}))
defer server.Close()
resp, err := http.Get(server.URL)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
apiErr := errorFromResponse(resp)
if apiErr.Message != tt.wantMessage {
t.Errorf("Message = %q, want %q", apiErr.Message, tt.wantMessage)
}
})
}
}
func TestDo_Retries(t *testing.T) {
origSleep := sleep
sleep = func(time.Duration) {}
defer func() { sleep = origSleep }()
tests := []struct {
name string
responses []int
wantStatus int
wantAttempts int32
}{
{
name: "success on first attempt",
responses: []int{200},
wantStatus: 200,
wantAttempts: 1,
},
{
name: "retries on 429 then succeeds",
responses: []int{429, 200},
wantStatus: 200,
wantAttempts: 2,
},
{
name: "retries on 500 then succeeds",
responses: []int{500, 200},
wantStatus: 200,
wantAttempts: 2,
},
{
name: "exhausts retries on persistent 429",
responses: []int{429, 429, 429},
wantStatus: 429,
wantAttempts: 3,
},
{
name: "no retry on 401",
responses: []int{401},
wantStatus: 401,
wantAttempts: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var attempts atomic.Int32
idx := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attempts.Add(1)
w.WriteHeader(tt.responses[idx])
idx++
}))
defer server.Close()
client := NewClient("test-key", WithBaseURL(server.URL))
req, _ := client.newRequest(http.MethodGet, "/", nil)
resp, err := client.do(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.wantStatus {
t.Errorf("status = %d, want %d", resp.StatusCode, tt.wantStatus)
}
if attempts.Load() != tt.wantAttempts {
t.Errorf("attempts = %d, want %d", attempts.Load(), tt.wantAttempts)
}
})
}
}