diff --git a/backend/internal/service/account_test_service_gemini_test.go b/backend/internal/service/account_test_service_gemini_test.go index f38264a2..1504b4ac 100644 --- a/backend/internal/service/account_test_service_gemini_test.go +++ b/backend/internal/service/account_test_service_gemini_test.go @@ -4,11 +4,9 @@ package service import ( "encoding/json" + "github.com/stretchr/testify/require" "strings" "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/require" ) func TestCreateGeminiTestPayload_ImageModel(t *testing.T) { @@ -40,7 +38,6 @@ func TestCreateGeminiTestPayload_ImageModel(t *testing.T) { func TestProcessGeminiStream_EmitsImageEvent(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) ctx, recorder := newTestContext() svc := &AccountTestService{} diff --git a/backend/internal/service/account_test_service_openai_compact_test.go b/backend/internal/service/account_test_service_openai_compact_test.go index 9eb98fdc..795706d9 100644 --- a/backend/internal/service/account_test_service_openai_compact_test.go +++ b/backend/internal/service/account_test_service_openai_compact_test.go @@ -15,7 +15,6 @@ import ( ) func TestAccountTestService_TestAccountConnection_OpenAICompactOAuthSuccessPersistsSupport(t *testing.T) { - gin.SetMode(gin.TestMode) updateCalls := make(chan map[string]any, 1) account := Account{ @@ -68,7 +67,6 @@ func TestAccountTestService_TestAccountConnection_OpenAICompactOAuthSuccessPersi } func TestAccountTestService_TestAccountConnection_OpenAICompactOAuth404MarksUnsupported(t *testing.T) { - gin.SetMode(gin.TestMode) updateCalls := make(chan map[string]any, 1) account := Account{ @@ -112,7 +110,6 @@ func TestAccountTestService_TestAccountConnection_OpenAICompactOAuth404MarksUnsu } func TestAccountTestService_TestAccountConnection_OpenAICompactAPIKeyUsesCompactPath(t *testing.T) { - gin.SetMode(gin.TestMode) updateCalls := make(chan map[string]any, 1) account := Account{ @@ -158,7 +155,6 @@ func TestAccountTestService_TestAccountConnection_OpenAICompactAPIKeyUsesCompact } func TestAccountTestService_TestAccountConnection_OpenAICompactAPIKeyDefaultBaseURLUsesV1Path(t *testing.T) { - gin.SetMode(gin.TestMode) updateCalls := make(chan map[string]any, 1) account := Account{ diff --git a/backend/internal/service/account_test_service_openai_image_test.go b/backend/internal/service/account_test_service_openai_image_test.go index 257159c4..7ea4ac86 100644 --- a/backend/internal/service/account_test_service_openai_image_test.go +++ b/backend/internal/service/account_test_service_openai_image_test.go @@ -14,7 +14,6 @@ import ( ) func TestAccountTestService_OpenAIImageOAuthHandlesOutputItemDoneFallback(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/1/test", nil) @@ -51,7 +50,6 @@ func TestAccountTestService_OpenAIImageOAuthHandlesOutputItemDoneFallback(t *tes } func TestAccountTestService_OpenAIImageAPIKeyUsesConfiguredV1BaseURL(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/1/test", nil) diff --git a/backend/internal/service/account_test_service_openai_test.go b/backend/internal/service/account_test_service_openai_test.go index c6e30ed6..677ab739 100644 --- a/backend/internal/service/account_test_service_openai_test.go +++ b/backend/internal/service/account_test_service_openai_test.go @@ -52,7 +52,6 @@ func newJSONResponse(status int, body string) *http.Response { // --- test functions --- func newTestContext() (*gin.Context, *httptest.ResponseRecorder) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/1/test", nil) @@ -100,7 +99,6 @@ func (r *openAIAccountTestRepo) SetError(_ context.Context, id int64, errorMsg s } func TestAccountTestService_OpenAISuccessPersistsSnapshotFromHeaders(t *testing.T) { - gin.SetMode(gin.TestMode) ctx, recorder := newTestContext() resp := newJSONResponse(http.StatusOK, "") @@ -134,7 +132,6 @@ func TestAccountTestService_OpenAISuccessPersistsSnapshotFromHeaders(t *testing. } func TestAccountTestService_OpenAIStreamEOFBeforeCompletedFails(t *testing.T) { - gin.SetMode(gin.TestMode) ctx, recorder := newTestContext() resp := newJSONResponse(http.StatusOK, "") @@ -159,7 +156,6 @@ func TestAccountTestService_OpenAIStreamEOFBeforeCompletedFails(t *testing.T) { } func TestAccountTestService_OpenAI429PersistsSnapshotAndRateLimitState(t *testing.T) { - gin.SetMode(gin.TestMode) ctx, _ := newTestContext() resp := newJSONResponse(http.StatusTooManyRequests, `{"error":{"type":"usage_limit_reached","message":"limit reached","resets_at":1777283883}}`) @@ -195,7 +191,6 @@ func TestAccountTestService_OpenAI429PersistsSnapshotAndRateLimitState(t *testin } func TestAccountTestService_OpenAI429BodyOnlyPersistsRateLimitAndClearsStaleError(t *testing.T) { - gin.SetMode(gin.TestMode) ctx, _ := newTestContext() resp := newJSONResponse(http.StatusTooManyRequests, `{"error":{"type":"usage_limit_reached","message":"limit reached","resets_at":"1777283883"}}`) @@ -225,7 +220,6 @@ func TestAccountTestService_OpenAI429BodyOnlyPersistsRateLimitAndClearsStaleErro } func TestAccountTestService_OpenAI429SyncsObservedPlanType(t *testing.T) { - gin.SetMode(gin.TestMode) ctx, _ := newTestContext() resp := newJSONResponse(http.StatusTooManyRequests, `{"error":{"type":"usage_limit_reached","message":"limit reached","plan_type":"free","resets_at":1777283883}}`) @@ -252,7 +246,6 @@ func TestAccountTestService_OpenAI429SyncsObservedPlanType(t *testing.T) { } func TestAccountTestService_OpenAI429ActiveAccountDoesNotClearError(t *testing.T) { - gin.SetMode(gin.TestMode) ctx, _ := newTestContext() resp := newJSONResponse(http.StatusTooManyRequests, `{"error":{"type":"usage_limit_reached","message":"limit reached","resets_in_seconds":3600}}`) @@ -279,7 +272,6 @@ func TestAccountTestService_OpenAI429ActiveAccountDoesNotClearError(t *testing.T } func TestAccountTestService_OpenAI429WithoutResetSignalDoesNotMutateRuntimeState(t *testing.T) { - gin.SetMode(gin.TestMode) ctx, _ := newTestContext() resp := newJSONResponse(http.StatusTooManyRequests, `{"error":{"type":"usage_limit_reached","message":"limit reached"}}`) @@ -308,7 +300,6 @@ func TestAccountTestService_OpenAI429WithoutResetSignalDoesNotMutateRuntimeState } func TestAccountTestService_OpenAI401SetsPermanentErrorOnly(t *testing.T) { - gin.SetMode(gin.TestMode) ctx, _ := newTestContext() resp := newJSONResponse(http.StatusUnauthorized, `{"error":"bad token"}`) diff --git a/backend/internal/service/antigravity_gateway_service_test.go b/backend/internal/service/antigravity_gateway_service_test.go index 1eb1451e..2a28cf66 100644 --- a/backend/internal/service/antigravity_gateway_service_test.go +++ b/backend/internal/service/antigravity_gateway_service_test.go @@ -207,7 +207,6 @@ func (s *antigravitySettingRepoStub) Delete(ctx context.Context, key string) err } func TestAntigravityGatewayService_Forward_PromptTooLong(t *testing.T) { - gin.SetMode(gin.TestMode) writer := httptest.NewRecorder() c, _ := gin.CreateTestContext(writer) @@ -270,7 +269,6 @@ func TestAntigravityGatewayService_Forward_PromptTooLong(t *testing.T) { // 验证:当账号存在模型限流且剩余时间 >= antigravityRateLimitThreshold 时, // Forward 方法应返回 UpstreamFailoverError,触发 Handler 切换账号 func TestAntigravityGatewayService_Forward_ModelRateLimitTriggersFailover(t *testing.T) { - gin.SetMode(gin.TestMode) writer := httptest.NewRecorder() c, _ := gin.CreateTestContext(writer) @@ -329,7 +327,6 @@ func TestAntigravityGatewayService_Forward_ModelRateLimitTriggersFailover(t *tes // TestAntigravityGatewayService_ForwardGemini_ModelRateLimitTriggersFailover // 验证:ForwardGemini 方法同样能正确将 AntigravityAccountSwitchError 转换为 UpstreamFailoverError func TestAntigravityGatewayService_ForwardGemini_ModelRateLimitTriggersFailover(t *testing.T) { - gin.SetMode(gin.TestMode) writer := httptest.NewRecorder() c, _ := gin.CreateTestContext(writer) @@ -385,7 +382,6 @@ func TestAntigravityGatewayService_ForwardGemini_ModelRateLimitTriggersFailover( // TestAntigravityGatewayService_Forward_StickySessionForceCacheBilling // 验证:粘性会话切换时,UpstreamFailoverError.ForceCacheBilling 应为 true func TestAntigravityGatewayService_Forward_StickySessionForceCacheBilling(t *testing.T) { - gin.SetMode(gin.TestMode) writer := httptest.NewRecorder() c, _ := gin.CreateTestContext(writer) @@ -439,7 +435,6 @@ func TestAntigravityGatewayService_Forward_StickySessionForceCacheBilling(t *tes // TestAntigravityGatewayService_ForwardGemini_StickySessionForceCacheBilling verifies // that ForwardGemini sets ForceCacheBilling=true for sticky session switch. func TestAntigravityGatewayService_ForwardGemini_StickySessionForceCacheBilling(t *testing.T) { - gin.SetMode(gin.TestMode) writer := httptest.NewRecorder() c, _ := gin.CreateTestContext(writer) @@ -494,7 +489,6 @@ func TestAntigravityGatewayService_ForwardGemini_StickySessionForceCacheBilling( // TestAntigravityGatewayService_Forward_BillsWithMappedModel // 验证:Antigravity Claude 转发返回的计费模型使用映射后的模型 func TestAntigravityGatewayService_Forward_BillsWithMappedModel(t *testing.T) { - gin.SetMode(gin.TestMode) writer := httptest.NewRecorder() c, _ := gin.CreateTestContext(writer) @@ -550,7 +544,6 @@ func TestAntigravityGatewayService_Forward_BillsWithMappedModel(t *testing.T) { // TestAntigravityGatewayService_ForwardGemini_BillsWithMappedModel // 验证:Antigravity Gemini 转发返回的计费模型使用映射后的模型 func TestAntigravityGatewayService_ForwardGemini_BillsWithMappedModel(t *testing.T) { - gin.SetMode(gin.TestMode) writer := httptest.NewRecorder() c, _ := gin.CreateTestContext(writer) @@ -601,7 +594,6 @@ func TestAntigravityGatewayService_ForwardGemini_BillsWithMappedModel(t *testing } func TestAntigravityGatewayService_ForwardGemini_RetriesCorruptedThoughtSignature(t *testing.T) { - gin.SetMode(gin.TestMode) writer := httptest.NewRecorder() c, _ := gin.CreateTestContext(writer) @@ -688,7 +680,6 @@ func TestAntigravityGatewayService_ForwardGemini_RetriesCorruptedThoughtSignatur } func TestAntigravityGatewayService_ForwardGemini_SignatureRetryPropagatesFailover(t *testing.T) { - gin.SetMode(gin.TestMode) writer := httptest.NewRecorder() c, _ := gin.CreateTestContext(writer) @@ -775,7 +766,6 @@ func TestAntigravityGatewayService_ForwardGemini_SignatureRetryPropagatesFailove // TestStreamUpstreamResponse_UsageAndFirstToken // 验证:usage 字段可被累积/覆盖更新,并且能记录首 token 时间 func TestStreamUpstreamResponse_UsageAndFirstToken(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -815,7 +805,6 @@ func TestStreamUpstreamResponse_UsageAndFirstToken(t *testing.T) { // TestStreamUpstreamResponse_NormalComplete // 验证:正常流式转发完成时,数据正确透传、usage 正确收集、clientDisconnect=false func TestStreamUpstreamResponse_NormalComplete(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -859,7 +848,6 @@ func TestStreamUpstreamResponse_NormalComplete(t *testing.T) { // TestHandleGeminiStreamingResponse_NormalComplete // 验证:正常 Gemini 流式转发,数据正确透传、usage 正确收集 func TestHandleGeminiStreamingResponse_NormalComplete(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -906,7 +894,6 @@ func TestHandleGeminiStreamingResponse_NormalComplete(t *testing.T) { // TestHandleClaudeStreamingResponse_NormalComplete // 验证:正常 Claude 流式转发(Gemini→Claude 转换),数据正确转换并输出 func TestHandleClaudeStreamingResponse_NormalComplete(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -949,7 +936,6 @@ func TestHandleClaudeStreamingResponse_NormalComplete(t *testing.T) { // TestHandleGeminiStreamingResponse_ThoughtsTokenCount // 验证:Gemini 流式转发时 thoughtsTokenCount 被计入 OutputTokens func TestHandleGeminiStreamingResponse_ThoughtsTokenCount(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -985,7 +971,6 @@ func TestHandleGeminiStreamingResponse_ThoughtsTokenCount(t *testing.T) { // TestHandleClaudeStreamingResponse_ThoughtsTokenCount // 验证:Gemini→Claude 流式转换时 thoughtsTokenCount 被计入 OutputTokens func TestHandleClaudeStreamingResponse_ThoughtsTokenCount(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -1020,7 +1005,6 @@ func TestHandleClaudeStreamingResponse_ThoughtsTokenCount(t *testing.T) { // TestStreamUpstreamResponse_ClientDisconnectDrainsUsage // 验证:客户端写入失败后,streamUpstreamResponse 继续读取上游以收集 usage func TestStreamUpstreamResponse_ClientDisconnectDrainsUsage(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -1055,7 +1039,6 @@ func TestStreamUpstreamResponse_ClientDisconnectDrainsUsage(t *testing.T) { // TestStreamUpstreamResponse_ContextCanceled // 验证:context 取消时返回 usage 且标记 clientDisconnect func TestStreamUpstreamResponse_ContextCanceled(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -1078,7 +1061,6 @@ func TestStreamUpstreamResponse_ContextCanceled(t *testing.T) { // TestStreamUpstreamResponse_Timeout // 验证:上游超时时返回已收集的 usage func TestStreamUpstreamResponse_Timeout(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{StreamDataIntervalTimeout: 1, MaxLineSize: defaultMaxLineSize}, }) @@ -1101,7 +1083,6 @@ func TestStreamUpstreamResponse_Timeout(t *testing.T) { // TestStreamUpstreamResponse_TimeoutAfterClientDisconnect // 验证:客户端断开后上游超时,返回 usage 并标记 clientDisconnect func TestStreamUpstreamResponse_TimeoutAfterClientDisconnect(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{StreamDataIntervalTimeout: 1, MaxLineSize: defaultMaxLineSize}, }) @@ -1131,7 +1112,6 @@ func TestStreamUpstreamResponse_TimeoutAfterClientDisconnect(t *testing.T) { // TestHandleGeminiStreamingResponse_ClientDisconnect // 验证:Gemini 流式转发中客户端断开后继续 drain 上游 func TestHandleGeminiStreamingResponse_ClientDisconnect(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -1162,7 +1142,6 @@ func TestHandleGeminiStreamingResponse_ClientDisconnect(t *testing.T) { // TestHandleGeminiStreamingResponse_ContextCanceled // 验证:context 取消时不注入错误事件 func TestHandleGeminiStreamingResponse_ContextCanceled(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -1186,7 +1165,6 @@ func TestHandleGeminiStreamingResponse_ContextCanceled(t *testing.T) { // TestHandleClaudeStreamingResponse_ClientDisconnect // 验证:Claude 流式转发中客户端断开后继续 drain 上游 func TestHandleClaudeStreamingResponse_ClientDisconnect(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -1217,7 +1195,6 @@ func TestHandleClaudeStreamingResponse_ClientDisconnect(t *testing.T) { // TestHandleClaudeStreamingResponse_EmptyStream // 验证:上游只返回无法解析的 SSE 行时,触发 UpstreamFailoverError 而不是向客户端发出残缺流 func TestHandleClaudeStreamingResponse_EmptyStream(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -1257,7 +1234,6 @@ func TestHandleClaudeStreamingResponse_EmptyStream(t *testing.T) { // TestHandleClaudeStreamingResponse_ContextCanceled // 验证:context 取消时不注入错误事件 func TestHandleClaudeStreamingResponse_ContextCanceled(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newAntigravityTestService(&config.Config{ Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, }) @@ -1314,7 +1290,6 @@ func TestExtractSSEUsage(t *testing.T) { // TestAntigravityClientWriter 验证 antigravityClientWriter 的断开检测 func TestAntigravityClientWriter(t *testing.T) { t.Run("normal write succeeds", func(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) flusher, _ := c.Writer.(http.Flusher) @@ -1327,7 +1302,6 @@ func TestAntigravityClientWriter(t *testing.T) { }) t.Run("write failure marks disconnected", func(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) fw := &antigravityFailingWriter{ResponseWriter: c.Writer, failAfter: 0} @@ -1340,7 +1314,6 @@ func TestAntigravityClientWriter(t *testing.T) { }) t.Run("subsequent writes are no-op", func(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) fw := &antigravityFailingWriter{ResponseWriter: c.Writer, failAfter: 0} diff --git a/backend/internal/service/error_passthrough_runtime_test.go b/backend/internal/service/error_passthrough_runtime_test.go index 7032d15b..0500b130 100644 --- a/backend/internal/service/error_passthrough_runtime_test.go +++ b/backend/internal/service/error_passthrough_runtime_test.go @@ -16,7 +16,6 @@ import ( ) func TestApplyErrorPassthroughRule_NoBoundService(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -37,7 +36,6 @@ func TestApplyErrorPassthroughRule_NoBoundService(t *testing.T) { } func TestGatewayHandleErrorResponse_NoRuleKeepsDefault(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -63,7 +61,6 @@ func TestGatewayHandleErrorResponse_NoRuleKeepsDefault(t *testing.T) { } func TestOpenAIHandleErrorResponse_NoRuleKeepsDefault(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -89,7 +86,6 @@ func TestOpenAIHandleErrorResponse_NoRuleKeepsDefault(t *testing.T) { } func TestGeminiWriteGeminiMappedError_NoRuleKeepsDefault(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -110,7 +106,6 @@ func TestGeminiWriteGeminiMappedError_NoRuleKeepsDefault(t *testing.T) { } func TestGatewayHandleErrorResponse_AppliesRuleFor422(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -140,7 +135,6 @@ func TestGatewayHandleErrorResponse_AppliesRuleFor422(t *testing.T) { } func TestOpenAIHandleErrorResponse_AppliesRuleFor422(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -170,7 +164,6 @@ func TestOpenAIHandleErrorResponse_AppliesRuleFor422(t *testing.T) { } func TestGeminiWriteGeminiMappedError_AppliesRuleFor422(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -195,7 +188,6 @@ func TestGeminiWriteGeminiMappedError_AppliesRuleFor422(t *testing.T) { } func TestApplyErrorPassthroughRule_SkipMonitoringSetsContextKey(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -225,7 +217,6 @@ func TestApplyErrorPassthroughRule_SkipMonitoringSetsContextKey(t *testing.T) { } func TestApplyErrorPassthroughRule_NoSkipMonitoringDoesNotSetContextKey(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go b/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go index 428231ee..86839c8a 100644 --- a/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go +++ b/backend/internal/service/gateway_anthropic_apikey_passthrough_test.go @@ -98,7 +98,6 @@ func (w *failWriteResponseWriter) WriteString(_ string) (int, error) { } func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardStreamPreservesBodyAndAuthReplacement(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -196,7 +195,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardStreamPreservesBodyAnd } func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardCountTokensPreservesBody(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -268,7 +266,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardCountTokensPreservesBo // TestGatewayService_AnthropicAPIKeyPassthrough_ModelMappingEdgeCases 覆盖透传模式下模型映射的各种边界情况 func TestGatewayService_AnthropicAPIKeyPassthrough_ModelMappingEdgeCases(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string @@ -425,7 +422,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_ModelMappingEdgeCases(t *test // TestGatewayService_AnthropicAPIKeyPassthrough_ModelMappingPreservesOtherFields // 确保模型映射只替换 model 字段,不影响请求体中的其他字段 func TestGatewayService_AnthropicAPIKeyPassthrough_ModelMappingPreservesOtherFields(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -484,7 +480,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_ModelMappingPreservesOtherFie // TestGatewayService_AnthropicAPIKeyPassthrough_EmptyModelSkipsMapping // 确保空模型名不会触发映射逻辑 func TestGatewayService_AnthropicAPIKeyPassthrough_EmptyModelSkipsMapping(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -534,7 +529,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_EmptyModelSkipsMapping(t *tes } func TestGatewayService_AnthropicAPIKeyPassthrough_CountTokens404PassthroughNotError(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string @@ -635,7 +629,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_CountTokens404PassthroughNotE } func TestGatewayService_AnthropicAPIKeyPassthrough_BuildRequestRejectsInvalidBaseURL(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -663,7 +656,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_BuildRequestRejectsInvalidBas } func TestGatewayService_AnthropicOAuth_NotAffectedByAPIKeyPassthroughToggle(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -690,7 +682,6 @@ func TestGatewayService_AnthropicOAuth_NotAffectedByAPIKeyPassthroughToggle(t *t } func TestGatewayService_AnthropicOAuth_ForwardPreservesBillingHeaderSystemBlock(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string @@ -782,7 +773,6 @@ func TestGatewayService_AnthropicOAuth_ForwardPreservesBillingHeaderSystemBlock( } func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingStillCollectsUsageAfterClientDisconnect(t *testing.T) { - gin.SetMode(gin.TestMode) // Use a canceled context recorder to simulate client disconnect behavior. req := httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -825,7 +815,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingStillCollectsUsageAf } func TestGatewayService_AnthropicAPIKeyPassthrough_MissingTerminalEventReturnsError(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -858,7 +847,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_MissingTerminalEventReturnsEr } func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardDirect_NonStreamingSuccess(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -892,7 +880,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardDirect_NonStreamingSuc } func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardDirect_InvalidTokenType(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -915,7 +902,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardDirect_InvalidTokenTyp } func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardDirect_UpstreamRequestError(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -945,7 +931,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardDirect_UpstreamRequest } func TestGatewayService_AnthropicAPIKeyPassthrough_ForwardDirect_EmptyResponseBody(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -1078,7 +1063,6 @@ func TestParseClaudeUsageFromResponseBody(t *testing.T) { } func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingErrTooLong(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -1106,7 +1090,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingErrTooLong(t *testin } func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingDataIntervalTimeout(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -1139,7 +1122,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingDataIntervalTimeout( } func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingReadError(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -1168,7 +1150,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingReadError(t *testing } func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingTimeoutAfterClientDisconnect(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -1212,7 +1193,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingTimeoutAfterClientDi } func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingContextCanceled(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -1241,7 +1221,6 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingContextCanceled(t *t } func TestGatewayService_AnthropicAPIKeyPassthrough_StreamingUpstreamReadErrorAfterClientDisconnect(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) diff --git a/backend/internal/service/gateway_anthropic_vertex_service_account_test.go b/backend/internal/service/gateway_anthropic_vertex_service_account_test.go index aa779805..c75cbf49 100644 --- a/backend/internal/service/gateway_anthropic_vertex_service_account_test.go +++ b/backend/internal/service/gateway_anthropic_vertex_service_account_test.go @@ -13,7 +13,6 @@ import ( ) func TestGatewayService_BuildAnthropicVertexServiceAccountRequest(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/gateway_forward_as_chat_completions_test.go b/backend/internal/service/gateway_forward_as_chat_completions_test.go index 5003e5b3..ce9a5e9a 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions_test.go +++ b/backend/internal/service/gateway_forward_as_chat_completions_test.go @@ -36,7 +36,6 @@ func TestExtractCCReasoningEffortFromBody(t *testing.T) { func TestHandleCCBufferedFromAnthropic_PreservesMessageStartCacheUsageAndReasoning(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -71,7 +70,6 @@ func TestHandleCCBufferedFromAnthropic_PreservesMessageStartCacheUsageAndReasoni func TestHandleCCStreamingFromAnthropic_PreservesMessageStartCacheUsageAndReasoning(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/gateway_forward_as_responses_test.go b/backend/internal/service/gateway_forward_as_responses_test.go index e48d8b22..811e05dd 100644 --- a/backend/internal/service/gateway_forward_as_responses_test.go +++ b/backend/internal/service/gateway_forward_as_responses_test.go @@ -26,7 +26,6 @@ func TestExtractResponsesReasoningEffortFromBody(t *testing.T) { func TestHandleResponsesBufferedStreamingResponse_PreservesMessageStartCacheUsage(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -59,7 +58,6 @@ func TestHandleResponsesBufferedStreamingResponse_PreservesMessageStartCacheUsag func TestHandleResponsesStreamingResponse_PreservesMessageStartCacheUsage(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/gateway_service_streaming_test.go b/backend/internal/service/gateway_service_streaming_test.go index 39a7d3b0..50a68993 100644 --- a/backend/internal/service/gateway_service_streaming_test.go +++ b/backend/internal/service/gateway_service_streaming_test.go @@ -16,7 +16,6 @@ import ( type upstreamContextTestKey string func TestGatewayService_StreamingReusesScannerBufferAndStillParsesUsage(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, diff --git a/backend/internal/service/gateway_streaming_test.go b/backend/internal/service/gateway_streaming_test.go index ef09a882..fd7a3102 100644 --- a/backend/internal/service/gateway_streaming_test.go +++ b/backend/internal/service/gateway_streaming_test.go @@ -138,7 +138,6 @@ func TestParseSSEUsage_DoneEvent(t *testing.T) { // --- 流式响应端到端测试 --- func TestHandleStreamingResponse_CacheTokens(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newMinimalGatewayService() rec := httptest.NewRecorder() @@ -167,7 +166,6 @@ func TestHandleStreamingResponse_CacheTokens(t *testing.T) { } func TestHandleStreamingResponse_EmptyStream(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newMinimalGatewayService() rec := httptest.NewRecorder() @@ -190,7 +188,6 @@ func TestHandleStreamingResponse_EmptyStream(t *testing.T) { } func TestHandleStreamingResponse_SpecialCharactersInJSON(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newMinimalGatewayService() rec := httptest.NewRecorder() @@ -225,7 +222,6 @@ func TestHandleStreamingResponse_SpecialCharactersInJSON(t *testing.T) { // 上游中途读错误(如 HTTP/2 GOAWAY 触发的 unexpected EOF)发生在向客户端写入任何字节前: // 网关应返回 *UpstreamFailoverError 触发账号 failover/重试,而不是把错误事件直接发给客户端。 func TestHandleStreamingResponse_StreamReadErrorBeforeOutput_TriggersFailover(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newMinimalGatewayService() rec := httptest.NewRecorder() @@ -264,7 +260,6 @@ func TestHandleStreamingResponse_StreamReadErrorBeforeOutput_TriggersFailover(t // 上游已经发送过事件(c.Writer 已写过字节)后再发生读错误: // SSE 协议无 resume,网关只能透传 stream_read_error 错误事件给客户端,不能 failover。 func TestHandleStreamingResponse_StreamReadErrorAfterOutput_PassesThrough(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newMinimalGatewayService() rec := httptest.NewRecorder() @@ -355,7 +350,6 @@ func TestSanitizeStreamError_KnownErrors(t *testing.T) { // failover ResponseBody 必须用 sanitize 过的消息,避免泄露给客户端 / 写入 ops 日志 // 时携带内部地址信息。 func TestHandleStreamingResponse_FailoverBodyDoesNotLeakAddresses(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newMinimalGatewayService() rec := httptest.NewRecorder() diff --git a/backend/internal/service/gemini_error_policy_test.go b/backend/internal/service/gemini_error_policy_test.go index 4bd1ced7..38977ed2 100644 --- a/backend/internal/service/gemini_error_policy_test.go +++ b/backend/internal/service/gemini_error_policy_test.go @@ -189,7 +189,6 @@ func TestCheckErrorPolicy_GeminiAccounts(t *testing.T) { // --------------------------------------------------------------------------- func TestGeminiErrorPolicyIntegration(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string diff --git a/backend/internal/service/gemini_messages_compat_service_test.go b/backend/internal/service/gemini_messages_compat_service_test.go index c2adf45d..680477f7 100644 --- a/backend/internal/service/gemini_messages_compat_service_test.go +++ b/backend/internal/service/gemini_messages_compat_service_test.go @@ -194,7 +194,6 @@ func TestConvertClaudeToolsToGeminiTools_PreservesWebSearchAlongsideFunctions(t } func TestGeminiHandleNativeNonStreamingResponse_DebugDisabledDoesNotEmitHeaderLogs(t *testing.T) { - gin.SetMode(gin.TestMode) logSink, restore := captureStructuredLog(t) defer restore() @@ -226,7 +225,6 @@ func TestGeminiHandleNativeNonStreamingResponse_DebugDisabledDoesNotEmitHeaderLo } func TestGeminiMessagesCompatServiceForward_PreservesRequestedModelAndMappedUpstreamModel(t *testing.T) { - gin.SetMode(gin.TestMode) w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) @@ -262,7 +260,6 @@ func TestGeminiMessagesCompatServiceForward_PreservesRequestedModelAndMappedUpst } func TestGeminiMessagesCompatServiceForward_NormalizesWebSearchToolForAIStudio(t *testing.T) { - gin.SetMode(gin.TestMode) w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) diff --git a/backend/internal/service/gin_test_setup_test.go b/backend/internal/service/gin_test_setup_test.go new file mode 100644 index 00000000..4a20bf4e --- /dev/null +++ b/backend/internal/service/gin_test_setup_test.go @@ -0,0 +1,7 @@ +package service + +import "github.com/gin-gonic/gin" + +func init() { + gin.SetMode(gin.TestMode) +} diff --git a/backend/internal/service/openai_client_restriction_detector_test.go b/backend/internal/service/openai_client_restriction_detector_test.go index 984b4ff6..d818cf0c 100644 --- a/backend/internal/service/openai_client_restriction_detector_test.go +++ b/backend/internal/service/openai_client_restriction_detector_test.go @@ -24,7 +24,6 @@ func newCodexDetectorTestContext(ua string, originator string) *gin.Context { } func TestOpenAICodexClientRestrictionDetector_Detect(t *testing.T) { - gin.SetMode(gin.TestMode) t.Run("未开启开关时绕过", func(t *testing.T) { detector := NewOpenAICodexClientRestrictionDetector(nil) diff --git a/backend/internal/service/openai_client_transport_test.go b/backend/internal/service/openai_client_transport_test.go index ef90e614..146950d8 100644 --- a/backend/internal/service/openai_client_transport_test.go +++ b/backend/internal/service/openai_client_transport_test.go @@ -9,7 +9,6 @@ import ( ) func TestOpenAIClientTransport_SetAndGet(t *testing.T) { - gin.SetMode(gin.TestMode) w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) @@ -23,7 +22,6 @@ func TestOpenAIClientTransport_SetAndGet(t *testing.T) { } func TestOpenAIClientTransport_GetNormalizesRawContextValue(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string @@ -76,7 +74,6 @@ func TestOpenAIClientTransport_NilAndUnknownInput(t *testing.T) { SetOpenAIClientTransport(nil, OpenAIClientTransportHTTP) require.Equal(t, OpenAIClientTransportUnknown, GetOpenAIClientTransport(nil)) - gin.SetMode(gin.TestMode) w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) diff --git a/backend/internal/service/openai_compact_model_mapping_test.go b/backend/internal/service/openai_compact_model_mapping_test.go index fc408e64..4b8c4025 100644 --- a/backend/internal/service/openai_compact_model_mapping_test.go +++ b/backend/internal/service/openai_compact_model_mapping_test.go @@ -15,7 +15,6 @@ import ( ) func TestOpenAIGatewayService_Forward_CompactOnlyModelMappingOverridesOAuthUpstreamModel(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -54,7 +53,6 @@ func TestOpenAIGatewayService_Forward_CompactOnlyModelMappingOverridesOAuthUpstr } func TestOpenAIGatewayService_Forward_NonCompactRequestIgnoresCompactOnlyModelMapping(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -93,7 +91,6 @@ func TestOpenAIGatewayService_Forward_NonCompactRequestIgnoresCompactOnlyModelMa } func TestOpenAIGatewayService_OAuthPassthrough_CompactOnlyModelMappingOverridesUpstreamModel(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/openai_compat_model_test.go b/backend/internal/service/openai_compat_model_test.go index e222b093..d6cd14c1 100644 --- a/backend/internal/service/openai_compat_model_test.go +++ b/backend/internal/service/openai_compat_model_test.go @@ -126,7 +126,6 @@ func TestApplyOpenAICompatModelNormalization(t *testing.T) { func TestForwardAsAnthropic_NormalizesRoutingAndEffortForGpt54XHigh(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -185,7 +184,6 @@ func TestForwardAsAnthropic_NormalizesRoutingAndEffortForGpt54XHigh(t *testing.T func TestForwardAsAnthropic_InjectsPromptCacheKeyForAPIKeyMessagesDispatch(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -231,7 +229,6 @@ func TestForwardAsAnthropic_InjectsPromptCacheKeyForAPIKeyMessagesDispatch(t *te func TestForwardAsAnthropic_AutoDerivesPromptCacheKeyWhenMessagesDispatchHasNoSessionID(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -278,7 +275,6 @@ func TestForwardAsAnthropic_AutoDerivesPromptCacheKeyWhenMessagesDispatchHasNoSe func TestForwardAsAnthropic_DoesNotAutoDerivePromptCacheKeyForNonCodexModel(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -323,7 +319,6 @@ func TestForwardAsAnthropic_DoesNotAutoDerivePromptCacheKeyForNonCodexModel(t *t func TestForwardAsAnthropic_TrimsFullReplayOnlyForCodexCompatModels(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) messages := make([]string, 0, openAICompatAnthropicReplayMaxTailMessages+3) for i := 0; i < openAICompatAnthropicReplayMaxTailMessages+3; i++ { @@ -387,7 +382,6 @@ func TestForwardAsAnthropic_TrimsFullReplayOnlyForCodexCompatModels(t *testing.T func TestForwardAsAnthropic_OAuthCompatKeepsFullReplayForCacheGrowth(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) messages := make([]string, 0, openAICompatAnthropicReplayMaxTailMessages+3) for i := 0; i < openAICompatAnthropicReplayMaxTailMessages+3; i++ { @@ -430,7 +424,6 @@ func TestForwardAsAnthropic_OAuthCompatKeepsFullReplayForCacheGrowth(t *testing. func TestForwardAsAnthropic_AttachesPreviousResponseIDForCompatContinuation(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{} svc := &OpenAIGatewayService{ @@ -482,7 +475,6 @@ func TestForwardAsAnthropic_AttachesPreviousResponseIDForCompatContinuation(t *t func TestForwardAsAnthropic_PreviousResponseIDKeepsMultiToolCallContext(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{} svc := &OpenAIGatewayService{ @@ -537,7 +529,6 @@ func TestForwardAsAnthropic_PreviousResponseIDKeepsMultiToolCallContext(t *testi func TestForwardAsAnthropic_ReplaysWithoutContinuationWhenPreviousResponseMissing(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{} svc := &OpenAIGatewayService{ @@ -588,7 +579,6 @@ func TestForwardAsAnthropic_ReplaysWithoutContinuationWhenPreviousResponseMissin func TestForwardAsAnthropic_DisablesAPIKeyContinuationWhenUpstreamRequiresWebSocketV2(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{} svc := &OpenAIGatewayService{ @@ -647,7 +637,6 @@ func TestForwardAsAnthropic_DisablesAPIKeyContinuationWhenUpstreamRequiresWebSoc func TestForwardAsAnthropic_APIKeyMetadataSessionSurvivesChangingCacheControlAnchorAfterContinuationDisabled(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) metadata := `{"user_id":"{\"device_id\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_uuid\":\"\",\"session_id\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"}"}` firstBody := []byte(`{"model":"claude-haiku-4-5-20251001","max_tokens":16,"metadata":` + metadata + `,"system":[{"type":"text","text":"project docs","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"first"}],"stream":false}`) @@ -712,7 +701,6 @@ func TestForwardAsAnthropic_APIKeyMetadataSessionSurvivesChangingCacheControlAnc func TestForwardAsAnthropic_DoesNotAttachPreviousResponseIDForOAuthCompat(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{resp: openAICompatSSECompletedResponse("resp_oauth_next", "gpt-5.4")} svc := &OpenAIGatewayService{ @@ -746,7 +734,6 @@ func TestForwardAsAnthropic_DoesNotAttachPreviousResponseIDForOAuthCompat(t *tes func TestForwardAsAnthropic_ReusesOAuthCodexTurnState(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) firstResp := openAICompatSSECompletedResponse("resp_oauth_first", "gpt-5.4") firstResp.Header.Set("x-codex-turn-state", "turn_state_first") @@ -803,7 +790,6 @@ func TestForwardAsAnthropic_ReusesOAuthCodexTurnState(t *testing.T) { func TestForwardAsAnthropic_OAuthDigestFallbackReusesTurnStateWithoutExplicitKey(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) firstResp := openAICompatSSECompletedResponse("resp_oauth_digest_first", "gpt-5.4") firstResp.Header.Set("x-codex-turn-state", "turn_state_digest_first") @@ -859,7 +845,6 @@ func TestForwardAsAnthropic_OAuthDigestFallbackReusesTurnStateWithoutExplicitKey func TestForwardAsAnthropic_OAuthMetadataSessionSurvivesDigestPrefixRewrite(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) firstResp := openAICompatSSECompletedResponse("resp_oauth_metadata_first", "gpt-5.5") firstResp.Header.Set("x-codex-turn-state", "turn_state_metadata_first") @@ -916,7 +901,6 @@ func TestForwardAsAnthropic_OAuthMetadataSessionSurvivesDigestPrefixRewrite(t *t func TestForwardAsAnthropic_OAuthMetadataSessionSurvivesChangingCacheControlAnchor(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) firstResp := openAICompatSSECompletedResponse("resp_oauth_cache_anchor_first", "gpt-5.5") firstResp.Header.Set("x-codex-turn-state", "turn_state_cache_anchor_first") @@ -973,7 +957,6 @@ func TestForwardAsAnthropic_OAuthMetadataSessionSurvivesChangingCacheControlAnch func TestForwardAsAnthropic_OAuthKeepsSystemAsDeveloperInput(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{resp: openAICompatSSECompletedResponse("resp_oauth_system", "gpt-5.4")} svc := &OpenAIGatewayService{ @@ -1013,7 +996,6 @@ func TestForwardAsAnthropic_OAuthKeepsSystemAsDeveloperInput(t *testing.T) { func TestForwardAsAnthropic_OAuthAddsClaudeCodeTodoGuardForCompatModel(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{resp: openAICompatSSECompletedResponse("resp_oauth_todo_guard", "gpt-5.5")} svc := &OpenAIGatewayService{ @@ -1050,7 +1032,6 @@ func TestForwardAsAnthropic_OAuthAddsClaudeCodeTodoGuardForCompatModel(t *testin func TestForwardAsAnthropic_OAuthPreservesClaudeCodeToolCallID(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{resp: openAICompatSSECompletedResponse("resp_oauth_tool", "gpt-5.4")} svc := &OpenAIGatewayService{ @@ -1087,7 +1068,6 @@ func TestForwardAsAnthropic_OAuthPreservesClaudeCodeToolCallID(t *testing.T) { func TestForwardAsAnthropic_StoresStreamingResponseIDWithoutUsage(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{} svc := &OpenAIGatewayService{ @@ -1161,7 +1141,6 @@ func openAICompatSSEResponseWithoutUsage(responseID, model string) *http.Respons func TestForwardAsAnthropic_ForcedCodexInstructionsTemplatePrependsRenderedInstructions(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) templateDir := t.TempDir() templatePath := filepath.Join(templateDir, "codex-instructions.md.tmpl") @@ -1212,7 +1191,6 @@ func TestForwardAsAnthropic_ForcedCodexInstructionsTemplatePrependsRenderedInstr func TestForwardAsAnthropic_ForcedCodexInstructionsTemplateUsesCachedTemplateContent(t *testing.T) { t.Parallel() - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1258,7 +1236,6 @@ func TestForwardAsAnthropic_ForcedCodexInstructionsTemplateUsesCachedTemplateCon } func TestForwardAsAnthropic_ClientDisconnectDrainsUpstreamUsage(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1305,7 +1282,6 @@ func TestForwardAsAnthropic_ClientDisconnectDrainsUpstreamUsage(t *testing.T) { } func TestForwardAsAnthropic_TerminalUsageWithoutUpstreamCloseReturns(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1361,7 +1337,6 @@ func TestForwardAsAnthropic_TerminalUsageWithoutUpstreamCloseReturns(t *testing. } func TestForwardAsAnthropic_BufferedTerminalWithoutUpstreamCloseReturns(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1417,7 +1392,6 @@ func TestForwardAsAnthropic_BufferedTerminalWithoutUpstreamCloseReturns(t *testi } func TestForwardAsAnthropic_DoneSentinelWithoutTerminalReturnsError(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1454,7 +1428,6 @@ func TestForwardAsAnthropic_DoneSentinelWithoutTerminalReturnsError(t *testing.T } func TestForwardAsAnthropic_UpstreamRequestIgnoresClientCancel(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/openai_fast_policy_ws_test.go b/backend/internal/service/openai_fast_policy_ws_test.go index 7c8341b2..1bba9c35 100644 --- a/backend/internal/service/openai_fast_policy_ws_test.go +++ b/backend/internal/service/openai_fast_policy_ws_test.go @@ -318,7 +318,6 @@ func TestPolicyEnforcingFrameConn_WithoutCapturedFallbackPolicyMisses(t *testing // is normalized + filtered out before being written upstream. This is the // integration flavour of TestWSResponseCreate_FilterStripsServiceTier. func TestWSResponseCreate_IngressFiltersServiceTierBeforeUpstream(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -440,7 +439,6 @@ func TestWSResponseCreate_IngressFiltersServiceTierBeforeUpstream(t *testing.T) // asserts that with a custom block rule, the client receives a Realtime-style // error event AND the upstream FrameConn never receives the offending frame. func TestWSResponseCreate_IngressBlockSendsErrorEventAndSkipsUpstream(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false diff --git a/backend/internal/service/openai_gateway_chat_completions_raw_test.go b/backend/internal/service/openai_gateway_chat_completions_raw_test.go index 1be07fd7..ddb9864e 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw_test.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw_test.go @@ -77,7 +77,6 @@ func TestBuildOpenAIResponsesURL_ProbeURL(t *testing.T) { } func TestForwardAsRawChatCompletions_ForcesStreamUsageUpstreamAndPassesUsageDownstream(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":true}`) rec := httptest.NewRecorder() @@ -119,7 +118,6 @@ func TestForwardAsRawChatCompletions_ForcesStreamUsageUpstreamAndPassesUsageDown } func TestForwardAsRawChatCompletions_ClientDisconnectDrainsUsage(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":true}`) rec := httptest.NewRecorder() @@ -158,7 +156,6 @@ func TestForwardAsRawChatCompletions_ClientDisconnectDrainsUsage(t *testing.T) { } func TestForwardAsRawChatCompletions_UpstreamRequestIgnoresClientCancel(t *testing.T) { - gin.SetMode(gin.TestMode) reqCtx, cancel := context.WithCancel(context.Background()) body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":true}`) @@ -215,7 +212,6 @@ func TestEnsureOpenAIChatStreamUsage(t *testing.T) { } func TestBufferRawChatCompletions_RejectsOversizedResponse(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/openai_gateway_chat_completions_test.go b/backend/internal/service/openai_gateway_chat_completions_test.go index b0d1fa31..b35ab6d1 100644 --- a/backend/internal/service/openai_gateway_chat_completions_test.go +++ b/backend/internal/service/openai_gateway_chat_completions_test.go @@ -98,7 +98,6 @@ func TestNormalizeResponsesBodyServiceTier(t *testing.T) { } func TestForwardAsChatCompletions_UnknownModelDoesNotUseDefaultMappedModel(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -134,7 +133,6 @@ func TestForwardAsChatCompletions_UnknownModelDoesNotUseDefaultMappedModel(t *te } func TestForwardAsChatCompletions_ClientDisconnectDrainsUpstreamUsage(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -181,7 +179,6 @@ func TestForwardAsChatCompletions_ClientDisconnectDrainsUpstreamUsage(t *testing } func TestForwardAsChatCompletions_TerminalUsageWithoutUpstreamCloseReturns(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -237,7 +234,6 @@ func TestForwardAsChatCompletions_TerminalUsageWithoutUpstreamCloseReturns(t *te } func TestForwardAsChatCompletions_BufferedTerminalWithoutUpstreamCloseReturns(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -293,7 +289,6 @@ func TestForwardAsChatCompletions_BufferedTerminalWithoutUpstreamCloseReturns(t } func TestForwardAsChatCompletions_DoneSentinelWithoutTerminalReturnsError(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -330,7 +325,6 @@ func TestForwardAsChatCompletions_DoneSentinelWithoutTerminalReturnsError(t *tes } func TestForwardAsChatCompletions_UpstreamRequestIgnoresClientCancel(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/openai_gateway_service_codex_cli_only_test.go b/backend/internal/service/openai_gateway_service_codex_cli_only_test.go index fe58e92f..0ea7c5fe 100644 --- a/backend/internal/service/openai_gateway_service_codex_cli_only_test.go +++ b/backend/internal/service/openai_gateway_service_codex_cli_only_test.go @@ -23,7 +23,6 @@ func (s *stubCodexRestrictionDetector) Detect(_ *gin.Context, _ *Account) CodexC } func TestOpenAIGatewayService_GetCodexClientRestrictionDetector(t *testing.T) { - gin.SetMode(gin.TestMode) t.Run("使用注入的 detector", func(t *testing.T) { expected := &stubCodexRestrictionDetector{ @@ -60,7 +59,6 @@ func TestOpenAIGatewayService_GetCodexClientRestrictionDetector(t *testing.T) { } func TestGetAPIKeyIDFromContext(t *testing.T) { - gin.SetMode(gin.TestMode) t.Run("context 为 nil", func(t *testing.T) { require.Equal(t, int64(0), getAPIKeyIDFromContext(nil)) @@ -124,7 +122,6 @@ func TestLogCodexCLIOnlyDetection_OnlyLogsRejected(t *testing.T) { } func TestLogCodexCLIOnlyDetection_RejectedIncludesRequestDetails(t *testing.T) { - gin.SetMode(gin.TestMode) logSink, restore := captureStructuredLog(t) defer restore() @@ -153,7 +150,6 @@ func TestLogCodexCLIOnlyDetection_RejectedIncludesRequestDetails(t *testing.T) { } func TestLogOpenAIInstructionsRequiredDebug_LogsRequestDetails(t *testing.T) { - gin.SetMode(gin.TestMode) logSink, restore := captureStructuredLog(t) defer restore() @@ -188,7 +184,6 @@ func TestLogOpenAIInstructionsRequiredDebug_LogsRequestDetails(t *testing.T) { } func TestLogOpenAIInstructionsRequiredDebug_NonTargetErrorSkipped(t *testing.T) { - gin.SetMode(gin.TestMode) logSink, restore := captureStructuredLog(t) defer restore() @@ -232,7 +227,6 @@ func TestIsOpenAITransientProcessingError(t *testing.T) { } func TestOpenAIGatewayService_Forward_LogsInstructionsRequiredDetails(t *testing.T) { - gin.SetMode(gin.TestMode) logSink, restore := captureStructuredLog(t) defer restore() @@ -286,7 +280,6 @@ func TestOpenAIGatewayService_Forward_LogsInstructionsRequiredDetails(t *testing } func TestOpenAIGatewayService_Forward_TransientProcessingErrorTriggersFailover(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/openai_gateway_service_hotpath_test.go b/backend/internal/service/openai_gateway_service_hotpath_test.go index 234dee00..63d1bd7f 100644 --- a/backend/internal/service/openai_gateway_service_hotpath_test.go +++ b/backend/internal/service/openai_gateway_service_hotpath_test.go @@ -107,7 +107,6 @@ func TestExtractOpenAIReasoningEffortFromBody(t *testing.T) { } func TestGetOpenAIRequestBodyMap_UsesContextCache(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -126,7 +125,6 @@ func TestGetOpenAIRequestBodyMap_ParseErrorWithoutCache(t *testing.T) { } func TestGetOpenAIRequestBodyMap_WriteBackContextCache(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/openai_gateway_service_test.go b/backend/internal/service/openai_gateway_service_test.go index 84a2fe71..861bb75f 100644 --- a/backend/internal/service/openai_gateway_service_test.go +++ b/backend/internal/service/openai_gateway_service_test.go @@ -153,7 +153,6 @@ func (c stubConcurrencyCache) GetAccountsLoadBatch(ctx context.Context, accounts } func TestOpenAIGatewayService_GenerateSessionHash_Priority(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil) @@ -198,7 +197,6 @@ func TestOpenAIGatewayService_GenerateSessionHash_Priority(t *testing.T) { } func TestOpenAIGatewayService_GenerateSessionHash_UsesXXHash64(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil) @@ -212,7 +210,6 @@ func TestOpenAIGatewayService_GenerateSessionHash_UsesXXHash64(t *testing.T) { } func TestOpenAIGatewayService_GenerateSessionHash_AttachesLegacyHashToContext(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil) @@ -228,7 +225,6 @@ func TestOpenAIGatewayService_GenerateSessionHash_AttachesLegacyHashToContext(t } func TestOpenAIGatewayService_GenerateExplicitSessionHash_SkipsContentFallback(t *testing.T) { - gin.SetMode(gin.TestMode) svc := &OpenAIGatewayService{} body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat"}`) @@ -263,7 +259,6 @@ func TestOpenAIGatewayService_GenerateExplicitSessionHash_SkipsContentFallback(t } func TestOpenAIGatewayService_GenerateSessionHashWithFallback(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil) @@ -281,7 +276,6 @@ func TestOpenAIGatewayService_GenerateSessionHashWithFallback(t *testing.T) { } func TestOpenAIGatewayService_GenerateSessionHash_ContentFallback(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/chat/completions", nil) @@ -306,7 +300,6 @@ func TestOpenAIGatewayService_GenerateSessionHash_ContentFallback(t *testing.T) } func TestOpenAIGatewayService_GenerateSessionHash_ExplicitSignalWinsOverContent(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/chat/completions", nil) @@ -324,7 +317,6 @@ func TestOpenAIGatewayService_GenerateSessionHash_ExplicitSignalWinsOverContent( } func TestOpenAIGatewayService_GenerateSessionHash_EmptyBodyStillEmpty(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/chat/completions", nil) @@ -979,7 +971,6 @@ func TestOpenAISelectAccountWithLoadAwareness_PreferNeverUsed(t *testing.T) { } func TestOpenAIStreamingTimeout(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 1, @@ -1014,7 +1005,6 @@ func TestOpenAIStreamingTimeout(t *testing.T) { } func TestOpenAIStreamingContextCanceledReturnsIncompleteErrorWithoutInjectingErrorEvent(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1046,7 +1036,6 @@ func TestOpenAIStreamingContextCanceledReturnsIncompleteErrorWithoutInjectingErr } func TestOpenAIStreamingReadErrorBeforeOutputReturnsFailover(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1076,7 +1065,6 @@ func TestOpenAIStreamingReadErrorBeforeOutputReturnsFailover(t *testing.T) { } func TestOpenAIStreamingResponseFailedBeforeOutputReturnsFailover(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1117,7 +1105,6 @@ func TestOpenAIStreamingResponseFailedBeforeOutputReturnsFailover(t *testing.T) } func TestOpenAIStreamingPreambleOnlyMissingTerminalReturnsFailover(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1153,7 +1140,6 @@ func TestOpenAIStreamingPreambleOnlyMissingTerminalReturnsFailover(t *testing.T) } func TestOpenAIStreamingPreambleKeepaliveUsesDownstreamIdle(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1193,7 +1179,6 @@ func TestOpenAIStreamingPreambleKeepaliveUsesDownstreamIdle(t *testing.T) { } func TestOpenAIStreamingPolicyResponseFailedBeforeOutputPassesThrough(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1230,7 +1215,6 @@ func TestOpenAIStreamingPolicyResponseFailedBeforeOutputPassesThrough(t *testing } func TestOpenAIStreamingClientDisconnectDrainsUpstreamUsage(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1275,7 +1259,6 @@ func TestOpenAIStreamingClientDisconnectDrainsUpstreamUsage(t *testing.T) { } func TestOpenAIStreamingMissingTerminalEventReturnsIncompleteError(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1309,7 +1292,6 @@ func TestOpenAIStreamingMissingTerminalEventReturnsIncompleteError(t *testing.T) } func TestOpenAIStreamingPassthroughMissingTerminalEventReturnsIncompleteError(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ MaxLineSize: defaultMaxLineSize, @@ -1341,7 +1323,6 @@ func TestOpenAIStreamingPassthroughMissingTerminalEventReturnsIncompleteError(t } func TestOpenAIStreamingPassthroughResponseFailedBeforeOutputReturnsFailover(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ MaxLineSize: defaultMaxLineSize, @@ -1377,7 +1358,6 @@ func TestOpenAIStreamingPassthroughResponseFailedBeforeOutputReturnsFailover(t * } func TestOpenAIStreamingPassthroughResponseDoneWithoutDoneMarkerStillSucceeds(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ MaxLineSize: defaultMaxLineSize, @@ -1412,7 +1392,6 @@ func TestOpenAIStreamingPassthroughResponseDoneWithoutDoneMarkerStillSucceeds(t } func TestOpenAIStreamingPassthroughResponseIncompleteWithoutDoneMarkerStillSucceeds(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ MaxLineSize: defaultMaxLineSize, @@ -1447,7 +1426,6 @@ func TestOpenAIStreamingPassthroughResponseIncompleteWithoutDoneMarkerStillSucce } func TestOpenAIStreamingTooLong(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1487,7 +1465,6 @@ func TestOpenAIStreamingTooLong(t *testing.T) { } func TestOpenAINonStreamingContentTypePassThrough(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Security: config.SecurityConfig{ ResponseHeaders: config.ResponseHeaderConfig{Enabled: false}, @@ -1517,7 +1494,6 @@ func TestOpenAINonStreamingContentTypePassThrough(t *testing.T) { } func TestOpenAINonStreamingContentTypeDefault(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Security: config.SecurityConfig{ ResponseHeaders: config.ResponseHeaderConfig{Enabled: false}, @@ -1547,7 +1523,6 @@ func TestOpenAINonStreamingContentTypeDefault(t *testing.T) { } func TestOpenAIStreamingHeadersOverride(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Security: config.SecurityConfig{ ResponseHeaders: config.ResponseHeaderConfig{Enabled: false}, @@ -1598,7 +1573,6 @@ func TestOpenAIStreamingHeadersOverride(t *testing.T) { } func TestOpenAIStreamingReuseScannerBufferAndStillWorks(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Gateway: config.GatewayConfig{ StreamDataIntervalTimeout: 0, @@ -1635,7 +1609,6 @@ func TestOpenAIStreamingReuseScannerBufferAndStillWorks(t *testing.T) { } func TestOpenAIInvalidBaseURLWhenAllowlistDisabled(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{ Security: config.SecurityConfig{ URLAllowlist: config.URLAllowlistConfig{Enabled: false}, @@ -1743,7 +1716,6 @@ func TestOpenAIUpdateCodexUsageSnapshotFromHeaders(t *testing.T) { } func TestOpenAIResponsesRequestPathSuffix(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1786,7 +1758,6 @@ func TestNormalizeOpenAICompactRequestBodyPreservesCurrentCodexPayloadFields(t * } func TestOpenAIBuildUpstreamRequestOpenAIPassthroughPreservesCompactPath(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses/compact", bytes.NewReader([]byte(`{"model":"gpt-5"}`))) @@ -1803,7 +1774,6 @@ func TestOpenAIBuildUpstreamRequestOpenAIPassthroughPreservesCompactPath(t *test } func TestOpenAIBuildUpstreamRequestCompactForcesJSONAcceptForOAuth(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses/compact", bytes.NewReader([]byte(`{"model":"gpt-5"}`))) @@ -1823,7 +1793,6 @@ func TestOpenAIBuildUpstreamRequestCompactForcesJSONAcceptForOAuth(t *testing.T) } func TestOpenAIBuildUpstreamRequestOAuthMessagesBridgeUsesSessionOnly(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) body := []byte(`{"model":"gpt-5.5","prompt_cache_key":"anthropic-metadata-session-1","input":[{"type":"message","role":"developer","content":[{"type":"input_text","text":""}]},{"type":"message","role":"user","content":"hello"}]}`) @@ -1846,7 +1815,6 @@ func TestOpenAIBuildUpstreamRequestOAuthMessagesBridgeUsesSessionOnly(t *testing } func TestOpenAIBuildUpstreamRequestPreservesCompactPathForAPIKeyBaseURL(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/responses/compact", bytes.NewReader([]byte(`{"model":"gpt-5"}`))) @@ -1868,7 +1836,6 @@ func TestOpenAIBuildUpstreamRequestPreservesCompactPathForAPIKeyBaseURL(t *testi } func TestOpenAIBuildUpstreamRequestOAuthOfficialClientOriginatorCompatibility(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string @@ -2191,7 +2158,6 @@ func TestExtractCodexFinalResponse_SampleReplay(t *testing.T) { } func TestHandleSSEToJSON_CompletedEventReturnsJSON(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/", nil) @@ -2220,7 +2186,6 @@ func TestHandleSSEToJSON_CompletedEventReturnsJSON(t *testing.T) { } func TestHandleSSEToJSON_ReconstructsImageGenerationOutputItemDone(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/", nil) @@ -2247,7 +2212,6 @@ func TestHandleSSEToJSON_ReconstructsImageGenerationOutputItemDone(t *testing.T) } func TestHandleSSEToJSON_NoFinalResponseKeepsSSEBody(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/", nil) @@ -2271,7 +2235,6 @@ func TestHandleSSEToJSON_NoFinalResponseKeepsSSEBody(t *testing.T) { } func TestHandleSSEToJSON_ResponseFailedReturnsProtocolError(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/", nil) diff --git a/backend/internal/service/openai_image_generation_controls_test.go b/backend/internal/service/openai_image_generation_controls_test.go index 9ff8b510..f5bc01d6 100644 --- a/backend/internal/service/openai_image_generation_controls_test.go +++ b/backend/internal/service/openai_image_generation_controls_test.go @@ -16,7 +16,6 @@ import ( ) func TestOpenAIGatewayServiceForward_RejectsDisabledImageGenerationIntents(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string @@ -55,7 +54,6 @@ func TestOpenAIGatewayServiceForward_RejectsDisabledImageGenerationIntents(t *te } func TestOpenAIGatewayServiceForward_DisabledGroupAllowsTextOnlyResponses(t *testing.T) { - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{ resp: &http.Response{ @@ -80,7 +78,6 @@ func TestOpenAIGatewayServiceForward_DisabledGroupAllowsTextOnlyResponses(t *tes } func TestOpenAIGatewayServiceForward_CodexImageInjectionRespectsGroupCapability(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string @@ -121,7 +118,6 @@ func TestOpenAIGatewayServiceForward_CodexImageInjectionRespectsGroupCapability( } func TestOpenAIGatewayServiceForward_ExplicitImageToolWorksWithBridgeDisabled(t *testing.T) { - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{ resp: &http.Response{ @@ -148,7 +144,6 @@ func TestOpenAIGatewayServiceForward_ExplicitImageToolWorksWithBridgeDisabled(t } func TestOpenAIGatewayServiceForward_ChannelBridgeOverrideEnablesCodexInjection(t *testing.T) { - gin.SetMode(gin.TestMode) upstream := &httpUpstreamRecorder{ resp: &http.Response{ @@ -269,7 +264,6 @@ func TestOpenAIGatewayService_CodexImageGenerationBridgeOverridePrecedence(t *te } func TestOpenAIGatewayServiceHandleResponsesImageOutputs_NonStreaming(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newOpenAIImageGenerationControlTestService(&httpUpstreamRecorder{}) c, _ := newOpenAIImageGenerationControlTestContext(true, "unit-test-agent/1.0") @@ -296,7 +290,6 @@ func TestOpenAIGatewayServiceHandleResponsesImageOutputs_NonStreaming(t *testing } func TestOpenAIGatewayServiceHandleResponsesImageOutputs_Streaming(t *testing.T) { - gin.SetMode(gin.TestMode) svc := newOpenAIImageGenerationControlTestService(&httpUpstreamRecorder{}) c, _ := newOpenAIImageGenerationControlTestContext(true, "unit-test-agent/1.0") diff --git a/backend/internal/service/openai_images_test.go b/backend/internal/service/openai_images_test.go index 45fb24e9..652c3e7c 100644 --- a/backend/internal/service/openai_images_test.go +++ b/backend/internal/service/openai_images_test.go @@ -33,7 +33,6 @@ func (w *failingOpenAIImageWriter) Write(p []byte) (int, error) { } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_JSON(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","size":"1024x1024","quality":"high","stream":true}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -57,7 +56,6 @@ func TestOpenAIGatewayServiceParseOpenAIImagesRequest_JSON(t *testing.T) { } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_MultipartEdit(t *testing.T) { - gin.SetMode(gin.TestMode) var body bytes.Buffer writer := multipart.NewWriter(&body) @@ -136,7 +134,6 @@ func TestOpenAIImagesRequestModerationBody_MultipartEditIncludesUploadsInMemory( } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_NormalizesOfficialAndCustomSizes(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { size string @@ -177,7 +174,6 @@ func TestOpenAIGatewayServiceParseOpenAIImagesRequest_NormalizesOfficialAndCusto } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_UnknownSizesDoNotBlockPassthrough(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { size string @@ -212,7 +208,6 @@ func TestOpenAIGatewayServiceParseOpenAIImagesRequest_UnknownSizesDoNotBlockPass } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_LegacyImageModelUnknownSizePassthrough(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-1.5","prompt":"draw a cat","size":"2048x1152"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -230,7 +225,6 @@ func TestOpenAIGatewayServiceParseOpenAIImagesRequest_LegacyImageModelUnknownSiz } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_MultipartEditWithMaskAndNativeOptions(t *testing.T) { - gin.SetMode(gin.TestMode) var body bytes.Buffer writer := multipart.NewWriter(&body) @@ -282,7 +276,6 @@ func TestOpenAIGatewayServiceParseOpenAIImagesRequest_MultipartEditWithMaskAndNa } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_PromptOnlyDefaultsRemainBasic(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"prompt":"draw a cat"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -300,7 +293,6 @@ func TestOpenAIGatewayServiceParseOpenAIImagesRequest_PromptOnlyDefaultsRemainBa } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_ExplicitSizeRequiresNativeCapability(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"prompt":"draw a cat","size":"1024x1024"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -317,7 +309,6 @@ func TestOpenAIGatewayServiceParseOpenAIImagesRequest_ExplicitSizeRequiresNative } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_RejectsNonImageModel(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-5.4","prompt":"draw a cat"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -333,7 +324,6 @@ func TestOpenAIGatewayServiceParseOpenAIImagesRequest_RejectsNonImageModel(t *te } func TestOpenAIGatewayServiceParseOpenAIImagesRequest_JSONEditURLs(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{ "model":"gpt-image-2", "prompt":"replace the background", @@ -471,7 +461,6 @@ func findOpenAIImageTestSSEEvent(events []openAIImageTestSSEEvent, name string) } func TestOpenAIGatewayServiceForwardImages_OAuthUsesResponsesAPI(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","size":"1024x1024","quality":"high","n":2}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -546,7 +535,6 @@ func TestOpenAIGatewayServiceForwardImages_OAuthUsesResponsesAPI(t *testing.T) { } func TestOpenAIGatewayServiceForwardImages_APIKeyGenerationUsesConfiguredV1BaseURL(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","response_format":"b64_json"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -601,7 +589,6 @@ func TestOpenAIGatewayServiceForwardImages_APIKeyGenerationUsesConfiguredV1BaseU } func TestOpenAIGatewayServiceForwardImages_APIKeyStreamJSONResponseBillsImage(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true,"response_format":"b64_json"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -650,7 +637,6 @@ func TestOpenAIGatewayServiceForwardImages_APIKeyStreamJSONResponseBillsImage(t } func TestOpenAIGatewayServiceForwardImages_APIKeyStreamRawJSONEventStreamFallbackBillsImage(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true,"response_format":"b64_json"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -698,7 +684,6 @@ func TestOpenAIGatewayServiceForwardImages_APIKeyStreamRawJSONEventStreamFallbac } func TestOpenAIGatewayServiceForwardImages_APIKeyStreamMultilineSSEDataBillsImage(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true,"response_format":"b64_json"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -755,7 +740,6 @@ func TestExtractOpenAIImagesBillableCountFromJSONBytes_CompletedEvent(t *testing } func TestOpenAIGatewayServiceForwardImages_APIKeyEditUsesConfiguredV1BaseURL(t *testing.T) { - gin.SetMode(gin.TestMode) var body bytes.Buffer writer := multipart.NewWriter(&body) @@ -818,7 +802,6 @@ func TestOpenAIGatewayServiceForwardImages_APIKeyEditUsesConfiguredV1BaseURL(t * } func TestOpenAIGatewayServiceForwardImages_OAuthStreamingTransformsEvents(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true,"response_format":"url"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -892,7 +875,6 @@ func TestOpenAIGatewayServiceForwardImages_OAuthStreamingTransformsEvents(t *tes } func TestOpenAIGatewayServiceForwardImages_APIKeyStreamingDrainsAfterClientDisconnect(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -947,7 +929,6 @@ func TestOpenAIGatewayServiceForwardImages_APIKeyStreamingDrainsAfterClientDisco } func TestOpenAIGatewayServiceForwardImages_OAuthEditsMultipartUsesResponsesAPI(t *testing.T) { - gin.SetMode(gin.TestMode) var body bytes.Buffer writer := multipart.NewWriter(&body) @@ -1027,7 +1008,6 @@ func TestOpenAIGatewayServiceForwardImages_OAuthEditsMultipartUsesResponsesAPI(t } func TestOpenAIGatewayServiceForwardImages_OAuthEditsStreamingTransformsEvents(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{ "model":"gpt-image-2", "prompt":"replace background with aurora", @@ -1179,7 +1159,6 @@ func TestCollectOpenAIImagesFromResponsesBody_MultilineSSE(t *testing.T) { } func TestOpenAIGatewayServiceForwardImages_OAuthStreamingHandlesOutputItemDoneFallback(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true,"response_format":"url"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -1236,7 +1215,6 @@ func TestOpenAIGatewayServiceForwardImages_OAuthStreamingHandlesOutputItemDoneFa } func TestOpenAIGatewayServiceForwardImages_OAuthStreamingHandlesMultilineSSE(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true,"response_format":"b64_json"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) @@ -1291,7 +1269,6 @@ func TestOpenAIGatewayServiceForwardImages_OAuthStreamingHandlesMultilineSSE(t * } func TestOpenAIGatewayServiceForwardImages_OAuthStreamingDrainsAfterClientDisconnect(t *testing.T) { - gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true,"response_format":"url"}`) req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) diff --git a/backend/internal/service/openai_oauth_passthrough_test.go b/backend/internal/service/openai_oauth_passthrough_test.go index 398cbb85..eeabd28d 100644 --- a/backend/internal/service/openai_oauth_passthrough_test.go +++ b/backend/internal/service/openai_oauth_passthrough_test.go @@ -59,7 +59,6 @@ func (u *httpUpstreamRecorder) DoWithTLS(req *http.Request, proxyURL string, acc } func TestOpenAIGatewayService_ResponsesUnknownModelDoesNotFallbackToGPT54(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -102,7 +101,6 @@ func TestOpenAIGatewayService_ResponsesUnknownModelDoesNotFallbackToGPT54(t *tes } func TestOpenAIGatewayService_OAuthMessagesBridgeDoesNotInjectDefaultInstructions(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -264,7 +262,6 @@ func captureStructuredLog(t *testing.T) (*inMemoryLogSink, func()) { } func TestOpenAIGatewayService_OAuthPassthrough_StreamKeepsToolNameAndBodyNormalized(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -351,7 +348,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_StreamKeepsToolNameAndBodyNormali } func TestOpenAIGatewayService_OAuthPassthrough_CompactUsesJSONAndKeepsNonStreaming(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -405,7 +401,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_CompactUsesJSONAndKeepsNonStreami } func TestOpenAIGatewayService_OAuthPassthrough_UpstreamRequestIgnoresClientCancel(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -451,7 +446,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_UpstreamRequestIgnoresClientCance } func TestOpenAIGatewayService_OAuthPassthrough_CodexMissingInstructionsRejectedBeforeUpstream(t *testing.T) { - gin.SetMode(gin.TestMode) logSink, restore := captureStructuredLog(t) defer restore() @@ -504,7 +498,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_CodexMissingInstructionsRejectedB } func TestOpenAIGatewayService_OAuthPassthrough_DisabledUsesLegacyTransform(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -549,7 +542,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_DisabledUsesLegacyTransform(t *te } func TestOpenAIGatewayService_OAuthLegacy_UpstreamRequestIgnoresClientCancel(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -595,7 +587,6 @@ func TestOpenAIGatewayService_OAuthLegacy_UpstreamRequestIgnoresClientCancel(t * } func TestOpenAIGatewayService_OAuthLegacy_CompositeCodexUAUsesCodexOriginator(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -638,7 +629,6 @@ func TestOpenAIGatewayService_OAuthLegacy_CompositeCodexUAUsesCodexOriginator(t } func TestOpenAIGatewayService_OAuthPassthrough_ResponseHeadersAllowXCodex(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -696,7 +686,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_ResponseHeadersAllowXCodex(t *tes } func TestOpenAIGatewayService_OAuthPassthrough_UpstreamErrorIncludesPassthroughFlag(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -746,7 +735,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_UpstreamErrorIncludesPassthroughF } func TestOpenAIGatewayService_OpenAIPassthrough_429And529TriggerFailover(t *testing.T) { - gin.SetMode(gin.TestMode) originalBody := []byte(`{"model":"gpt-5.2","stream":false,"instructions":"local-test-instructions","input":[{"type":"text","text":"hi"}]}`) newAccount := func(accountType string) *Account { @@ -884,7 +872,6 @@ func TestOpenAIGatewayService_OpenAIPassthrough_429And529TriggerFailover(t *test } func TestOpenAIGatewayService_OAuthPassthrough_NonCodexUAFallbackToCodexUA(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -927,7 +914,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_NonCodexUAFallbackToCodexUA(t *te } func TestOpenAIGatewayService_CodexCLIOnly_RejectsNonCodexClient(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -960,7 +946,6 @@ func TestOpenAIGatewayService_CodexCLIOnly_RejectsNonCodexClient(t *testing.T) { } func TestOpenAIGatewayService_CodexCLIOnly_AllowOfficialClientFamilies(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string @@ -1018,7 +1003,6 @@ func TestOpenAIGatewayService_CodexCLIOnly_AllowOfficialClientFamilies(t *testin } func TestOpenAIGatewayService_OAuthPassthrough_StreamingSetsFirstTokenMs(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1070,7 +1054,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_StreamingSetsFirstTokenMs(t *test } func TestOpenAIGatewayService_OAuthPassthrough_StreamClientDisconnectStillCollectsUsage(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1125,7 +1108,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_StreamClientDisconnectStillCollec } func TestOpenAIGatewayService_APIKeyPassthrough_PreservesBodyAndUsesResponsesEndpoint(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1173,7 +1155,6 @@ func TestOpenAIGatewayService_APIKeyPassthrough_PreservesBodyAndUsesResponsesEnd } func TestOpenAIGatewayService_OAuthPassthrough_WarnOnTimeoutHeadersForStream(t *testing.T) { - gin.SetMode(gin.TestMode) logSink, restore := captureStructuredLog(t) defer restore() @@ -1214,7 +1195,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_WarnOnTimeoutHeadersForStream(t * } func TestOpenAIGatewayService_OAuthPassthrough_InfoWhenStreamEndsWithoutDone(t *testing.T) { - gin.SetMode(gin.TestMode) logSink, restore := captureStructuredLog(t) defer restore() @@ -1256,7 +1236,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_InfoWhenStreamEndsWithoutDone(t * } func TestOpenAIGatewayService_OAuthPassthrough_DefaultFiltersTimeoutHeaders(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1302,7 +1281,6 @@ func TestOpenAIGatewayService_OAuthPassthrough_DefaultFiltersTimeoutHeaders(t *t } func TestOpenAIGatewayService_OAuthPassthrough_AllowTimeoutHeadersWhenConfigured(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go index a4b39ddf..c8d1da08 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go +++ b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go @@ -19,7 +19,6 @@ import ( ) func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_KeepLeaseAcrossTurns(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -165,7 +164,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_KeepLeaseAcrossT } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_DedicatedModeDoesNotReuseConnAcrossSessions(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -299,7 +297,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_DedicatedModeDoe } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PassthroughModeRelaysByCaddyAdapter(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -442,7 +439,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PassthroughModeR } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_ModeOffReturnsPolicyViolation(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -540,7 +536,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_ModeOffReturnsPo } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPrevResponseStrictDropToFullCreate(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -676,7 +671,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPre } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPrevResponseStrictDropBeforePreflightPingFailReconnects(t *testing.T) { - gin.SetMode(gin.TestMode) prevPreflightPingIdle := openAIWSIngressPreflightPingIdle openAIWSIngressPreflightPingIdle = 0 defer func() { @@ -828,7 +822,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPre } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreEnabledSkipsStrictPrevResponseEval(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -960,7 +953,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreEnabledSkip } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPrevResponsePreflightSkipForFunctionCallOutput(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -1092,7 +1084,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPre } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledFunctionCallOutputAutoAttachPreviousResponseID(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -1224,7 +1215,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledFun } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledFunctionCallOutputSkipsAutoAttachWhenLastResponseIDMissing(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -1357,7 +1347,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledFun } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledFunctionCallOutputSkipsAutoAttachWhenToolCallContextPresent(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -1491,7 +1480,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledFun } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledFunctionCallOutputAutoAttachWhenOnlyItemReferencesPresent(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -1625,7 +1613,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledFun } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PreflightPingFailReconnectsBeforeTurn(t *testing.T) { - gin.SetMode(gin.TestMode) prevPreflightPingIdle := openAIWSIngressPreflightPingIdle openAIWSIngressPreflightPingIdle = 0 defer func() { @@ -1767,7 +1754,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PreflightPingFai } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledStrictAffinityPreflightPingFailAutoRecoveryReconnects(t *testing.T) { - gin.SetMode(gin.TestMode) prevPreflightPingIdle := openAIWSIngressPreflightPingIdle openAIWSIngressPreflightPingIdle = 0 defer func() { @@ -1919,7 +1905,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledStr } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPreflightPingFailClosesWhenFunctionCallOutputNeedsPreviousResponseID(t *testing.T) { - gin.SetMode(gin.TestMode) prevPreflightPingIdle := openAIWSIngressPreflightPingIdle openAIWSIngressPreflightPingIdle = 0 defer func() { @@ -2065,7 +2050,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPre } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPreflightPingFailClosesWhenReplayHasFunctionCallOutput(t *testing.T) { - gin.SetMode(gin.TestMode) prevPreflightPingIdle := openAIWSIngressPreflightPingIdle openAIWSIngressPreflightPingIdle = 0 defer func() { @@ -2211,7 +2195,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledPre } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_WriteFailBeforeDownstreamRetriesOnce(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -2372,7 +2355,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_WriteFailBeforeD } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PreviousResponseNotFoundRecoversByDroppingPrevID(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -2523,7 +2505,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PreviousResponse } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledStrictAffinityPreviousResponseNotFoundLayer2Recovery(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -2679,7 +2660,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_StoreDisabledStr } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PreviousResponseNotFoundRecoveryRemovesDuplicatePrevID(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -2830,7 +2810,6 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PreviousResponse } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_RejectsMessageIDAsPreviousResponseID(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -3053,7 +3032,6 @@ func (c *openAIWSWriteFailAfterFirstTurnConn) Close() error { } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_ClientDisconnectStillDrainsUpstream(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false diff --git a/backend/internal/service/openai_ws_forwarder_success_test.go b/backend/internal/service/openai_ws_forwarder_success_test.go index cd816533..35f16fa0 100644 --- a/backend/internal/service/openai_ws_forwarder_success_test.go +++ b/backend/internal/service/openai_ws_forwarder_success_test.go @@ -23,7 +23,6 @@ import ( ) func TestOpenAIGatewayService_Forward_WSv2_SuccessAndBindSticky(t *testing.T) { - gin.SetMode(gin.TestMode) type receivedPayload struct { Type string @@ -172,7 +171,6 @@ func TestOpenAIGatewayService_Forward_WSv2_SuccessAndBindSticky(t *testing.T) { } func TestOpenAIGatewayService_Forward_WSv2_ImageGenerationCountsOutputs(t *testing.T) { - gin.SetMode(gin.TestMode) upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -313,7 +311,6 @@ func TestLogOpenAIWSBindResponseAccountWarn(t *testing.T) { } func TestOpenAIGatewayService_Forward_WSv2_RewriteModelAndToolCallsOnCompletedEvent(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -398,7 +395,6 @@ func TestOpenAIWSPayloadString_OnlyAcceptsStringValues(t *testing.T) { } func TestOpenAIGatewayService_Forward_WSv2_PoolReuseNotOneToOne(t *testing.T) { - gin.SetMode(gin.TestMode) var upgradeCount atomic.Int64 var sequence atomic.Int64 @@ -509,7 +505,6 @@ func TestOpenAIGatewayService_Forward_WSv2_PoolReuseNotOneToOne(t *testing.T) { } func TestOpenAIGatewayService_Forward_WSv2_OAuthStoreFalseByDefault(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -583,7 +578,6 @@ func TestOpenAIGatewayService_Forward_WSv2_OAuthStoreFalseByDefault(t *testing.T } func TestOpenAIGatewayService_Forward_WSv2_OAuthOriginatorCompatibility(t *testing.T) { - gin.SetMode(gin.TestMode) tests := []struct { name string @@ -663,7 +657,6 @@ func TestOpenAIGatewayService_Forward_WSv2_OAuthOriginatorCompatibility(t *testi } func TestOpenAIGatewayService_Forward_WSv2_HeaderSessionFallbackFromPromptCacheKey(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -728,7 +721,6 @@ func TestOpenAIGatewayService_Forward_WSv2_HeaderSessionFallbackFromPromptCacheK } func TestOpenAIGatewayService_Forward_WSv1_Unsupported(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -788,7 +780,6 @@ func TestOpenAIGatewayService_Forward_WSv1_Unsupported(t *testing.T) { } func TestOpenAIGatewayService_Forward_WSv2_TurnStateAndMetadataReplayOnReconnect(t *testing.T) { - gin.SetMode(gin.TestMode) var connIndex atomic.Int64 headersCh := make(chan http.Header, 4) @@ -907,7 +898,6 @@ func TestOpenAIGatewayService_Forward_WSv2_TurnStateAndMetadataReplayOnReconnect } func TestOpenAIGatewayService_Forward_WSv2_GeneratePrewarm(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1026,7 +1016,6 @@ func TestOpenAIGatewayService_PrewarmReadHonorsParentContext(t *testing.T) { } func TestOpenAIGatewayService_Forward_WSv2_TurnMetadataInPayloadOnConnReuse(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := &config.Config{} cfg.Security.URLAllowlist.Enabled = false @@ -1110,7 +1099,6 @@ func TestOpenAIGatewayService_Forward_WSv2_TurnMetadataInPayloadOnConnReuse(t *t } func TestOpenAIGatewayService_Forward_WSv2StoreFalseSessionConnIsolation(t *testing.T) { - gin.SetMode(gin.TestMode) var upgradeCount atomic.Int64 var sequence atomic.Int64 @@ -1217,7 +1205,6 @@ func TestOpenAIGatewayService_Forward_WSv2StoreFalseSessionConnIsolation(t *test } func TestOpenAIGatewayService_Forward_WSv2StoreFalseDisableForceNewConnAllowsReuse(t *testing.T) { - gin.SetMode(gin.TestMode) var upgradeCount atomic.Int64 var sequence atomic.Int64 @@ -1315,7 +1302,6 @@ func TestOpenAIGatewayService_Forward_WSv2StoreFalseDisableForceNewConnAllowsReu } func TestOpenAIGatewayService_Forward_WSv2ReadTimeoutAppliesPerRead(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/openai_ws_protocol_forward_test.go b/backend/internal/service/openai_ws_protocol_forward_test.go index f3936de1..3cec9f61 100644 --- a/backend/internal/service/openai_ws_protocol_forward_test.go +++ b/backend/internal/service/openai_ws_protocol_forward_test.go @@ -63,7 +63,6 @@ func (u *httpUpstreamSequenceRecorder) DoWithTLS(req *http.Request, proxyURL str } func TestOpenAIGatewayService_Forward_PreservePreviousResponseIDWhenWSEnabled(t *testing.T) { - gin.SetMode(gin.TestMode) wsFallbackServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) })) @@ -121,7 +120,6 @@ func TestOpenAIGatewayService_Forward_PreservePreviousResponseIDWhenWSEnabled(t } func TestOpenAIGatewayService_Forward_HTTPIngressStaysHTTPWhenWSEnabled(t *testing.T) { - gin.SetMode(gin.TestMode) wsFallbackServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) })) @@ -187,7 +185,6 @@ func TestOpenAIGatewayService_Forward_HTTPIngressStaysHTTPWhenWSEnabled(t *testi } func TestOpenAIGatewayService_Forward_HTTPIngressRetriesInvalidEncryptedContentOnce(t *testing.T) { - gin.SetMode(gin.TestMode) wsFallbackServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) })) @@ -273,7 +270,6 @@ func TestOpenAIGatewayService_Forward_HTTPIngressRetriesInvalidEncryptedContentO } func TestOpenAIGatewayService_Forward_HTTPIngressRetriesWrappedInvalidEncryptedContentOnce(t *testing.T) { - gin.SetMode(gin.TestMode) wsFallbackServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) })) @@ -357,7 +353,6 @@ func TestOpenAIGatewayService_Forward_HTTPIngressRetriesWrappedInvalidEncryptedC } func TestOpenAIGatewayService_Forward_RemovePreviousResponseIDWhenWSDisabled(t *testing.T) { - gin.SetMode(gin.TestMode) wsFallbackServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) })) @@ -413,7 +408,6 @@ func TestOpenAIGatewayService_Forward_RemovePreviousResponseIDWhenWSDisabled(t * } func TestOpenAIGatewayService_Forward_WSv2Dial426FallbackHTTP(t *testing.T) { - gin.SetMode(gin.TestMode) ws426Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUpgradeRequired) _, _ = w.Write([]byte(`upgrade required`)) @@ -476,7 +470,6 @@ func TestOpenAIGatewayService_Forward_WSv2Dial426FallbackHTTP(t *testing.T) { } func TestOpenAIGatewayService_Forward_WSv2FallbackCoolingSkipWS(t *testing.T) { - gin.SetMode(gin.TestMode) wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) })) @@ -539,7 +532,6 @@ func TestOpenAIGatewayService_Forward_WSv2FallbackCoolingSkipWS(t *testing.T) { } func TestOpenAIGatewayService_Forward_ReturnErrorWhenOnlyWSv1Enabled(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -627,7 +619,6 @@ func TestNewOpenAIGatewayService_InitializesOpenAIWSResolver(t *testing.T) { } func TestOpenAIGatewayService_Forward_WSv2FallbackWhenResponseAlreadyWrittenReturnsWSError(t *testing.T) { - gin.SetMode(gin.TestMode) ws426Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUpgradeRequired) _, _ = w.Write([]byte(`upgrade required`)) @@ -687,7 +678,6 @@ func TestOpenAIGatewayService_Forward_WSv2FallbackWhenResponseAlreadyWrittenRetu } func TestOpenAIGatewayService_Forward_WSv2StreamEarlyCloseFallbackHTTP(t *testing.T) { - gin.SetMode(gin.TestMode) upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -780,7 +770,6 @@ func TestOpenAIGatewayService_Forward_WSv2StreamEarlyCloseFallbackHTTP(t *testin } func TestOpenAIGatewayService_Forward_WSv2RetryFiveTimesThenFallbackHTTP(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} @@ -862,7 +851,6 @@ func TestOpenAIGatewayService_Forward_WSv2RetryFiveTimesThenFallbackHTTP(t *test } func TestOpenAIGatewayService_Forward_WSv2PolicyViolationFastFallbackHTTP(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} @@ -943,7 +931,6 @@ func TestOpenAIGatewayService_Forward_WSv2PolicyViolationFastFallbackHTTP(t *tes } func TestOpenAIGatewayService_Forward_WSv2ConnectionLimitReachedRetryThenFallbackHTTP(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} @@ -1027,7 +1014,6 @@ func TestOpenAIGatewayService_Forward_WSv2ConnectionLimitReachedRetryThenFallbac } func TestOpenAIGatewayService_Forward_WSv2PreviousResponseNotFoundRecoversByDroppingPreviousResponseID(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 var wsRequestPayloads [][]byte @@ -1144,7 +1130,6 @@ func TestOpenAIGatewayService_Forward_WSv2PreviousResponseNotFoundRecoversByDrop } func TestOpenAIGatewayService_Forward_WSv2PreviousResponseNotFoundSkipsRecoveryForFunctionCallOutput(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 var wsRequestPayloads [][]byte @@ -1242,7 +1227,6 @@ func TestOpenAIGatewayService_Forward_WSv2PreviousResponseNotFoundSkipsRecoveryF } func TestOpenAIGatewayService_Forward_WSv2PreviousResponseNotFoundSkipsRecoveryWithoutPreviousResponseID(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 var wsRequestPayloads [][]byte @@ -1339,7 +1323,6 @@ func TestOpenAIGatewayService_Forward_WSv2PreviousResponseNotFoundSkipsRecoveryW } func TestOpenAIGatewayService_Forward_WSv2PreviousResponseNotFoundOnlyRecoversOnce(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 var wsRequestPayloads [][]byte @@ -1437,7 +1420,6 @@ func TestOpenAIGatewayService_Forward_WSv2PreviousResponseNotFoundOnlyRecoversOn } func TestOpenAIGatewayService_Forward_WSv2InvalidEncryptedContentRecoversOnce(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 var wsRequestPayloads [][]byte @@ -1557,7 +1539,6 @@ func TestOpenAIGatewayService_Forward_WSv2InvalidEncryptedContentRecoversOnce(t } func TestOpenAIGatewayService_Forward_WSv2InvalidEncryptedContentSkipsRecoveryWithoutReasoningItem(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 var wsRequestPayloads [][]byte @@ -1656,7 +1637,6 @@ func TestOpenAIGatewayService_Forward_WSv2InvalidEncryptedContentSkipsRecoveryWi } func TestOpenAIGatewayService_Forward_WSv2InvalidEncryptedContentRecoversSingleObjectInputAndKeepsSummary(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 var wsRequestPayloads [][]byte @@ -1774,7 +1754,6 @@ func TestOpenAIGatewayService_Forward_WSv2InvalidEncryptedContentRecoversSingleO } func TestOpenAIGatewayService_Forward_WSv2InvalidEncryptedContentKeepsPreviousResponseIDForFunctionCallOutput(t *testing.T) { - gin.SetMode(gin.TestMode) var wsAttempts atomic.Int32 var wsRequestPayloads [][]byte diff --git a/backend/internal/service/openai_ws_ratelimit_signal_test.go b/backend/internal/service/openai_ws_ratelimit_signal_test.go index 4ee85a3a..5e62d83f 100644 --- a/backend/internal/service/openai_ws_ratelimit_signal_test.go +++ b/backend/internal/service/openai_ws_ratelimit_signal_test.go @@ -84,7 +84,6 @@ func (r *openAICodexExtraListRepo) ListWithFilters(_ context.Context, params pag } func TestOpenAIGatewayService_Forward_WSv2ErrorEventUsageLimitPersistsRateLimit(t *testing.T) { - gin.SetMode(gin.TestMode) resetAt := time.Now().Add(2 * time.Hour).Unix() upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} @@ -169,7 +168,6 @@ func TestOpenAIGatewayService_Forward_WSv2ErrorEventUsageLimitPersistsRateLimit( } func TestOpenAIGatewayService_Forward_WSv2Handshake429PersistsRateLimit(t *testing.T) { - gin.SetMode(gin.TestMode) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("x-codex-primary-used-percent", "100") @@ -240,7 +238,6 @@ func TestOpenAIGatewayService_Forward_WSv2Handshake429PersistsRateLimit(t *testi } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_ErrorEventUsageLimitPersistsRateLimit(t *testing.T) { - gin.SetMode(gin.TestMode) cfg := newOpenAIWSV2TestConfig() cfg.Security.URLAllowlist.Enabled = false diff --git a/backend/internal/service/ops_upstream_context_test.go b/backend/internal/service/ops_upstream_context_test.go index fa6d1085..040ad8ae 100644 --- a/backend/internal/service/ops_upstream_context_test.go +++ b/backend/internal/service/ops_upstream_context_test.go @@ -30,7 +30,6 @@ func TestSafeUpstreamURL(t *testing.T) { } func TestAppendOpsUpstreamError_UsesRequestBodyBytesFromContext(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -49,7 +48,6 @@ func TestAppendOpsUpstreamError_UsesRequestBodyBytesFromContext(t *testing.T) { } func TestAppendOpsUpstreamError_UsesRequestBodyStringFromContext(t *testing.T) { - gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/usage_cleanup_service_test.go b/backend/internal/service/usage_cleanup_service_test.go index 17f21bef..50b4a8fd 100644 --- a/backend/internal/service/usage_cleanup_service_test.go +++ b/backend/internal/service/usage_cleanup_service_test.go @@ -56,6 +56,7 @@ type cleanupRepoStub struct { } type dashboardRepoStub struct { + mu sync.Mutex recomputeErr error recomputeCalls int } @@ -65,10 +66,18 @@ func (s *dashboardRepoStub) AggregateRange(ctx context.Context, start, end time. } func (s *dashboardRepoStub) RecomputeRange(ctx context.Context, start, end time.Time) error { + s.mu.Lock() + defer s.mu.Unlock() s.recomputeCalls++ return s.recomputeErr } +func (s *dashboardRepoStub) RecomputeCallCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.recomputeCalls +} + func (s *dashboardRepoStub) GetAggregationWatermark(ctx context.Context) (time.Time, error) { return time.Time{}, nil } @@ -580,7 +589,7 @@ func TestUsageCleanupServiceExecuteTaskDashboardRecomputeError(t *testing.T) { repo.mu.Lock() defer repo.mu.Unlock() require.Len(t, repo.markSucceeded, 1) - require.Eventually(t, func() bool { return dashboardRepo.recomputeCalls == 1 }, time.Second, 10*time.Millisecond) + require.Eventually(t, func() bool { return dashboardRepo.RecomputeCallCount() == 1 }, time.Second, 10*time.Millisecond) } func TestUsageCleanupServiceExecuteTaskDashboardRecomputeSuccess(t *testing.T) { @@ -608,7 +617,7 @@ func TestUsageCleanupServiceExecuteTaskDashboardRecomputeSuccess(t *testing.T) { repo.mu.Lock() defer repo.mu.Unlock() require.Len(t, repo.markSucceeded, 1) - require.Eventually(t, func() bool { return dashboardRepo.recomputeCalls == 1 }, time.Second, 10*time.Millisecond) + require.Eventually(t, func() bool { return dashboardRepo.RecomputeCallCount() == 1 }, time.Second, 10*time.Millisecond) } func TestUsageCleanupServiceExecuteTaskCanceled(t *testing.T) {