Assign stable keys to the three supported sources, preserve excluded historical rows, and expose history read-only in admin. Add migration, coverage, and responsive browser spec. Refs #13 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
272 lines
13 KiB
Go
272 lines
13 KiB
Go
// These tests define the public use-case seam expected by ticket #7. The
|
|
// production package/types are intentionally absent in this red phase.
|
|
package generation
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/tradarr/backend/internal/models"
|
|
"github.com/tradarr/backend/internal/scraper"
|
|
)
|
|
|
|
type contractRepository struct {
|
|
inputs map[string]UserInput
|
|
saved map[string][]GenerationRecord
|
|
}
|
|
|
|
func (r *contractRepository) LoadUserInput(_ context.Context, userID string) (UserInput, error) {
|
|
input, ok := r.inputs[userID]
|
|
if !ok {
|
|
return UserInput{}, fmt.Errorf("unknown user %s", userID)
|
|
}
|
|
return input, nil
|
|
}
|
|
|
|
func (r *contractRepository) SaveGeneration(_ context.Context, userID string, record GenerationRecord) error {
|
|
r.saved[userID] = append(r.saved[userID], record)
|
|
return nil
|
|
}
|
|
|
|
type contractScraper struct {
|
|
name string
|
|
articles []scraper.Article
|
|
err error
|
|
calls [][]string
|
|
}
|
|
|
|
func (s *contractScraper) Name() string { return s.name }
|
|
func (s *contractScraper) Scrape(_ context.Context, symbols []string) ([]scraper.Article, error) {
|
|
s.calls = append(s.calls, append([]string(nil), symbols...))
|
|
return append([]scraper.Article(nil), s.articles...), s.err
|
|
}
|
|
|
|
type contractRanker struct {
|
|
order []string
|
|
err error
|
|
modes []string
|
|
}
|
|
|
|
func (r *contractRanker) Rank(_ context.Context, mode string, _ []models.UserAsset, candidates []Candidate) ([]Candidate, error) {
|
|
r.modes = append(r.modes, mode)
|
|
if r.err != nil {
|
|
return nil, r.err
|
|
}
|
|
byID := make(map[string]Candidate, len(candidates))
|
|
for _, candidate := range candidates {
|
|
byID[candidate.ID] = candidate
|
|
byID[candidate.Article.Title] = candidate
|
|
}
|
|
if len(r.order) == 0 {
|
|
return append([]Candidate(nil), candidates...), nil
|
|
}
|
|
ordered := make([]Candidate, 0, len(r.order))
|
|
for _, id := range r.order {
|
|
if candidate, ok := byID[id]; ok {
|
|
ordered = append(ordered, candidate)
|
|
}
|
|
}
|
|
return ordered, nil
|
|
}
|
|
|
|
type contractSummarizer struct {
|
|
languages []string
|
|
articles [][]Candidate
|
|
err error
|
|
}
|
|
|
|
func (s *contractSummarizer) Summarize(_ context.Context, language string, _ []models.UserAsset, articles []Candidate) (string, error) {
|
|
s.languages = append(s.languages, language)
|
|
s.articles = append(s.articles, append([]Candidate(nil), articles...))
|
|
if s.err != nil {
|
|
return "", s.err
|
|
}
|
|
return "summary-only", nil
|
|
}
|
|
|
|
func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testing.T) {
|
|
alphaID, betaID := "user-alpha", "user-beta"
|
|
alphaSource := models.Source{ID: "alpha-feed", Type: "alpha", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}
|
|
betaSource := models.Source{ID: "beta-feed", Type: "beta", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}
|
|
disabled := models.Source{ID: "disabled-feed", Type: "disabled", SourceKey: testSourceKey(models.SourceWatcherGuru), Enabled: false, ArticleLimit: 5}
|
|
alphaScraper := &contractScraper{name: "alpha", articles: []scraper.Article{{Title: "alpha-only", URL: "https://private.test/alpha", Content: "alpha-secret"}}}
|
|
betaScraper := &contractScraper{name: "beta", articles: []scraper.Article{{Title: "beta-only", URL: "https://private.test/beta", Content: "beta-secret"}}}
|
|
disabledScraper := &contractScraper{name: "disabled"}
|
|
ranker := &contractRanker{}
|
|
summarizer := &contractSummarizer{}
|
|
repo := &contractRepository{
|
|
inputs: map[string]UserInput{
|
|
alphaID: {Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "ALPHA", Name: "Alpha Index"}}, Sources: []models.Source{alphaSource, disabled}},
|
|
betaID: {Language: "en", RankingMode: "title_content", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "BETA", Name: "Beta Index"}}, Sources: []models.Source{betaSource}},
|
|
},
|
|
saved: map[string][]GenerationRecord{},
|
|
}
|
|
useCase := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: alphaScraper, models.SourceBloomberg: betaScraper, models.SourceWatcherGuru: disabledScraper}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) }})
|
|
|
|
alpha, err := useCase.Generate(context.Background(), alphaID)
|
|
if err != nil || alpha.Summary == nil {
|
|
t.Fatalf("alpha generation: result=%+v err=%v", alpha, err)
|
|
}
|
|
beta, err := useCase.Generate(context.Background(), betaID)
|
|
if err != nil || beta.Summary == nil {
|
|
t.Fatalf("beta generation: result=%+v err=%v", beta, err)
|
|
}
|
|
if !reflect.DeepEqual(alphaScraper.calls, [][]string{{"ALPHA"}}) || !reflect.DeepEqual(betaScraper.calls, [][]string{{"BETA"}}) {
|
|
t.Fatalf("scraper symbols crossed users: alpha=%v beta=%v", alphaScraper.calls, betaScraper.calls)
|
|
}
|
|
if len(disabledScraper.calls) != 0 {
|
|
t.Fatalf("disabled source was scraped: %v", disabledScraper.calls)
|
|
}
|
|
if !reflect.DeepEqual(ranker.modes, []string{"title", "title_content"}) || !reflect.DeepEqual(summarizer.languages, []string{"fr", "en"}) {
|
|
t.Fatalf("user preferences not applied: modes=%v languages=%v", ranker.modes, summarizer.languages)
|
|
}
|
|
if len(repo.saved[alphaID]) != 1 || len(repo.saved[betaID]) != 1 || len(repo.saved["user-gamma"]) != 0 {
|
|
t.Fatalf("generation persistence crossed users: %#v", repo.saved)
|
|
}
|
|
encoded, err := json.Marshal(alpha)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, private := range []string{"alpha-only", "alpha-secret", "https://private.test/alpha"} {
|
|
if strings.Contains(string(encoded), private) {
|
|
t.Fatalf("article candidate leaked into generation result: %s", encoded)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestUseCasePreservesLayaOrderThenAppliesPerSourceAndGlobalCaps(t *testing.T) {
|
|
articles := []scraper.Article{
|
|
{Title: "a1"}, {Title: "a2"}, {Title: "b1"}, {Title: "a3"}, {Title: "b2"},
|
|
}
|
|
feedA := &contractScraper{name: "a", articles: articles[:2]}
|
|
feedB := &contractScraper{name: "b", articles: articles[2:]}
|
|
ranker := &contractRanker{order: []string{"a2", "b1", "a1", "b2", "a3"}}
|
|
summarizer := &contractSummarizer{}
|
|
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 3, Assets: []models.UserAsset{{Symbol: "IDX"}}, Sources: []models.Source{{ID: "a", Type: "a", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}, {ID: "b", Type: "b", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
|
|
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feedA, models.SourceBloomberg: feedB}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
|
if _, err := uc.Generate(context.Background(), "u"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(summarizer.articles) != 1 {
|
|
t.Fatalf("summary calls=%d, want 1", len(summarizer.articles))
|
|
}
|
|
got := candidateTitles(summarizer.articles[0])
|
|
want := []string{"a2", "b1", "b2"}
|
|
if !reflect.DeepEqual(got, want) {
|
|
t.Fatalf("rank order/caps got %v, want %v", got, want)
|
|
}
|
|
}
|
|
|
|
func TestUseCaseNoResultsInvalidLayaAndSummaryFailurePersistNoSummary(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
articles []scraper.Article
|
|
rankErr error
|
|
summaryErr error
|
|
}{
|
|
{name: "no results"},
|
|
{name: "invalid Laya result", articles: []scraper.Article{{Title: "candidate"}}, rankErr: errors.New("invalid ranked IDs")},
|
|
{name: "summary provider failure", articles: []scraper.Article{{Title: "candidate"}}, summaryErr: errors.New("provider unavailable")},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Sources: []models.Source{{ID: "s", Type: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 10}}}}, saved: map[string][]GenerationRecord{}}
|
|
ranker := &contractRanker{err: tt.rankErr}
|
|
summarizer := &contractSummarizer{err: tt.summaryErr}
|
|
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{name: "s", articles: tt.articles}}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
|
result, err := uc.Generate(context.Background(), "u")
|
|
if err != nil {
|
|
t.Fatalf("expected aggregate failure outcome, got error: %v", err)
|
|
}
|
|
if result.Summary != nil {
|
|
t.Fatalf("failed generation persisted summary: %+v", result.Summary)
|
|
}
|
|
if result.Outcome.Status == "" || len(repo.saved["u"]) != 1 {
|
|
t.Fatalf("failure outcome not persisted: result=%+v saved=%v", result, repo.saved)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestUseCasePartialSourceFailureCanSummarizeRemainingSources(t *testing.T) {
|
|
good := &contractScraper{name: "good", articles: []scraper.Article{{Title: "good-result"}}}
|
|
bad := &contractScraper{name: "bad", err: errors.New("private error with URL https://private.test/article")}
|
|
ranker := &contractRanker{order: []string{"good-result"}}
|
|
summarizer := &contractSummarizer{}
|
|
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "good", Type: "good", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}, {ID: "bad", Type: "bad", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
|
|
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: good, models.SourceBloomberg: bad}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
|
result, err := uc.Generate(context.Background(), "u")
|
|
if err != nil || result.Summary == nil || result.Outcome.Status != "partial" {
|
|
t.Fatalf("partial source failure result=%+v err=%v", result, err)
|
|
}
|
|
encoded, err := json.Marshal(result.Outcome)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if contains(string(encoded), "private.test/article") || contains(string(encoded), "private error") {
|
|
t.Fatalf("unbounded source error leaked to outcome: %s", encoded)
|
|
}
|
|
if result.Outcome.FailureCode == "" || len(result.Outcome.FailureCode) > 64 {
|
|
t.Fatalf("partial outcome must use a bounded failure code: %+v", result.Outcome)
|
|
}
|
|
}
|
|
|
|
func TestUseCaseOutcomeContainsAggregateCountsWithoutArticleIdentifiers(t *testing.T) {
|
|
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "candidate-title-secret", URL: "https://private.test/x", Content: "candidate-content-secret"}}}
|
|
ranker := &contractRanker{order: []string{"candidate-title-secret"}}
|
|
summarizer := &contractSummarizer{}
|
|
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "source-id", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
|
|
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
|
result, err := uc.Generate(context.Background(), "u")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
encoded, err := json.Marshal(result)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, secret := range []string{"candidate-title-secret", "candidate-content-secret", "https://private.test/x"} {
|
|
if contains(string(encoded), secret) {
|
|
t.Fatalf("article field leaked in result: %s", encoded)
|
|
}
|
|
}
|
|
if result.Outcome.Language != "fr" || result.Outcome.RankingMode != "title_content" || result.Outcome.TotalCandidates != 1 {
|
|
t.Fatalf("aggregate outcome missing locale/mode/counts: %+v", result.Outcome)
|
|
}
|
|
}
|
|
|
|
func TestUseCaseCountsTitleOnlyFallbackWhenContentIsUnavailable(t *testing.T) {
|
|
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "title-without-content", Content: ""}}}
|
|
ranker := &contractRanker{}
|
|
summarizer := &contractSummarizer{}
|
|
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "en", RankingMode: "title_content", GlobalLimit: 4, Sources: []models.Source{{ID: "source", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 4}}}}, saved: map[string][]GenerationRecord{}}
|
|
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
|
result, err := uc.Generate(context.Background(), "u")
|
|
if err != nil || result.Summary == nil {
|
|
t.Fatalf("content fallback should permit generation: result=%+v err=%v", result, err)
|
|
}
|
|
if result.Outcome.ContentFallbacks != 1 {
|
|
t.Fatalf("content fallback count=%d, want 1", result.Outcome.ContentFallbacks)
|
|
}
|
|
}
|
|
|
|
func candidateTitles(candidates []Candidate) []string {
|
|
titles := make([]string, len(candidates))
|
|
for i, candidate := range candidates {
|
|
titles[i] = candidate.Article.Title
|
|
}
|
|
return titles
|
|
}
|
|
|
|
func contains(value, needle string) bool {
|
|
return len(needle) > 0 && strings.Contains(value, needle)
|
|
}
|
|
|
|
func testSourceKey(key string) *string { return &key }
|