refactor: standardize code comments

This commit is contained in:
tinkle-community
2025-12-08 01:40:48 +08:00
parent 0636ced476
commit a12c0ae8c9
103 changed files with 5466 additions and 5468 deletions

View File

@@ -11,49 +11,49 @@ import (
)
// ============================================================
// 测试 Config 字段真正被使用验证问题2修复
// Test Config Fields Are Actually Used (Verify Issue 2 Fix)
// ============================================================
func TestConfig_MaxRetries_IsUsed(t *testing.T) {
mockHTTP := NewMockHTTPClient()
mockLogger := NewMockLogger()
// 设置 HTTP 客户端返回错误
// Set HTTP client to return error
callCount := 0
mockHTTP.ResponseFunc = func(req *http.Request) (*http.Response, error) {
callCount++
return nil, errors.New("connection reset")
}
// 创建客户端并设置自定义重试次数为 5
// Create client and set custom retry count to 5
client := NewClient(
WithHTTPClient(mockHTTP.ToHTTPClient()),
WithLogger(mockLogger),
WithAPIKey("sk-test-key"),
WithMaxRetries(5), // ✅ 设置重试5次
WithMaxRetries(5), // Set to retry 5 times
)
// 调用 API应该失败
// Call API (should fail)
_, err := client.CallWithMessages("system", "user")
if err == nil {
t.Error("should error")
}
// 验证确实重试了5次而不是默认的3次
// 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 // 第2、3、4、5次重试时会打印警告
expectedWarningCount := 4 // Warnings will be printed on 2nd, 3rd, 4th, 5th retry
actualWarningCount := 0
for _, log := range logs {
if log.Message == "⚠️ AI API调用失败,正在重试 (2/5)..." ||
log.Message == "⚠️ AI API调用失败,正在重试 (3/5)..." ||
log.Message == "⚠️ AI API调用失败,正在重试 (4/5)..." ||
log.Message == "⚠️ AI API调用失败,正在重试 (5/5)..." {
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++
}
}
@@ -73,20 +73,20 @@ func TestConfig_Temperature_IsUsed(t *testing.T) {
customTemperature := 0.8
// 创建客户端并设置自定义 temperature
// Create client and set custom temperature
client := NewClient(
WithHTTPClient(mockHTTP.ToHTTPClient()),
WithLogger(mockLogger),
WithAPIKey("sk-test-key"),
WithTemperature(customTemperature), // ✅ 设置自定义 temperature
WithTemperature(customTemperature), // Set custom temperature
)
c := client.(*Client)
// 构建请求体
// Build request body
requestBody := c.buildMCPRequestBody("system", "user")
// 验证 temperature 字段
// Verify temperature field
temp, ok := requestBody["temperature"].(float64)
if !ok {
t.Fatal("temperature should be float64")
@@ -96,26 +96,26 @@ func TestConfig_Temperature_IsUsed(t *testing.T) {
t.Errorf("expected temperature %f (from WithTemperature), got %f", customTemperature, temp)
}
// 也可以通过实际 HTTP 请求验证
// 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)
}
// 验证 temperature
// Verify temperature
if body["temperature"] != customTemperature {
t.Errorf("expected temperature %f in HTTP request, got %v", customTemperature, body["temperature"])
}
@@ -125,18 +125,18 @@ func TestConfig_RetryWaitBase_IsUsed(t *testing.T) {
mockHTTP := NewMockHTTPClient()
mockLogger := NewMockLogger()
// 设置成功响应(在 ResponseFunc 之前)
// Set success response (before ResponseFunc)
mockHTTP.SetSuccessResponse("AI response")
// 设置 HTTP 客户端前2次返回错误第3次成功
// Set HTTP client to return error first 2 times, success on 3rd time
callCount := 0
successResponse := mockHTTP.Response // 保存成功响应字符串
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")
}
// 第3次返回成功响应
// 3rd time return success response
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(successResponse)),
@@ -144,27 +144,27 @@ func TestConfig_RetryWaitBase_IsUsed(t *testing.T) {
}, nil
}
// 设置自定义重试等待基数为 1 秒(而不是默认的 2 秒)
// 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), // ✅ 设置自定义等待时间
WithRetryWaitBase(customWaitBase), // Set custom wait time
WithMaxRetries(3),
)
// 记录开始时间
// Record start time
start := time.Now()
// 调用 API
// Call API
_, err := client.CallWithMessages("system", "user")
// 记录结束时间
// Record end time
elapsed := time.Since(start)
// 第3次成功但前面失败了2次
// 3rd time succeeds, but failed 2 times before
if err != nil {
t.Fatalf("should succeed on 3rd attempt, got error: %v", err)
}
@@ -173,10 +173,10 @@ func TestConfig_RetryWaitBase_IsUsed(t *testing.T) {
t.Errorf("expected 3 attempts, got %d", callCount)
}
// 验证等待时间
// 第1次失败后等待 1s (customWaitBase * 1)
// 第2次失败后等待 2s (customWaitBase * 2)
// 总等待时间应该约为 3s (允许一些误差)
// 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
@@ -189,7 +189,7 @@ func TestConfig_RetryableErrors_IsUsed(t *testing.T) {
mockHTTP := NewMockHTTPClient()
mockLogger := NewMockLogger()
// 自定义可重试错误列表(只包含 "custom error"
// Custom retryable error list (only contains "custom error")
customRetryableErrors := []string{"custom error"}
client := NewClient(
@@ -200,7 +200,7 @@ func TestConfig_RetryableErrors_IsUsed(t *testing.T) {
c := client.(*Client)
// 修改 config RetryableErrors(暂时没有 WithRetryableErrors 选项)
// Modify config's RetryableErrors (no WithRetryableErrors option yet)
c.config.RetryableErrors = customRetryableErrors
tests := []struct {
@@ -236,14 +236,14 @@ func TestConfig_RetryableErrors_IsUsed(t *testing.T) {
}
// ============================================================
// 测试默认值
// 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)
}