Files
TradarrV2/backend/internal/api/generation_ticket7_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

237 lines
11 KiB
Go

package api_test
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/lib/pq"
"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/models"
"github.com/tradarr/backend/internal/scraper"
)
const ticket7JWTSecret = "ticket-7-test-secret"
func TestGenerationHistoryRouteExistsAndIsAuthenticated(t *testing.T) {
router := api.SetupRouter(handlers.New(nil, &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, nil, nil), ticket7JWTSecret)
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/summaries/generations?limit=10", nil))
if response.Code != http.StatusUnauthorized {
t.Fatalf("GET /api/summaries/generations without a token: got %d, want 401; body=%s", response.Code, response.Body.String())
}
}
func TestGenerationHistoryIsScopedToJWTUserPostgres(t *testing.T) {
db, _ := ticket7DB(t)
if _, err := db.Exec(`CREATE TABLE summary_generations (id UUID PRIMARY KEY, user_id UUID NOT NULL, summary_id UUID, outcome JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`); err != nil {
t.Fatal(err)
}
for _, row := range []struct{ id, user, marker string }{
{"00000000-0000-0000-0000-000000000101", "00000000-0000-0000-0000-000000000001", "alpha-private-outcome"},
{"00000000-0000-0000-0000-000000000202", "00000000-0000-0000-0000-000000000002", "beta-private-outcome"},
} {
if _, err := db.Exec(`INSERT INTO summary_generations (id,user_id,outcome) VALUES ($1,$2,$3)`, row.id, row.user, `{"marker":"`+row.marker+`"}`); err != nil {
t.Fatal(err)
}
}
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, nil, nil), ticket7JWTSecret)
for _, user := range []struct{ id, email, own, other string }{
{"00000000-0000-0000-0000-000000000001", "alpha@example.test", "alpha-private-outcome", "beta-private-outcome"},
{"00000000-0000-0000-0000-000000000002", "beta@example.test", "beta-private-outcome", "alpha-private-outcome"},
} {
token, err := auth.GenerateToken(user.id, user.email, "user", ticket7JWTSecret)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodGet, "/api/summaries/generations?limit=10", nil)
request.Header.Set("Authorization", "Bearer "+token)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Errorf("generation history for %s: got %d want 200: %s", user.email, response.Code, response.Body.String())
continue
}
var body map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
encoded, _ := json.Marshal(body["data"])
if !strings.Contains(string(encoded), user.own) || strings.Contains(string(encoded), user.other) {
t.Errorf("generation history crossed user scope for %s: %s", user.email, encoded)
}
}
}
func TestGenerationHistoryLimitContractPostgres(t *testing.T) {
db, _ := ticket7DB(t)
if _, err := db.Exec(`CREATE TABLE summary_generations (id UUID PRIMARY KEY, user_id UUID NOT NULL, summary_id UUID, outcome JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`); err != nil {
t.Fatal(err)
}
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, nil, nil), ticket7JWTSecret)
token, err := auth.GenerateToken("00000000-0000-0000-0000-000000000001", "limit@example.test", "user", ticket7JWTSecret)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
limit string
want int
}{{"50", http.StatusOK}, {"51", http.StatusBadRequest}} {
t.Run("limit="+tc.limit, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "/api/summaries/generations?limit="+tc.limit, nil)
request.Header.Set("Authorization", "Bearer "+token)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != tc.want {
t.Fatalf("GET /api/summaries/generations?limit=%s: got %d, want %d; body=%s", tc.limit, response.Code, tc.want, response.Body.String())
}
})
}
}
func TestPersistentScrapeTriggerRouteIsClosed(t *testing.T) {
router := api.SetupRouter(handlers.New(nil, &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, nil, nil), ticket7JWTSecret)
for _, route := range router.Routes() {
if route.Method == http.MethodPost && route.Path == "/api/admin/scrape-jobs/trigger" {
t.Fatalf("persistent scrape trigger route is still registered: %s %s", route.Method, route.Path)
}
}
}
func TestSummaryGenerationOutcomesMigrationIsAggregateAndTransactionalPostgres(t *testing.T) {
db, schema := ticket7DB(t)
for _, statement := range []string{
`CREATE TABLE users (id UUID PRIMARY KEY, email TEXT NOT NULL UNIQUE)`,
`CREATE TABLE summaries (id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id), content TEXT NOT NULL)`,
} {
if _, err := db.Exec(statement); err != nil {
t.Fatal(err)
}
}
up, err := os.ReadFile("../database/migrations/000013_summary_generations.up.sql")
if err != nil {
t.Fatalf("read migration 000013 summary generations: %v", err)
}
tx, err := db.Begin()
if err != nil {
t.Fatal(err)
}
if _, err = tx.Exec(string(up)); err != nil {
t.Fatalf("apply migration 000013 in a transaction: %v", err)
}
var aggregateColumns int
if err = tx.QueryRow(`SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=$1 AND table_name='summary_generations' AND column_name IN ('user_id','summary_id','outcome','created_at')`, schema).Scan(&aggregateColumns); err != nil || aggregateColumns != 4 {
t.Fatalf("migration must persist user/summary references and aggregate outcome only: aggregate columns=%d err=%v", aggregateColumns, err)
}
var forbiddenColumns int
if err = tx.QueryRow(`SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=$1 AND table_name='summary_generations' AND column_name IN ('article_id','article_title','title','url','content','prompt')`, schema).Scan(&forbiddenColumns); err != nil || forbiddenColumns != 0 {
t.Fatalf("generation outcome schema contains article/prompt data columns: count=%d err=%v", forbiddenColumns, err)
}
for _, relation := range []string{"articles", "article_symbols"} {
var exists bool
if err = tx.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, schema+"."+relation).Scan(&exists); err != nil || exists {
t.Fatalf("generation migration requires/persisted article relation %s: exists=%v err=%v", relation, exists, err)
}
}
if err = tx.Rollback(); err != nil {
t.Fatal(err)
}
var exists bool
if err = db.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, schema+".summary_generations").Scan(&exists); err != nil || exists {
t.Fatalf("migration DDL did not roll back atomically: exists=%v err=%v", exists, err)
}
}
func TestReportRequiresOwnedSummaryAndExcerptFromThatSummaryPostgres(t *testing.T) {
db, _ := ticket7DB(t)
for _, statement := range []string{
`CREATE TABLE users (id UUID PRIMARY KEY, email TEXT NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'user', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE TABLE summaries (id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id), content TEXT NOT NULL, ai_provider_id UUID, generated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE TABLE reports (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id), summary_id UUID REFERENCES summaries(id), context_excerpt TEXT NOT NULL, question TEXT NOT NULL, answer TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'generating', error_msg TEXT NOT NULL DEFAULT '', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL DEFAULT '')`,
`CREATE TABLE ai_providers (id UUID PRIMARY KEY, name TEXT NOT NULL, api_key_encrypted TEXT NOT NULL DEFAULT '', model TEXT NOT NULL DEFAULT '', endpoint TEXT NOT NULL DEFAULT '', is_active BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`INSERT INTO users (id,email,password_hash) VALUES ('00000000-0000-0000-0000-000000000001','first@example.test','hash'), ('00000000-0000-0000-0000-000000000002','second@example.test','hash')`,
`INSERT INTO summaries (id,user_id,content) VALUES ('00000000-0000-0000-0000-000000000011','00000000-0000-0000-0000-000000000001','FIRST USER SUMMARY: approved excerpt.'), ('00000000-0000-0000-0000-000000000022','00000000-0000-0000-0000-000000000002','SECOND USER SUMMARY: private excerpt.')`,
} {
if _, err := db.Exec(statement); err != nil {
t.Fatal(err)
}
}
token, err := auth.GenerateToken("00000000-0000-0000-0000-000000000001", "first@example.test", "user", ticket7JWTSecret)
if err != nil {
t.Fatal(err)
}
repo := models.NewRepository(db)
h := handlers.New(repo, &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, ai.NewPipeline(repo, nil), nil)
router := api.SetupRouter(h, ticket7JWTSecret)
for _, payload := range []string{
`{"excerpts":["FIRST USER SUMMARY: approved excerpt."],"question":"Explain"}`,
`{"summary_id":"00000000-0000-0000-0000-000000000022","excerpts":["SECOND USER SUMMARY: private excerpt."],"question":"Explain"}`,
`{"summary_id":"00000000-0000-0000-0000-000000000011","excerpts":["article data not present in this summary"],"question":"Explain"}`,
} {
request := httptest.NewRequest(http.MethodPost, "/api/reports", strings.NewReader(payload))
request.Header.Set("Authorization", "Bearer "+token)
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code < http.StatusBadRequest || response.Code >= http.StatusInternalServerError {
t.Errorf("report must reject missing/foreign summary or unverified excerpt with a client error: status=%d", response.Code)
}
}
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
var pending int
if err := db.QueryRow(`SELECT COUNT(*) FROM reports WHERE status='generating'`).Scan(&pending); err != nil || pending == 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
var reports int
if err := db.QueryRow(`SELECT COUNT(*) FROM reports`).Scan(&reports); err != nil || reports != 0 {
t.Errorf("rejected report requests were persisted: count=%d err=%v", reports, err)
}
}
func ticket7DB(t *testing.T) (*sql.DB, string) {
t.Helper()
dsn := postgresTestURL(t)
db, err := sql.Open("postgres", dsn)
if err != nil {
t.Fatal(err)
}
db.SetMaxOpenConns(1)
schema := fmt.Sprintf("ticket7_%d", time.Now().UnixNano())
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
db.Close()
t.Fatal(err)
}
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
db.Close()
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
_ = db.Close()
})
return db, schema
}
type inertContractScraper struct{}
func (inertContractScraper) Name() string { return "bloomberg" }
func (inertContractScraper) Scrape(context.Context, []string) ([]scraper.Article, error) {
return nil, nil
}