fix: 修复 /v1/messages 间歇性 400 错误 (#112)
* fix(upstream): 修复上游格式兼容性问题
- 跳过Claude模型无signature的thinking block
- 支持custom类型工具(MCP)格式转换
- 添加ClaudeCustomToolSpec结构体支持MCP工具
- 添加Custom字段验证,跳过无效custom工具
- 在convertClaudeToolsToGeminiTools中添加schema清理
- 完整的单元测试覆盖,包含边界情况
修复: Issue 0.1 signature缺失, Issue 0.2 custom工具格式
改进: Codex审查发现的2个重要问题
测试:
- TestBuildParts_ThinkingBlockWithoutSignature: 验证thinking block处理
- TestBuildTools_CustomTypeTools: 验证custom工具转换和边界情况
- TestConvertClaudeToolsToGeminiTools_CustomType: 验证service层转换
* feat(gemini): 添加Gemini限额与TierID支持
实现PR1:Gemini限额与TierID功能
后端修改:
- GeminiTokenInfo结构体添加TierID字段
- fetchProjectID函数返回(projectID, tierID, error)
- 从LoadCodeAssist响应中提取tierID(优先IsDefault,回退到第一个非空tier)
- ExchangeCode、RefreshAccountToken、GetAccessToken函数更新以处理tierID
- BuildAccountCredentials函数保存tier_id到credentials
前端修改:
- AccountStatusIndicator组件添加tier显示
- 支持LEGACY/PRO/ULTRA等tier类型的友好显示
- 使用蓝色badge展示tier信息
技术细节:
- tierID提取逻辑:优先选择IsDefault的tier,否则选择第一个非空tier
- 所有fetchProjectID调用点已更新以处理新的返回签名
- 前端gracefully处理missing/unknown tier_id
* refactor(gemini): 优化TierID实现并添加安全验证
根据并发代码审查(code-reviewer, security-auditor, gemini, codex)的反馈进行改进:
安全改进:
- 添加validateTierID函数验证tier_id格式和长度(最大64字符)
- 限制tier_id字符集为字母数字、下划线、连字符和斜杠
- 在BuildAccountCredentials中验证tier_id后再存储
- 静默跳过无效tier_id,不阻塞账户创建
代码质量改进:
- 提取extractTierIDFromAllowedTiers辅助函数消除重复代码
- 重构fetchProjectID函数,tierID提取逻辑只执行一次
- 改进代码可读性和可维护性
审查工具:
- code-reviewer agent (a09848e)
- security-auditor agent (a9a149c)
- gemini CLI (bcc7c81)
- codex (b5d8919)
修复问题:
- HIGH: 未验证的tier_id输入
- MEDIUM: 代码重复(tierID提取逻辑重复2次)
* fix(format): 修复 gofmt 格式问题
- 修复 claude_types.go 中的字段对齐问题
- 修复 gemini_messages_compat_service.go 中的缩进问题
* fix(upstream): 修复上游格式兼容性问题 (#14)
* fix(upstream): 修复上游格式兼容性问题
- 跳过Claude模型无signature的thinking block
- 支持custom类型工具(MCP)格式转换
- 添加ClaudeCustomToolSpec结构体支持MCP工具
- 添加Custom字段验证,跳过无效custom工具
- 在convertClaudeToolsToGeminiTools中添加schema清理
- 完整的单元测试覆盖,包含边界情况
修复: Issue 0.1 signature缺失, Issue 0.2 custom工具格式
改进: Codex审查发现的2个重要问题
测试:
- TestBuildParts_ThinkingBlockWithoutSignature: 验证thinking block处理
- TestBuildTools_CustomTypeTools: 验证custom工具转换和边界情况
- TestConvertClaudeToolsToGeminiTools_CustomType: 验证service层转换
* fix(format): 修复 gofmt 格式问题
- 修复 claude_types.go 中的字段对齐问题
- 修复 gemini_messages_compat_service.go 中的缩进问题
* fix(format): 修复 claude_types.go 的 gofmt 格式问题
* feat(antigravity): 优化 thinking block 和 schema 处理
- 为 dummy thinking block 添加 ThoughtSignature
- 重构 thinking block 处理逻辑,在每个条件分支内创建 part
- 优化 excludedSchemaKeys,移除 Gemini 实际支持的字段
(minItems, maxItems, minimum, maximum, additionalProperties, format)
- 添加详细注释说明 Gemini API 支持的 schema 字段
* fix(antigravity): 增强 schema 清理的安全性
基于 Codex review 建议:
- 添加 format 字段白名单过滤,只保留 Gemini 支持的 date-time/date/time
- 补充更多不支持的 schema 关键字到黑名单:
* 组合 schema: oneOf, anyOf, allOf, not, if/then/else
* 对象验证: minProperties, maxProperties, patternProperties 等
* 定义引用: $defs, definitions
- 避免不支持的 schema 字段导致 Gemini API 校验失败
* fix(lint): 修复 gemini_messages_compat_service 空分支警告
- 在 cleanToolSchema 的 if 语句中添加 continue
- 移除重复的注释
* fix(antigravity): 移除 minItems/maxItems 以兼容 Claude API
- 将 minItems 和 maxItems 添加到 schema 黑名单
- Claude API (Vertex AI) 不支持这些数组验证字段
- 添加调试日志记录工具 schema 转换过程
- 修复 tools.14.custom.input_schema 验证错误
* fix(antigravity): 修复 additionalProperties schema 对象问题
- 将 additionalProperties 的 schema 对象转换为布尔值 true
- Claude API 只支持 additionalProperties: false,不支持 schema 对象
- 修复 tools.14.custom.input_schema 验证错误
- 参考 Claude 官方文档的 JSON Schema 限制
* fix(antigravity): 修复 Claude 模型 thinking 块兼容性问题
- 完全跳过 Claude 模型的 thinking 块以避免 signature 验证失败
- 只在 Gemini 模型中使用 dummy thought signature
- 修改 additionalProperties 默认值为 false(更安全)
- 添加调试日志以便排查问题
* fix(upstream): 修复跨模型切换时的 dummy signature 问题
基于 Codex review 和用户场景分析的修复:
1. 问题场景
- Gemini (thinking) → Claude (thinking) 切换时
- Gemini 返回的 thinking 块使用 dummy signature
- Claude API 会拒绝 dummy signature,导致 400 错误
2. 修复内容
- request_transformer.go:262: 跳过 dummy signature
- 只保留真实的 Claude signature
- 支持频繁的跨模型切换
3. 其他修复(基于 Codex review)
- gateway_service.go:691: 修复 io.ReadAll 错误处理
- gateway_service.go:687: 条件日志(尊重 LogUpstreamErrorBody 配置)
- gateway_service.go:915: 收紧 400 failover 启发式
- request_transformer.go:188: 移除签名成功日志
4. 新增功能(默认关闭)
- 阶段 1: 上游错误日志(GATEWAY_LOG_UPSTREAM_ERROR_BODY)
- 阶段 2: Antigravity thinking 修复
- 阶段 3: API-key beta 注入(GATEWAY_INJECT_BETA_FOR_APIKEY)
- 阶段 3: 智能 400 failover(GATEWAY_FAILOVER_ON_400)
测试:所有测试通过
* fix(lint): 修复 golangci-lint 问题
- 应用 De Morgan 定律简化条件判断
- 修复 gofmt 格式问题
- 移除未使用的 min 函数
2026-01-01 10:45:57 +08:00
|
|
|
|
package service
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2026-02-03 06:01:29 +08:00
|
|
|
|
"encoding/json"
|
2026-02-10 08:59:30 +08:00
|
|
|
|
"fmt"
|
2026-02-14 11:23:10 +08:00
|
|
|
|
"io"
|
|
|
|
|
|
"net/http"
|
|
|
|
|
|
"net/http/httptest"
|
2026-02-03 06:01:29 +08:00
|
|
|
|
"strings"
|
fix: 修复 /v1/messages 间歇性 400 错误 (#112)
* fix(upstream): 修复上游格式兼容性问题
- 跳过Claude模型无signature的thinking block
- 支持custom类型工具(MCP)格式转换
- 添加ClaudeCustomToolSpec结构体支持MCP工具
- 添加Custom字段验证,跳过无效custom工具
- 在convertClaudeToolsToGeminiTools中添加schema清理
- 完整的单元测试覆盖,包含边界情况
修复: Issue 0.1 signature缺失, Issue 0.2 custom工具格式
改进: Codex审查发现的2个重要问题
测试:
- TestBuildParts_ThinkingBlockWithoutSignature: 验证thinking block处理
- TestBuildTools_CustomTypeTools: 验证custom工具转换和边界情况
- TestConvertClaudeToolsToGeminiTools_CustomType: 验证service层转换
* feat(gemini): 添加Gemini限额与TierID支持
实现PR1:Gemini限额与TierID功能
后端修改:
- GeminiTokenInfo结构体添加TierID字段
- fetchProjectID函数返回(projectID, tierID, error)
- 从LoadCodeAssist响应中提取tierID(优先IsDefault,回退到第一个非空tier)
- ExchangeCode、RefreshAccountToken、GetAccessToken函数更新以处理tierID
- BuildAccountCredentials函数保存tier_id到credentials
前端修改:
- AccountStatusIndicator组件添加tier显示
- 支持LEGACY/PRO/ULTRA等tier类型的友好显示
- 使用蓝色badge展示tier信息
技术细节:
- tierID提取逻辑:优先选择IsDefault的tier,否则选择第一个非空tier
- 所有fetchProjectID调用点已更新以处理新的返回签名
- 前端gracefully处理missing/unknown tier_id
* refactor(gemini): 优化TierID实现并添加安全验证
根据并发代码审查(code-reviewer, security-auditor, gemini, codex)的反馈进行改进:
安全改进:
- 添加validateTierID函数验证tier_id格式和长度(最大64字符)
- 限制tier_id字符集为字母数字、下划线、连字符和斜杠
- 在BuildAccountCredentials中验证tier_id后再存储
- 静默跳过无效tier_id,不阻塞账户创建
代码质量改进:
- 提取extractTierIDFromAllowedTiers辅助函数消除重复代码
- 重构fetchProjectID函数,tierID提取逻辑只执行一次
- 改进代码可读性和可维护性
审查工具:
- code-reviewer agent (a09848e)
- security-auditor agent (a9a149c)
- gemini CLI (bcc7c81)
- codex (b5d8919)
修复问题:
- HIGH: 未验证的tier_id输入
- MEDIUM: 代码重复(tierID提取逻辑重复2次)
* fix(format): 修复 gofmt 格式问题
- 修复 claude_types.go 中的字段对齐问题
- 修复 gemini_messages_compat_service.go 中的缩进问题
* fix(upstream): 修复上游格式兼容性问题 (#14)
* fix(upstream): 修复上游格式兼容性问题
- 跳过Claude模型无signature的thinking block
- 支持custom类型工具(MCP)格式转换
- 添加ClaudeCustomToolSpec结构体支持MCP工具
- 添加Custom字段验证,跳过无效custom工具
- 在convertClaudeToolsToGeminiTools中添加schema清理
- 完整的单元测试覆盖,包含边界情况
修复: Issue 0.1 signature缺失, Issue 0.2 custom工具格式
改进: Codex审查发现的2个重要问题
测试:
- TestBuildParts_ThinkingBlockWithoutSignature: 验证thinking block处理
- TestBuildTools_CustomTypeTools: 验证custom工具转换和边界情况
- TestConvertClaudeToolsToGeminiTools_CustomType: 验证service层转换
* fix(format): 修复 gofmt 格式问题
- 修复 claude_types.go 中的字段对齐问题
- 修复 gemini_messages_compat_service.go 中的缩进问题
* fix(format): 修复 claude_types.go 的 gofmt 格式问题
* feat(antigravity): 优化 thinking block 和 schema 处理
- 为 dummy thinking block 添加 ThoughtSignature
- 重构 thinking block 处理逻辑,在每个条件分支内创建 part
- 优化 excludedSchemaKeys,移除 Gemini 实际支持的字段
(minItems, maxItems, minimum, maximum, additionalProperties, format)
- 添加详细注释说明 Gemini API 支持的 schema 字段
* fix(antigravity): 增强 schema 清理的安全性
基于 Codex review 建议:
- 添加 format 字段白名单过滤,只保留 Gemini 支持的 date-time/date/time
- 补充更多不支持的 schema 关键字到黑名单:
* 组合 schema: oneOf, anyOf, allOf, not, if/then/else
* 对象验证: minProperties, maxProperties, patternProperties 等
* 定义引用: $defs, definitions
- 避免不支持的 schema 字段导致 Gemini API 校验失败
* fix(lint): 修复 gemini_messages_compat_service 空分支警告
- 在 cleanToolSchema 的 if 语句中添加 continue
- 移除重复的注释
* fix(antigravity): 移除 minItems/maxItems 以兼容 Claude API
- 将 minItems 和 maxItems 添加到 schema 黑名单
- Claude API (Vertex AI) 不支持这些数组验证字段
- 添加调试日志记录工具 schema 转换过程
- 修复 tools.14.custom.input_schema 验证错误
* fix(antigravity): 修复 additionalProperties schema 对象问题
- 将 additionalProperties 的 schema 对象转换为布尔值 true
- Claude API 只支持 additionalProperties: false,不支持 schema 对象
- 修复 tools.14.custom.input_schema 验证错误
- 参考 Claude 官方文档的 JSON Schema 限制
* fix(antigravity): 修复 Claude 模型 thinking 块兼容性问题
- 完全跳过 Claude 模型的 thinking 块以避免 signature 验证失败
- 只在 Gemini 模型中使用 dummy thought signature
- 修改 additionalProperties 默认值为 false(更安全)
- 添加调试日志以便排查问题
* fix(upstream): 修复跨模型切换时的 dummy signature 问题
基于 Codex review 和用户场景分析的修复:
1. 问题场景
- Gemini (thinking) → Claude (thinking) 切换时
- Gemini 返回的 thinking 块使用 dummy signature
- Claude API 会拒绝 dummy signature,导致 400 错误
2. 修复内容
- request_transformer.go:262: 跳过 dummy signature
- 只保留真实的 Claude signature
- 支持频繁的跨模型切换
3. 其他修复(基于 Codex review)
- gateway_service.go:691: 修复 io.ReadAll 错误处理
- gateway_service.go:687: 条件日志(尊重 LogUpstreamErrorBody 配置)
- gateway_service.go:915: 收紧 400 failover 启发式
- request_transformer.go:188: 移除签名成功日志
4. 新增功能(默认关闭)
- 阶段 1: 上游错误日志(GATEWAY_LOG_UPSTREAM_ERROR_BODY)
- 阶段 2: Antigravity thinking 修复
- 阶段 3: API-key beta 注入(GATEWAY_INJECT_BETA_FOR_APIKEY)
- 阶段 3: 智能 400 failover(GATEWAY_FAILOVER_ON_400)
测试:所有测试通过
* fix(lint): 修复 golangci-lint 问题
- 应用 De Morgan 定律简化条件判断
- 修复 gofmt 格式问题
- 移除未使用的 min 函数
2026-01-01 10:45:57 +08:00
|
|
|
|
"testing"
|
2026-02-10 08:59:30 +08:00
|
|
|
|
"time"
|
|
|
|
|
|
|
2026-02-14 11:23:10 +08:00
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/config"
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2026-02-10 08:59:30 +08:00
|
|
|
|
"github.com/stretchr/testify/require"
|
fix: 修复 /v1/messages 间歇性 400 错误 (#112)
* fix(upstream): 修复上游格式兼容性问题
- 跳过Claude模型无signature的thinking block
- 支持custom类型工具(MCP)格式转换
- 添加ClaudeCustomToolSpec结构体支持MCP工具
- 添加Custom字段验证,跳过无效custom工具
- 在convertClaudeToolsToGeminiTools中添加schema清理
- 完整的单元测试覆盖,包含边界情况
修复: Issue 0.1 signature缺失, Issue 0.2 custom工具格式
改进: Codex审查发现的2个重要问题
测试:
- TestBuildParts_ThinkingBlockWithoutSignature: 验证thinking block处理
- TestBuildTools_CustomTypeTools: 验证custom工具转换和边界情况
- TestConvertClaudeToolsToGeminiTools_CustomType: 验证service层转换
* feat(gemini): 添加Gemini限额与TierID支持
实现PR1:Gemini限额与TierID功能
后端修改:
- GeminiTokenInfo结构体添加TierID字段
- fetchProjectID函数返回(projectID, tierID, error)
- 从LoadCodeAssist响应中提取tierID(优先IsDefault,回退到第一个非空tier)
- ExchangeCode、RefreshAccountToken、GetAccessToken函数更新以处理tierID
- BuildAccountCredentials函数保存tier_id到credentials
前端修改:
- AccountStatusIndicator组件添加tier显示
- 支持LEGACY/PRO/ULTRA等tier类型的友好显示
- 使用蓝色badge展示tier信息
技术细节:
- tierID提取逻辑:优先选择IsDefault的tier,否则选择第一个非空tier
- 所有fetchProjectID调用点已更新以处理新的返回签名
- 前端gracefully处理missing/unknown tier_id
* refactor(gemini): 优化TierID实现并添加安全验证
根据并发代码审查(code-reviewer, security-auditor, gemini, codex)的反馈进行改进:
安全改进:
- 添加validateTierID函数验证tier_id格式和长度(最大64字符)
- 限制tier_id字符集为字母数字、下划线、连字符和斜杠
- 在BuildAccountCredentials中验证tier_id后再存储
- 静默跳过无效tier_id,不阻塞账户创建
代码质量改进:
- 提取extractTierIDFromAllowedTiers辅助函数消除重复代码
- 重构fetchProjectID函数,tierID提取逻辑只执行一次
- 改进代码可读性和可维护性
审查工具:
- code-reviewer agent (a09848e)
- security-auditor agent (a9a149c)
- gemini CLI (bcc7c81)
- codex (b5d8919)
修复问题:
- HIGH: 未验证的tier_id输入
- MEDIUM: 代码重复(tierID提取逻辑重复2次)
* fix(format): 修复 gofmt 格式问题
- 修复 claude_types.go 中的字段对齐问题
- 修复 gemini_messages_compat_service.go 中的缩进问题
* fix(upstream): 修复上游格式兼容性问题 (#14)
* fix(upstream): 修复上游格式兼容性问题
- 跳过Claude模型无signature的thinking block
- 支持custom类型工具(MCP)格式转换
- 添加ClaudeCustomToolSpec结构体支持MCP工具
- 添加Custom字段验证,跳过无效custom工具
- 在convertClaudeToolsToGeminiTools中添加schema清理
- 完整的单元测试覆盖,包含边界情况
修复: Issue 0.1 signature缺失, Issue 0.2 custom工具格式
改进: Codex审查发现的2个重要问题
测试:
- TestBuildParts_ThinkingBlockWithoutSignature: 验证thinking block处理
- TestBuildTools_CustomTypeTools: 验证custom工具转换和边界情况
- TestConvertClaudeToolsToGeminiTools_CustomType: 验证service层转换
* fix(format): 修复 gofmt 格式问题
- 修复 claude_types.go 中的字段对齐问题
- 修复 gemini_messages_compat_service.go 中的缩进问题
* fix(format): 修复 claude_types.go 的 gofmt 格式问题
* feat(antigravity): 优化 thinking block 和 schema 处理
- 为 dummy thinking block 添加 ThoughtSignature
- 重构 thinking block 处理逻辑,在每个条件分支内创建 part
- 优化 excludedSchemaKeys,移除 Gemini 实际支持的字段
(minItems, maxItems, minimum, maximum, additionalProperties, format)
- 添加详细注释说明 Gemini API 支持的 schema 字段
* fix(antigravity): 增强 schema 清理的安全性
基于 Codex review 建议:
- 添加 format 字段白名单过滤,只保留 Gemini 支持的 date-time/date/time
- 补充更多不支持的 schema 关键字到黑名单:
* 组合 schema: oneOf, anyOf, allOf, not, if/then/else
* 对象验证: minProperties, maxProperties, patternProperties 等
* 定义引用: $defs, definitions
- 避免不支持的 schema 字段导致 Gemini API 校验失败
* fix(lint): 修复 gemini_messages_compat_service 空分支警告
- 在 cleanToolSchema 的 if 语句中添加 continue
- 移除重复的注释
* fix(antigravity): 移除 minItems/maxItems 以兼容 Claude API
- 将 minItems 和 maxItems 添加到 schema 黑名单
- Claude API (Vertex AI) 不支持这些数组验证字段
- 添加调试日志记录工具 schema 转换过程
- 修复 tools.14.custom.input_schema 验证错误
* fix(antigravity): 修复 additionalProperties schema 对象问题
- 将 additionalProperties 的 schema 对象转换为布尔值 true
- Claude API 只支持 additionalProperties: false,不支持 schema 对象
- 修复 tools.14.custom.input_schema 验证错误
- 参考 Claude 官方文档的 JSON Schema 限制
* fix(antigravity): 修复 Claude 模型 thinking 块兼容性问题
- 完全跳过 Claude 模型的 thinking 块以避免 signature 验证失败
- 只在 Gemini 模型中使用 dummy thought signature
- 修改 additionalProperties 默认值为 false(更安全)
- 添加调试日志以便排查问题
* fix(upstream): 修复跨模型切换时的 dummy signature 问题
基于 Codex review 和用户场景分析的修复:
1. 问题场景
- Gemini (thinking) → Claude (thinking) 切换时
- Gemini 返回的 thinking 块使用 dummy signature
- Claude API 会拒绝 dummy signature,导致 400 错误
2. 修复内容
- request_transformer.go:262: 跳过 dummy signature
- 只保留真实的 Claude signature
- 支持频繁的跨模型切换
3. 其他修复(基于 Codex review)
- gateway_service.go:691: 修复 io.ReadAll 错误处理
- gateway_service.go:687: 条件日志(尊重 LogUpstreamErrorBody 配置)
- gateway_service.go:915: 收紧 400 failover 启发式
- request_transformer.go:188: 移除签名成功日志
4. 新增功能(默认关闭)
- 阶段 1: 上游错误日志(GATEWAY_LOG_UPSTREAM_ERROR_BODY)
- 阶段 2: Antigravity thinking 修复
- 阶段 3: API-key beta 注入(GATEWAY_INJECT_BETA_FOR_APIKEY)
- 阶段 3: 智能 400 failover(GATEWAY_FAILOVER_ON_400)
测试:所有测试通过
* fix(lint): 修复 golangci-lint 问题
- 应用 De Morgan 定律简化条件判断
- 修复 gofmt 格式问题
- 移除未使用的 min 函数
2026-01-01 10:45:57 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// TestConvertClaudeToolsToGeminiTools_CustomType 测试custom类型工具转换
|
|
|
|
|
|
func TestConvertClaudeToolsToGeminiTools_CustomType(t *testing.T) {
|
|
|
|
|
|
tests := []struct {
|
|
|
|
|
|
name string
|
|
|
|
|
|
tools any
|
|
|
|
|
|
expectedLen int
|
|
|
|
|
|
description string
|
|
|
|
|
|
}{
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "Standard tools",
|
|
|
|
|
|
tools: []any{
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"name": "get_weather",
|
|
|
|
|
|
"description": "Get weather info",
|
|
|
|
|
|
"input_schema": map[string]any{"type": "object"},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
expectedLen: 1,
|
|
|
|
|
|
description: "标准工具格式应该正常转换",
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "Custom type tool (MCP format)",
|
|
|
|
|
|
tools: []any{
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"type": "custom",
|
|
|
|
|
|
"name": "mcp_tool",
|
|
|
|
|
|
"custom": map[string]any{
|
|
|
|
|
|
"description": "MCP tool description",
|
|
|
|
|
|
"input_schema": map[string]any{"type": "object"},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
expectedLen: 1,
|
|
|
|
|
|
description: "Custom类型工具应该从custom字段读取",
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "Mixed standard and custom tools",
|
|
|
|
|
|
tools: []any{
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"name": "standard_tool",
|
|
|
|
|
|
"description": "Standard",
|
|
|
|
|
|
"input_schema": map[string]any{"type": "object"},
|
|
|
|
|
|
},
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"type": "custom",
|
|
|
|
|
|
"name": "custom_tool",
|
|
|
|
|
|
"custom": map[string]any{
|
|
|
|
|
|
"description": "Custom",
|
|
|
|
|
|
"input_schema": map[string]any{"type": "object"},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
expectedLen: 1,
|
|
|
|
|
|
description: "混合工具应该都能正确转换",
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "Custom tool without custom field",
|
|
|
|
|
|
tools: []any{
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"type": "custom",
|
|
|
|
|
|
"name": "invalid_custom",
|
|
|
|
|
|
// 缺少 custom 字段
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
expectedLen: 0, // 应该被跳过
|
|
|
|
|
|
description: "缺少custom字段的custom工具应该被跳过",
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for _, tt := range tests {
|
|
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
|
|
|
|
result := convertClaudeToolsToGeminiTools(tt.tools)
|
|
|
|
|
|
|
|
|
|
|
|
if tt.expectedLen == 0 {
|
|
|
|
|
|
if result != nil {
|
|
|
|
|
|
t.Errorf("%s: expected nil result, got %v", tt.description, result)
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if result == nil {
|
|
|
|
|
|
t.Fatalf("%s: expected non-nil result", tt.description)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if len(result) != 1 {
|
|
|
|
|
|
t.Errorf("%s: expected 1 tool declaration, got %d", tt.description, len(result))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
toolDecl, ok := result[0].(map[string]any)
|
|
|
|
|
|
if !ok {
|
|
|
|
|
|
t.Fatalf("%s: result[0] is not map[string]any", tt.description)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
funcDecls, ok := toolDecl["functionDeclarations"].([]any)
|
|
|
|
|
|
if !ok {
|
|
|
|
|
|
t.Fatalf("%s: functionDeclarations is not []any", tt.description)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
toolsArr, _ := tt.tools.([]any)
|
|
|
|
|
|
expectedFuncCount := 0
|
|
|
|
|
|
for _, tool := range toolsArr {
|
|
|
|
|
|
toolMap, _ := tool.(map[string]any)
|
|
|
|
|
|
if toolMap["name"] != "" {
|
|
|
|
|
|
// 检查是否为有效的custom工具
|
|
|
|
|
|
if toolMap["type"] == "custom" {
|
|
|
|
|
|
if toolMap["custom"] != nil {
|
|
|
|
|
|
expectedFuncCount++
|
|
|
|
|
|
}
|
|
|
|
|
|
} else {
|
|
|
|
|
|
expectedFuncCount++
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if len(funcDecls) != expectedFuncCount {
|
|
|
|
|
|
t.Errorf("%s: expected %d function declarations, got %d",
|
|
|
|
|
|
tt.description, expectedFuncCount, len(funcDecls))
|
|
|
|
|
|
}
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-02-03 06:01:29 +08:00
|
|
|
|
|
2026-02-14 11:23:10 +08:00
|
|
|
|
func TestGeminiHandleNativeNonStreamingResponse_DebugDisabledDoesNotEmitHeaderLogs(t *testing.T) {
|
|
|
|
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
|
|
logSink, restore := captureStructuredLog(t)
|
|
|
|
|
|
defer restore()
|
|
|
|
|
|
|
|
|
|
|
|
svc := &GeminiMessagesCompatService{
|
|
|
|
|
|
cfg: &config.Config{
|
|
|
|
|
|
Gateway: config.GatewayConfig{
|
|
|
|
|
|
GeminiDebugResponseHeaders: false,
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
w := httptest.NewRecorder()
|
|
|
|
|
|
c, _ := gin.CreateTestContext(w)
|
|
|
|
|
|
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
|
|
|
|
|
|
|
|
|
|
|
resp := &http.Response{
|
|
|
|
|
|
StatusCode: http.StatusOK,
|
|
|
|
|
|
Header: http.Header{
|
|
|
|
|
|
"Content-Type": []string{"application/json"},
|
|
|
|
|
|
"X-RateLimit-Limit": []string{"60"},
|
|
|
|
|
|
},
|
|
|
|
|
|
Body: io.NopCloser(strings.NewReader(`{"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":2}}`)),
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
usage, err := svc.handleNativeNonStreamingResponse(c, resp, false)
|
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
require.NotNil(t, usage)
|
|
|
|
|
|
require.False(t, logSink.ContainsMessage("[GeminiAPI]"), "debug 关闭时不应输出 Gemini 响应头日志")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-03 06:01:29 +08:00
|
|
|
|
func TestConvertClaudeMessagesToGeminiGenerateContent_AddsThoughtSignatureForToolUse(t *testing.T) {
|
|
|
|
|
|
claudeReq := map[string]any{
|
|
|
|
|
|
"model": "claude-haiku-4-5-20251001",
|
|
|
|
|
|
"max_tokens": 10,
|
|
|
|
|
|
"messages": []any{
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"role": "user",
|
|
|
|
|
|
"content": []any{
|
|
|
|
|
|
map[string]any{"type": "text", "text": "hi"},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"role": "assistant",
|
|
|
|
|
|
"content": []any{
|
|
|
|
|
|
map[string]any{"type": "text", "text": "ok"},
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"type": "tool_use",
|
|
|
|
|
|
"id": "toolu_123",
|
|
|
|
|
|
"name": "default_api:write_file",
|
|
|
|
|
|
"input": map[string]any{"path": "a.txt", "content": "x"},
|
|
|
|
|
|
// no signature on purpose
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
"tools": []any{
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"name": "default_api:write_file",
|
|
|
|
|
|
"description": "write file",
|
|
|
|
|
|
"input_schema": map[string]any{
|
|
|
|
|
|
"type": "object",
|
|
|
|
|
|
"properties": map[string]any{"path": map[string]any{"type": "string"}},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
b, _ := json.Marshal(claudeReq)
|
|
|
|
|
|
|
|
|
|
|
|
out, err := convertClaudeMessagesToGeminiGenerateContent(b)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
t.Fatalf("convert failed: %v", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
s := string(out)
|
|
|
|
|
|
if !strings.Contains(s, "\"functionCall\"") {
|
|
|
|
|
|
t.Fatalf("expected functionCall in output, got: %s", s)
|
|
|
|
|
|
}
|
|
|
|
|
|
if !strings.Contains(s, "\"thoughtSignature\":\""+geminiDummyThoughtSignature+"\"") {
|
|
|
|
|
|
t.Fatalf("expected injected thoughtSignature %q, got: %s", geminiDummyThoughtSignature, s)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func TestEnsureGeminiFunctionCallThoughtSignatures_InsertsWhenMissing(t *testing.T) {
|
|
|
|
|
|
geminiReq := map[string]any{
|
|
|
|
|
|
"contents": []any{
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"role": "user",
|
|
|
|
|
|
"parts": []any{
|
|
|
|
|
|
map[string]any{
|
|
|
|
|
|
"functionCall": map[string]any{
|
|
|
|
|
|
"name": "default_api:write_file",
|
|
|
|
|
|
"args": map[string]any{"path": "a.txt"},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
b, _ := json.Marshal(geminiReq)
|
|
|
|
|
|
out := ensureGeminiFunctionCallThoughtSignatures(b)
|
|
|
|
|
|
s := string(out)
|
|
|
|
|
|
if !strings.Contains(s, "\"thoughtSignature\":\""+geminiDummyThoughtSignature+"\"") {
|
|
|
|
|
|
t.Fatalf("expected injected thoughtSignature %q, got: %s", geminiDummyThoughtSignature, s)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-02-10 08:59:30 +08:00
|
|
|
|
|
|
|
|
|
|
// TestUnwrapGeminiResponse 测试 unwrapGeminiResponse 的各种输入场景
|
|
|
|
|
|
// 关键区别:只有 response 为 JSON 对象/数组时才解包
|
|
|
|
|
|
func TestUnwrapGeminiResponse(t *testing.T) {
|
|
|
|
|
|
// 构造 >50KB 的大型 JSON 对象
|
|
|
|
|
|
largePadding := strings.Repeat("x", 50*1024)
|
|
|
|
|
|
largeInput := []byte(fmt.Sprintf(`{"response":{"id":"big","pad":"%s"}}`, largePadding))
|
|
|
|
|
|
largeExpected := fmt.Sprintf(`{"id":"big","pad":"%s"}`, largePadding)
|
|
|
|
|
|
|
|
|
|
|
|
tests := []struct {
|
|
|
|
|
|
name string
|
|
|
|
|
|
input []byte
|
|
|
|
|
|
expected string
|
|
|
|
|
|
wantErr bool
|
|
|
|
|
|
}{
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "正常 response 包装(JSON 对象)",
|
|
|
|
|
|
input: []byte(`{"response":{"key":"val"}}`),
|
|
|
|
|
|
expected: `{"key":"val"}`,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "无包装直接返回",
|
|
|
|
|
|
input: []byte(`{"key":"val"}`),
|
|
|
|
|
|
expected: `{"key":"val"}`,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "空 JSON",
|
|
|
|
|
|
input: []byte(`{}`),
|
|
|
|
|
|
expected: `{}`,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "null response 返回原始 body",
|
|
|
|
|
|
input: []byte(`{"response":null}`),
|
|
|
|
|
|
expected: `{"response":null}`,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "非法 JSON 返回原始 body",
|
|
|
|
|
|
input: []byte(`not json`),
|
|
|
|
|
|
expected: `not json`,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "response 为基础类型 string 返回原始 body",
|
|
|
|
|
|
input: []byte(`{"response":"hello"}`),
|
|
|
|
|
|
expected: `{"response":"hello"}`,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "嵌套 response 只解一层",
|
|
|
|
|
|
input: []byte(`{"response":{"response":{"inner":true}}}`),
|
|
|
|
|
|
expected: `{"response":{"inner":true}}`,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "大型 JSON >50KB",
|
|
|
|
|
|
input: largeInput,
|
|
|
|
|
|
expected: largeExpected,
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for _, tt := range tests {
|
|
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
|
|
|
|
got, err := unwrapGeminiResponse(tt.input)
|
|
|
|
|
|
if tt.wantErr {
|
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
require.Equal(t, tt.expected, strings.TrimSpace(string(got)))
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Task 8.1 — extractGeminiUsage 测试
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
func TestExtractGeminiUsage(t *testing.T) {
|
|
|
|
|
|
tests := []struct {
|
|
|
|
|
|
name string
|
|
|
|
|
|
input string
|
|
|
|
|
|
wantNil bool
|
|
|
|
|
|
wantUsage *ClaudeUsage
|
|
|
|
|
|
}{
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "完整 usageMetadata",
|
|
|
|
|
|
input: `{"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"cachedContentTokenCount":20}}`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
wantUsage: &ClaudeUsage{
|
|
|
|
|
|
InputTokens: 80,
|
|
|
|
|
|
OutputTokens: 50,
|
|
|
|
|
|
CacheReadInputTokens: 20,
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
2026-02-11 15:41:54 +08:00
|
|
|
|
{
|
2026-02-12 23:43:47 +08:00
|
|
|
|
name: "包含 thoughtsTokenCount",
|
|
|
|
|
|
input: `{"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":20,"thoughtsTokenCount":50}}`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
wantUsage: &ClaudeUsage{
|
|
|
|
|
|
InputTokens: 100,
|
|
|
|
|
|
OutputTokens: 70,
|
|
|
|
|
|
CacheReadInputTokens: 0,
|
2026-02-11 15:41:54 +08:00
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
2026-02-12 23:43:47 +08:00
|
|
|
|
name: "包含 thoughtsTokenCount 与缓存",
|
|
|
|
|
|
input: `{"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":20,"cachedContentTokenCount":30,"thoughtsTokenCount":50}}`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
wantUsage: &ClaudeUsage{
|
|
|
|
|
|
InputTokens: 70,
|
|
|
|
|
|
OutputTokens: 70,
|
|
|
|
|
|
CacheReadInputTokens: 30,
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
2026-02-10 08:59:30 +08:00
|
|
|
|
{
|
|
|
|
|
|
name: "缺失 cachedContentTokenCount",
|
|
|
|
|
|
input: `{"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50}}`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
wantUsage: &ClaudeUsage{
|
|
|
|
|
|
InputTokens: 100,
|
|
|
|
|
|
OutputTokens: 50,
|
|
|
|
|
|
CacheReadInputTokens: 0,
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "无 usageMetadata",
|
|
|
|
|
|
input: `{"candidates":[]}`,
|
|
|
|
|
|
wantNil: true,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
// gjson 对 null 返回 Exists()=true,因此函数不会返回 nil,
|
|
|
|
|
|
// 而是返回全零的 ClaudeUsage。
|
|
|
|
|
|
name: "null usageMetadata — gjson Exists 为 true",
|
|
|
|
|
|
input: `{"usageMetadata":null}`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
wantUsage: &ClaudeUsage{
|
|
|
|
|
|
InputTokens: 0,
|
|
|
|
|
|
OutputTokens: 0,
|
|
|
|
|
|
CacheReadInputTokens: 0,
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "零值字段",
|
|
|
|
|
|
input: `{"usageMetadata":{"promptTokenCount":0,"candidatesTokenCount":0,"cachedContentTokenCount":0}}`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
wantUsage: &ClaudeUsage{
|
|
|
|
|
|
InputTokens: 0,
|
|
|
|
|
|
OutputTokens: 0,
|
|
|
|
|
|
CacheReadInputTokens: 0,
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for _, tt := range tests {
|
|
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
|
|
|
|
got := extractGeminiUsage([]byte(tt.input))
|
|
|
|
|
|
if tt.wantNil {
|
|
|
|
|
|
if got != nil {
|
|
|
|
|
|
t.Fatalf("期望返回 nil,实际返回 %+v", got)
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if got == nil {
|
|
|
|
|
|
t.Fatalf("期望返回非 nil,实际返回 nil")
|
|
|
|
|
|
}
|
|
|
|
|
|
if got.InputTokens != tt.wantUsage.InputTokens {
|
|
|
|
|
|
t.Errorf("InputTokens: 期望 %d,实际 %d", tt.wantUsage.InputTokens, got.InputTokens)
|
|
|
|
|
|
}
|
|
|
|
|
|
if got.OutputTokens != tt.wantUsage.OutputTokens {
|
|
|
|
|
|
t.Errorf("OutputTokens: 期望 %d,实际 %d", tt.wantUsage.OutputTokens, got.OutputTokens)
|
|
|
|
|
|
}
|
|
|
|
|
|
if got.CacheReadInputTokens != tt.wantUsage.CacheReadInputTokens {
|
|
|
|
|
|
t.Errorf("CacheReadInputTokens: 期望 %d,实际 %d", tt.wantUsage.CacheReadInputTokens, got.CacheReadInputTokens)
|
|
|
|
|
|
}
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Task 8.2 — estimateGeminiCountTokens 测试
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
func TestEstimateGeminiCountTokens(t *testing.T) {
|
|
|
|
|
|
tests := []struct {
|
|
|
|
|
|
name string
|
|
|
|
|
|
input string
|
|
|
|
|
|
wantGt0 bool // 期望结果 > 0
|
|
|
|
|
|
wantExact *int // 如果非 nil,期望精确匹配
|
|
|
|
|
|
}{
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "含 systemInstruction 和 contents",
|
|
|
|
|
|
input: `{
|
|
|
|
|
|
"systemInstruction":{"parts":[{"text":"You are a helpful assistant."}]},
|
|
|
|
|
|
"contents":[{"parts":[{"text":"Hello, how are you?"}]}]
|
|
|
|
|
|
}`,
|
|
|
|
|
|
wantGt0: true,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "仅 contents,无 systemInstruction",
|
|
|
|
|
|
input: `{
|
|
|
|
|
|
"contents":[{"parts":[{"text":"Hello, how are you?"}]}]
|
|
|
|
|
|
}`,
|
|
|
|
|
|
wantGt0: true,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "空 parts",
|
|
|
|
|
|
input: `{"contents":[{"parts":[]}]}`,
|
|
|
|
|
|
wantGt0: false,
|
|
|
|
|
|
wantExact: intPtr(0),
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "非文本 parts(inlineData)",
|
|
|
|
|
|
input: `{"contents":[{"parts":[{"inlineData":{"mimeType":"image/png"}}]}]}`,
|
|
|
|
|
|
wantGt0: false,
|
|
|
|
|
|
wantExact: intPtr(0),
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "空白文本",
|
|
|
|
|
|
input: `{"contents":[{"parts":[{"text":" "}]}]}`,
|
|
|
|
|
|
wantGt0: false,
|
|
|
|
|
|
wantExact: intPtr(0),
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for _, tt := range tests {
|
|
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
|
|
|
|
got := estimateGeminiCountTokens([]byte(tt.input))
|
|
|
|
|
|
if tt.wantExact != nil {
|
|
|
|
|
|
if got != *tt.wantExact {
|
|
|
|
|
|
t.Errorf("期望精确值 %d,实际 %d", *tt.wantExact, got)
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if tt.wantGt0 && got <= 0 {
|
|
|
|
|
|
t.Errorf("期望返回 > 0,实际 %d", got)
|
|
|
|
|
|
}
|
|
|
|
|
|
if !tt.wantGt0 && got != 0 {
|
|
|
|
|
|
t.Errorf("期望返回 0,实际 %d", got)
|
|
|
|
|
|
}
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Task 8.3 — ParseGeminiRateLimitResetTime 测试
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
func TestParseGeminiRateLimitResetTime(t *testing.T) {
|
|
|
|
|
|
tests := []struct {
|
|
|
|
|
|
name string
|
|
|
|
|
|
input string
|
|
|
|
|
|
wantNil bool
|
|
|
|
|
|
approxDelta int64 // 预期的 (返回值 - now) 大约是多少秒
|
|
|
|
|
|
}{
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "正常 quotaResetDelay",
|
|
|
|
|
|
input: `{"error":{"details":[{"metadata":{"quotaResetDelay":"12.345s"}}]}}`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
approxDelta: 13, // 向上取整 12.345 -> 13
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "daily quota",
|
|
|
|
|
|
input: `{"error":{"message":"quota per day exceeded"}}`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
approxDelta: -1, // 不检查精确 delta,仅检查非 nil
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "无 details 且无 regex 匹配",
|
|
|
|
|
|
input: `{"error":{"message":"rate limit"}}`,
|
|
|
|
|
|
wantNil: true,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "regex 回退匹配",
|
|
|
|
|
|
input: `Please retry in 30s`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
approxDelta: 30,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "完全无匹配",
|
|
|
|
|
|
input: `{"error":{"code":429}}`,
|
|
|
|
|
|
wantNil: true,
|
|
|
|
|
|
},
|
|
|
|
|
|
{
|
|
|
|
|
|
name: "非法 JSON 但 regex 回退仍工作",
|
|
|
|
|
|
input: `not json but Please retry in 10s`,
|
|
|
|
|
|
wantNil: false,
|
|
|
|
|
|
approxDelta: 10,
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for _, tt := range tests {
|
|
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
|
|
|
|
now := time.Now().Unix()
|
|
|
|
|
|
got := ParseGeminiRateLimitResetTime([]byte(tt.input))
|
|
|
|
|
|
|
|
|
|
|
|
if tt.wantNil {
|
|
|
|
|
|
if got != nil {
|
|
|
|
|
|
t.Fatalf("期望返回 nil,实际返回 %d", *got)
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if got == nil {
|
|
|
|
|
|
t.Fatalf("期望返回非 nil,实际返回 nil")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// approxDelta == -1 表示只检查非 nil,不检查具体值(如 daily quota 场景)
|
|
|
|
|
|
if tt.approxDelta == -1 {
|
|
|
|
|
|
// 仅验证返回的时间戳在合理范围内(未来的某个时间)
|
|
|
|
|
|
if *got < now {
|
|
|
|
|
|
t.Errorf("期望返回的时间戳 >= now(%d),实际 %d", now, *got)
|
|
|
|
|
|
}
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 使用 +/-2 秒容差进行范围检查
|
|
|
|
|
|
delta := *got - now
|
|
|
|
|
|
if delta < tt.approxDelta-2 || delta > tt.approxDelta+2 {
|
|
|
|
|
|
t.Errorf("期望 delta 约为 %d 秒(+/-2),实际 delta = %d 秒(返回值=%d, now=%d)",
|
|
|
|
|
|
tt.approxDelta, delta, *got, now)
|
|
|
|
|
|
}
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|