Files
TradarrV2/backend/internal/api/handlers/generation_http_contract_test.go
Blomios 768c0fd7f5 feat(generation): persist summary outcomes without articles
Record generation outcomes and summaries for history while keeping article content transient.

Refs #7

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-20 21:20:35 +01:00

111 lines
4.4 KiB
Go

package handlers_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
)
const generationHTTPSecret = "ticket-7-http-contract-secret"
type fakeGenerationUseCase struct {
result generation.Result
err error
userID string
calls int
}
func (f *fakeGenerationUseCase) Generate(_ context.Context, userID string) (generation.Result, error) {
f.calls++
f.userID = userID
return f.result, f.err
}
func TestGenerateSummaryHTTPUsesJWTUserAndReturnsAggregateOnlyEnvelopes(t *testing.T) {
previousMode := gin.Mode()
gin.SetMode(gin.TestMode)
t.Cleanup(func() { gin.SetMode(previousMode) })
token, err := auth.GenerateToken("jwt-owner", "owner@example.test", "user", generationHTTPSecret)
if err != nil {
t.Fatal(err)
}
tests := []struct {
name string
status string
wantStatus int
wantSummary bool
}{
{name: "success", status: "succeeded", wantStatus: http.StatusCreated, wantSummary: true},
{name: "partial", status: "partial", wantStatus: http.StatusCreated, wantSummary: true},
{name: "no results", status: "no_results", wantStatus: http.StatusOK, wantSummary: false},
{name: "provider failure", status: "failed", wantStatus: http.StatusBadGateway, wantSummary: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fake := &fakeGenerationUseCase{result: generation.Result{
Outcome: generation.GenerationOutcome{
ID: "outcome-aggregate-id", Status: tt.status, Language: "fr", RankingMode: "title",
TotalCandidates: 7, ContentFallbacks: 1, LayaSelected: 2,
Selected: 2, SourceStats: []generation.SourceStat{{SourceID: "source-aggregate-id", SourceType: "fixture", Status: "ok", Candidates: 7, LayaSelected: 2}},
},
}}
if tt.wantSummary {
fake.result.Summary = &models.Summary{ID: "summary-id", UserID: "jwt-owner", Content: "Safe synthesized market summary"}
}
h := handlers.New(nil, &config.Config{JWTSecret: generationHTTPSecret}, nil, nil, ai.NewPipeline(nil, nil), nil)
h.SetGenerationUseCase(fake)
router := api.SetupRouter(h, generationHTTPSecret)
body := `{"user_id":"attacker-user","title":"candidate-title-secret","url":"https://candidate.invalid/private","content":"candidate-content-secret","candidate_id":"candidate-id-secret"}`
request := httptest.NewRequest(http.MethodPost, "/api/summaries/generate", strings.NewReader(body))
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != tt.wantStatus {
t.Fatalf("POST /api/summaries/generate status=%d, want %d: %s", response.Code, tt.wantStatus, response.Body.String())
}
if fake.calls != 1 || fake.userID != "jwt-owner" {
t.Fatalf("use case identity came from client input: calls=%d userID=%q", fake.calls, fake.userID)
}
var envelope struct {
Data struct {
Summary *models.Summary `json:"summary"`
Outcome generation.GenerationOutcome `json:"outcome"`
} `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &envelope); err != nil {
t.Fatalf("decode generation envelope: %v; body=%s", err, response.Body.String())
}
if (envelope.Data.Summary != nil) != tt.wantSummary || envelope.Data.Outcome.Status != tt.status {
t.Fatalf("unexpected summary/outcome envelope: %+v", envelope.Data)
}
for _, articleValue := range []string{"candidate-title-secret", "https://candidate.invalid/private", "candidate-content-secret", "candidate-id-secret"} {
if strings.Contains(response.Body.String(), articleValue) {
t.Errorf("article candidate data leaked in response: %q", articleValue)
}
}
outcomeJSON, err := json.Marshal(envelope.Data.Outcome)
if err != nil {
t.Fatal(err)
}
for _, articleField := range []string{`"title"`, `"url"`, `"content"`, `"prompt"`, `"candidate_id"`} {
if strings.Contains(string(outcomeJSON), articleField+":") {
t.Errorf("article field %s leaked into outcome: %s", articleField, outcomeJSON)
}
}
})
}
}