Repository navigation
Expand file tree
/
Copy pathconfig_usage_test.go
More file actions
262 lines (216 loc) · 7 KB
/
Copy pathconfig_usage_test.go
File metadata and controls
262 lines (216 loc) · 7 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
package mcp
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"testing"
"time"
)
// ============================================================
// Test Config Fields Are Actually Used (Verify Issue 2 Fix)
// ============================================================
func TestConfig_MaxRetries_IsUsed(t *testing.T) {
mockHTTP := NewMockHTTPClient()
mockLogger := NewMockLogger()
// Set HTTP client to return error
callCount := 0
mockHTTP.ResponseFunc = func(req *http.Request) (*http.Response, error) {
callCount++
return nil, errors.New("connection reset")
}
// Create client and set custom retry count to 5
client := NewClient(
WithHTTPClient(mockHTTP.ToHTTPClient()),
WithLogger(mockLogger),
WithAPIKey("sk-test-key"),
WithMaxRetries(5), // Set to retry 5 times
)
// Call API (should fail)
_, err := client.CallWithMessages("system", "user")
if err == nil {
t.Error("should error")
}
// Verify indeed retried 5 times (not the default 3 times)
if callCount != 5 {
t.Errorf("expected 5 retry attempts (from WithMaxRetries(5)), got %d", callCount)
}
// Verify logs show correct retry count
logs := mockLogger.GetLogsByLevel("WARN")
expectedWarningCount := 4 // Warnings will be printed on 2nd, 3rd, 4th, 5th retry
actualWarningCount := 0
for _, log := range logs {
if log.Message == "⚠️ AI API call failed, retrying (2/5)..." ||
log.Message == "⚠️ AI API call failed, retrying (3/5)..." ||
log.Message == "⚠️ AI API call failed, retrying (4/5)..." ||
log.Message == "⚠️ AI API call failed, retrying (5/5)..." {
actualWarningCount++
}
}
if actualWarningCount != expectedWarningCount {
t.Errorf("expected %d warning logs, got %d", expectedWarningCount, actualWarningCount)
for _, log := range logs {
t.Logf(" WARN: %s", log.Message)
}
}
}
func TestConfig_Temperature_IsUsed(t *testing.T) {
mockHTTP := NewMockHTTPClient()
mockHTTP.SetSuccessResponse("AI response")
mockLogger := NewMockLogger()
customTemperature := 0.8
// Create client and set custom temperature
client := NewClient(
WithHTTPClient(mockHTTP.ToHTTPClient()),
WithLogger(mockLogger),
WithAPIKey("sk-test-key"),
WithTemperature(customTemperature), // Set custom temperature
)
c := client.(*Client)
// Build request body
requestBody := c.buildMCPRequestBody("system", "user")
// Verify temperature field
temp, ok := requestBody["temperature"].(float64)
if !ok {
t.Fatal("temperature should be float64")
}
if temp != customTemperature {
t.Errorf("expected temperature %f (from WithTemperature), got %f", customTemperature, temp)
}
// Can also verify through actual HTTP request
_, err := client.CallWithMessages("system", "user")
if err != nil {
t.Fatalf("should not error: %v", err)
}
// Check sent request body
requests := mockHTTP.GetRequests()
if len(requests) != 1 {
t.Fatalf("expected 1 request, got %d", len(requests))
}
// Parse request body
var body map[string]interface{}
decoder := json.NewDecoder(requests[0].Body)
if err := decoder.Decode(&body); err != nil {
t.Fatalf("failed to decode request body: %v", err)
}
// Verify temperature
if body["temperature"] != customTemperature {
t.Errorf("expected temperature %f in HTTP request, got %v", customTemperature, body["temperature"])
}
}
func TestConfig_RetryWaitBase_IsUsed(t *testing.T) {
mockHTTP := NewMockHTTPClient()
mockLogger := NewMockLogger()
// Set success response (before ResponseFunc)
mockHTTP.SetSuccessResponse("AI response")
// Set HTTP client to return error first 2 times, success on 3rd time
callCount := 0
successResponse := mockHTTP.Response // Save success response string
mockHTTP.ResponseFunc = func(req *http.Request) (*http.Response, error) {
callCount++
if callCount <= 2 {
return nil, errors.New("timeout exceeded")
}
// 3rd time return success response
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(successResponse)),
Header: make(http.Header),
}, nil
}
// Set custom retry wait base to 1 second (instead of default 2 seconds)
customWaitBase := 1 * time.Second
client := NewClient(
WithHTTPClient(mockHTTP.ToHTTPClient()),
WithLogger(mockLogger),
WithAPIKey("sk-test-key"),
WithRetryWaitBase(customWaitBase), // Set custom wait time
WithMaxRetries(3),
)
// Record start time
start := time.Now()
// Call API
_, err := client.CallWithMessages("system", "user")
// Record end time
elapsed := time.Since(start)
// 3rd time succeeds, but failed 2 times before
if err != nil {
t.Fatalf("should succeed on 3rd attempt, got error: %v", err)
}
if callCount != 3 {
t.Errorf("expected 3 attempts, got %d", callCount)
}
// Verify wait time
// After 1st failure wait 1s (customWaitBase * 1)
// After 2nd failure wait 2s (customWaitBase * 2)
// Total wait time should be about 3s (allow some error)
expectedWait := 3 * time.Second
tolerance := 200 * time.Millisecond
if elapsed < expectedWait-tolerance || elapsed > expectedWait+tolerance {
t.Errorf("expected total time ~%v (with RetryWaitBase=%v), got %v", expectedWait, customWaitBase, elapsed)
}
}
func TestConfig_RetryableErrors_IsUsed(t *testing.T) {
mockHTTP := NewMockHTTPClient()
mockLogger := NewMockLogger()
// Custom retryable error list (only contains "custom error")
customRetryableErrors := []string{"custom error"}
client := NewClient(
WithHTTPClient(mockHTTP.ToHTTPClient()),
WithLogger(mockLogger),
WithAPIKey("sk-test-key"),
)
c := client.(*Client)
// Modify config's RetryableErrors (no WithRetryableErrors option yet)
c.config.RetryableErrors = customRetryableErrors
tests := []struct {
name string
err error
retryable bool
}{
{
name: "custom error should be retryable",
err: errors.New("custom error occurred"),
retryable: true,
},
{
name: "EOF should NOT be retryable (not in custom list)",
err: errors.New("unexpected EOF"),
retryable: false,
},
{
name: "timeout should NOT be retryable (not in custom list)",
err: errors.New("timeout exceeded"),
retryable: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := c.isRetryableError(tt.err)
if result != tt.retryable {
t.Errorf("expected isRetryableError(%v) = %v, got %v", tt.err, tt.retryable, result)
}
})
}
}
// ============================================================
// Test Default Values
// ============================================================
func TestConfig_DefaultValues(t *testing.T) {
client := NewClient()
c := client.(*Client)
// Verify default values
if c.config.MaxRetries != 3 {
t.Errorf("default MaxRetries should be 3, got %d", c.config.MaxRetries)
}
if c.config.Temperature != 0.5 {
t.Errorf("default Temperature should be 0.5, got %f", c.config.Temperature)
}
if c.config.RetryWaitBase != 2*time.Second {
t.Errorf("default RetryWaitBase should be 2s, got %v", c.config.RetryWaitBase)
}
if len(c.config.RetryableErrors) == 0 {
t.Error("default RetryableErrors should not be empty")
}
}