feat(sources): enforce supported source allowlist
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>
This commit is contained in:
@ -109,7 +109,7 @@ func run(ctx context.Context) error {
|
||||
if err = server.EnsureAdmin(repo, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
feeds := map[string]scraper.Scraper{"stocktwits": e2estack.FakeScraper{URL: fakeURL, Client: client}}
|
||||
feeds := map[string]scraper.Scraper{models.SourceYahooFinance: e2estack.FakeScraper{URL: fakeURL, Client: client}}
|
||||
provider := e2estack.FakeProvider{URL: fakeURL, Client: client}
|
||||
gin.SetMode(gin.TestMode)
|
||||
gin.DefaultWriter = io.Discard
|
||||
@ -222,7 +222,7 @@ func seed(db *sql.DB, fakeURL string) error {
|
||||
if _, err = tx.Exec(`UPDATE sources SET enabled=false`); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES('00000000-0000-0000-0000-000000001201','E2E fixture','stocktwits',true,20)`); err != nil {
|
||||
if _, err = tx.Exec(`UPDATE sources SET enabled=true WHERE source_key='yahoo_finance'`); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(`INSERT INTO ai_providers(id,name,model,endpoint,is_active) VALUES('00000000-0000-0000-0000-000000001202','ollama','fake-laya',$1,true)`, fakeURL); err != nil {
|
||||
|
||||
@ -11,7 +11,6 @@ import (
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/scraper/bloomberg"
|
||||
"github.com/tradarr/backend/internal/scraper/reuters"
|
||||
"github.com/tradarr/backend/internal/scraper/watcherguru"
|
||||
"github.com/tradarr/backend/internal/scraper/yahoofinance"
|
||||
"github.com/tradarr/backend/internal/server"
|
||||
@ -40,9 +39,10 @@ func main() {
|
||||
log.Printf("ensure admin: %v", err)
|
||||
}
|
||||
|
||||
feeds := map[string]scraper.Scraper{}
|
||||
for _, feed := range []scraper.Scraper{bloomberg.NewDynamic(repo, enc, cfg.ScraperURL), yahoofinance.New(), reuters.New(), watcherguru.New()} {
|
||||
feeds[feed.Name()] = feed
|
||||
feeds := map[string]scraper.Scraper{
|
||||
models.SourceBloomberg: bloomberg.NewDynamic(repo, enc, cfg.ScraperURL),
|
||||
models.SourceYahooFinance: yahoofinance.New(),
|
||||
models.SourceWatcherGuru: watcherguru.New(),
|
||||
}
|
||||
|
||||
app := server.New(repo, cfg, server.Dependencies{Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
|
||||
|
||||
@ -39,10 +39,10 @@ func TestArticleCapsMigrationAndInvalidAdminUpdatesAreAtomicPostgres(t *testing.
|
||||
`CREATE TABLE users (id TEXT PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`INSERT INTO users(id,email,password_hash,role) VALUES ('admin-id','admin@example.test','hash','admin')`,
|
||||
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
|
||||
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, source_key TEXT, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE scrape_schedules (id UUID PRIMARY KEY, day_of_week INT NOT NULL, hour INT NOT NULL, minute INT NOT NULL)`,
|
||||
`INSERT INTO settings (key,value) VALUES ('summary_max_articles','733')`,
|
||||
`INSERT INTO sources (id,name,type) VALUES ('00000000-0000-0000-0000-000000000001','Yahoo Finance','stocktwits')`,
|
||||
`INSERT INTO sources (id,name,type,source_key) VALUES ('00000000-0000-0000-0000-000000000001','Yahoo Finance','stocktwits','yahoo_finance')`,
|
||||
} {
|
||||
if _, err = db.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
117
backend/internal/api/admin_sources_ticket13_postgres_test.go
Normal file
117
backend/internal/api/admin_sources_ticket13_postgres_test.go
Normal file
@ -0,0 +1,117 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
"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"
|
||||
)
|
||||
|
||||
func TestAdminSourcesExposeSupportStateAndRejectHistoricalUpdateAtomicallyPostgres(t *testing.T) {
|
||||
dbURL := postgresTestURL(t)
|
||||
db, err := sql.Open("postgres", dbURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("ticket13_admin_sources_%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() })
|
||||
for _, q := range []string{`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,role TEXT,password_hash TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO users(id,email,role,password_hash) VALUES('admin-id','admin@example.test','admin','hash')`, `CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES('old-id','Reuters','reuters',true,42,NULL),('y-id','Yahoo Finance','stocktwits',true,83,'yahoo_finance')`} {
|
||||
if _, err = db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
const secret = "ticket13-admin-route-test"
|
||||
token, err := auth.GenerateToken("admin-id", "admin@example.test", "admin", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
||||
get := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/admin/sources", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
router.ServeHTTP(get, req)
|
||||
if get.Code != http.StatusOK {
|
||||
t.Fatalf("GET sources status=%d body=%s", get.Code, get.Body.String())
|
||||
}
|
||||
var envelope struct {
|
||||
Data []map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(get.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := envelope.Data
|
||||
var old map[string]any
|
||||
var supported map[string]any
|
||||
for _, row := range rows {
|
||||
if row["id"] == "old-id" {
|
||||
old = row
|
||||
}
|
||||
if row["id"] == "y-id" {
|
||||
supported = row
|
||||
}
|
||||
}
|
||||
if old == nil {
|
||||
t.Fatalf("GET omitted historical source: %s", get.Body.String())
|
||||
}
|
||||
for field, want := range map[string]any{"source_key": nil, "supported": false, "enabled": true, "operational": false} {
|
||||
if _, exists := old[field]; !exists {
|
||||
t.Errorf("historical response omitted %s: row=%v", field, old)
|
||||
}
|
||||
if old[field] != want {
|
||||
t.Errorf("historical %s=%v, want %v; row=%v", field, old[field], want, old)
|
||||
}
|
||||
}
|
||||
for _, secretField := range []string{"api_key", "password", "credentials", "article", "content", "url"} {
|
||||
if _, ok := old[secretField]; ok {
|
||||
t.Errorf("GET sources exposed forbidden %q", secretField)
|
||||
}
|
||||
}
|
||||
if supported == nil {
|
||||
t.Fatalf("GET omitted supported source: %s", get.Body.String())
|
||||
}
|
||||
for field, want := range map[string]any{"source_key": "yahoo_finance", "supported": true, "operational": true} {
|
||||
if supported[field] != want {
|
||||
t.Errorf("supported source %s=%v, want %v; row=%v", field, supported[field], want, supported)
|
||||
}
|
||||
}
|
||||
put := httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodPut, "/api/admin/sources/old-id", bytes.NewBufferString(`{"enabled":true,"article_limit":99}`))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(put, req)
|
||||
if put.Code != http.StatusConflict {
|
||||
t.Errorf("PUT historical source status=%d body=%s, want 409 source_not_supported", put.Code, put.Body.String())
|
||||
}
|
||||
if !bytes.Contains(put.Body.Bytes(), []byte("source_not_supported")) {
|
||||
t.Errorf("PUT error body=%s, want source_not_supported", put.Body.String())
|
||||
}
|
||||
var enabled bool
|
||||
var cap int
|
||||
if err := db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE id='old-id'`).Scan(&enabled, &cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !enabled || cap != 42 {
|
||||
t.Fatalf("rejected update mutated historical row enabled=%v cap=%d", enabled, cap)
|
||||
}
|
||||
}
|
||||
@ -36,11 +36,11 @@ func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *te
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title')`,
|
||||
`CREATE TABLE user_assets(id UUID PRIMARY KEY,user_id UUID,symbol TEXT,name TEXT,figi TEXT NULL,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
|
||||
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID REFERENCES users(id),content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ)`,
|
||||
`INSERT INTO users(id) VALUES('00000000-0000-0000-0000-000000000001')`,
|
||||
`INSERT INTO sources(id,name,type,enabled) VALUES('00000000-0000-0000-0000-000000000002','Fixture','fixture',true)`,
|
||||
`INSERT INTO sources(id,name,type,enabled,source_key) VALUES('00000000-0000-0000-0000-000000000002','Fixture','fixture',true,'yahoo_finance')`,
|
||||
`CREATE TABLE summary_generations(id UUID PRIMARY KEY,user_id UUID,summary_id UUID REFERENCES summaries(id),outcome JSONB NOT NULL,created_at TIMESTAMPTZ)`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
@ -48,7 +48,7 @@ func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *te
|
||||
}
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{"fixture": memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
|
||||
result, err := uc.Generate(context.Background(), "00000000-0000-0000-0000-000000000001")
|
||||
if err != nil || result.Summary == nil || result.Outcome.Status != "succeeded" {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
|
||||
@ -233,7 +233,16 @@ func (h *Handler) ListSources(c *gin.Context) {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.OK(c, sources)
|
||||
type sourceResponse struct {
|
||||
models.Source
|
||||
Supported bool `json:"supported"`
|
||||
Operational bool `json:"operational"`
|
||||
}
|
||||
result := make([]sourceResponse, 0, len(sources))
|
||||
for _, source := range sources {
|
||||
result = append(result, sourceResponse{Source: source, Supported: source.Supported(), Operational: source.Operational()})
|
||||
}
|
||||
httputil.OK(c, result)
|
||||
}
|
||||
|
||||
type updateSourceRequest struct {
|
||||
@ -248,6 +257,14 @@ func (h *Handler) UpdateSource(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if err := h.repo.UpdateSource(c.Param("id"), req.Enabled, req.ArticleLimit); err != nil {
|
||||
if errors.Is(err, models.ErrSourceNotSupported) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "source_not_supported"})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
httputil.NotFound(c)
|
||||
return
|
||||
}
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
@ -0,0 +1,3 @@
|
||||
-- Historical rows stay preserved and disabled; rollback must not reactivate
|
||||
-- sources for which the previous enabled state is no longer known.
|
||||
ALTER TABLE sources DROP COLUMN source_key;
|
||||
@ -0,0 +1,30 @@
|
||||
-- One SQL statement: validation, DDL and backfill share a transaction even when
|
||||
-- executed without a caller-owned transaction. Never merge historical sources.
|
||||
DO $migration$
|
||||
BEGIN
|
||||
LOCK TABLE sources IN ACCESS EXCLUSIVE MODE;
|
||||
IF (SELECT count(*) FROM sources WHERE type = 'stocktwits'
|
||||
AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'yahoo finance') <> 1 THEN
|
||||
RAISE EXCEPTION 'source_identity_invalid: expected exactly one Yahoo Finance';
|
||||
END IF;
|
||||
IF (SELECT count(*) FROM sources WHERE type = 'bloomberg'
|
||||
AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'bloomberg') <> 1 THEN
|
||||
RAISE EXCEPTION 'source_identity_invalid: expected exactly one Bloomberg';
|
||||
END IF;
|
||||
IF (SELECT count(*) FROM sources WHERE type = 'watcherguru'
|
||||
AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'watcher.guru') <> 1 THEN
|
||||
RAISE EXCEPTION 'source_identity_invalid: expected exactly one Watcher.Guru';
|
||||
END IF;
|
||||
|
||||
ALTER TABLE sources ADD COLUMN source_key TEXT NULL
|
||||
CONSTRAINT sources_source_key_check CHECK (source_key IN ('yahoo_finance', 'bloomberg', 'watcher_guru'));
|
||||
CREATE UNIQUE INDEX sources_source_key_unique ON sources(source_key) WHERE source_key IS NOT NULL;
|
||||
|
||||
UPDATE sources SET source_key = CASE
|
||||
WHEN type = 'stocktwits' AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'yahoo finance' THEN 'yahoo_finance'
|
||||
WHEN type = 'bloomberg' AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'bloomberg' THEN 'bloomberg'
|
||||
WHEN type = 'watcherguru' AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'watcher.guru' THEN 'watcher_guru'
|
||||
ELSE NULL END;
|
||||
UPDATE sources SET enabled = false WHERE source_key IS NULL;
|
||||
END
|
||||
$migration$;
|
||||
@ -0,0 +1,81 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSourceMigrationDirectExecFailureLeavesSchemaAndRowsUnchangedPostgres(t *testing.T) {
|
||||
db, cleanup := ticket13Database(t)
|
||||
defer cleanup()
|
||||
// Caller intentionally supplies no transaction. The migration must own its
|
||||
// atomicity, as when a migration driver submits a single SQL statement.
|
||||
for _, row := range ticket13HistoricalRows() {
|
||||
if row.typ == "bloomberg" {
|
||||
continue
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
beforeSchema := ticket13SchemaSnapshot(t, db)
|
||||
beforeRows := ticket13ReadSources(t, db)
|
||||
up, err := os.ReadFile("000015_source_allowlist.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(up)); err == nil {
|
||||
t.Fatal("missing exact Bloomberg identity accepted")
|
||||
}
|
||||
if after := ticket13SchemaSnapshot(t, db); after != beforeSchema {
|
||||
t.Fatal("direct Exec changed schema on failure")
|
||||
}
|
||||
if after := ticket13ReadSources(t, db); !reflect.DeepEqual(after, beforeRows) {
|
||||
t.Fatal("direct Exec changed rows on failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceMigrationNormalizesNamesWithoutFuzzyMatchingOrRewritingOutcomesPostgres(t *testing.T) {
|
||||
db, cleanup := ticket13Database(t)
|
||||
defer cleanup()
|
||||
for _, row := range []ticket13SourceRow{
|
||||
{"y", "\tYaHoO \n Finance \t", "stocktwits", true, 83},
|
||||
{"b", " Bloomberg ", "bloomberg", false, 77},
|
||||
{"w", " watcher.guru ", "watcherguru", true, 64},
|
||||
{"fake-y", "Yahoo Finance Daily", "stocktwits", true, 42},
|
||||
{"wrong-type", "Yahoo Finance", "reuters", true, 31},
|
||||
{"wrong-name", "StockTwits", "stocktwits", true, 32},
|
||||
{"no-dot", "Watcher Guru", "watcherguru", true, 33},
|
||||
} {
|
||||
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := db.Exec(`CREATE TABLE summary_generations(id TEXT PRIMARY KEY,outcome JSONB); INSERT INTO summary_generations VALUES('old','{"source_stats":[{"source_id":"wrong-name","source_type":"stocktwits","selected":4}],"status":"succeeded"}')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var before, after string
|
||||
if err := db.QueryRow(`SELECT outcome::text FROM summary_generations WHERE id='old'`).Scan(&before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
applyTicket13(t, db)
|
||||
var targets, unsupported int
|
||||
if err := db.QueryRow(`SELECT count(*) FROM sources WHERE source_key IS NOT NULL`).Scan(&targets); err != nil || targets != 3 {
|
||||
t.Fatalf("target count=%d err=%v", targets, err)
|
||||
}
|
||||
if err := db.QueryRow(`SELECT count(*) FROM sources WHERE source_key IS NULL AND enabled=false`).Scan(&unsupported); err != nil || unsupported != 4 {
|
||||
t.Fatalf("unsupported count=%d err=%v", unsupported, err)
|
||||
}
|
||||
var enabled bool
|
||||
var cap int
|
||||
if err := db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE id='b'`).Scan(&enabled, &cap); err != nil || enabled || cap != 77 {
|
||||
t.Fatalf("recognized disabled/cap state changed: %v %d %v", enabled, cap, err)
|
||||
}
|
||||
if err := db.QueryRow(`SELECT outcome::text FROM summary_generations WHERE id='old'`).Scan(&after); err != nil || after != before {
|
||||
t.Fatal("historical outcome rewritten", err)
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES('duplicate-key','x','x',true,20,'yahoo_finance')`); err == nil {
|
||||
t.Fatal("duplicate source_key accepted")
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,267 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
// These cases intentionally exercise the historical source identity pairs:
|
||||
// Yahoo's type is stocktwits, while the actual StockTwits row has a different name.
|
||||
func TestSourceAllowlistMigrationBackfillsOnlyExactTargetsPostgres(t *testing.T) {
|
||||
db, cleanup := ticket13Database(t)
|
||||
defer cleanup()
|
||||
for _, row := range []struct {
|
||||
id, name, typ string
|
||||
enabled bool
|
||||
cap int
|
||||
}{
|
||||
{"yahoo-id", "Yahoo Finance", "stocktwits", true, 83},
|
||||
{"bloomberg-id", "Bloomberg", "bloomberg", false, 77},
|
||||
{"watcher-id", "Watcher.Guru", "watcherguru", true, 64},
|
||||
{"stocktwits-id", "StockTwits", "stocktwits", true, 31},
|
||||
{"reuters-id", "Reuters", "reuters", true, 42},
|
||||
} {
|
||||
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO articles(id,source_id,title,url) VALUES('article-yahoo','yahoo-id','historic','https://fixture.invalid/yahoo'),('article-stocktwits','stocktwits-id','historic','https://fixture.invalid/stocktwits')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
applyTicket13(t, db)
|
||||
want := map[string]struct {
|
||||
key string
|
||||
enabled bool
|
||||
cap int
|
||||
}{
|
||||
"yahoo-id": {"yahoo_finance", true, 83}, "bloomberg-id": {"bloomberg", false, 77}, "watcher-id": {"watcher_guru", true, 64},
|
||||
"stocktwits-id": {"", false, 31}, "reuters-id": {"", false, 42},
|
||||
}
|
||||
for id, expected := range want {
|
||||
var key sql.NullString
|
||||
var enabled bool
|
||||
var cap int
|
||||
if err := db.QueryRow(`SELECT source_key,enabled,article_limit FROM sources WHERE id=$1`, id).Scan(&key, &enabled, &cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actualKey := ""
|
||||
if key.Valid {
|
||||
actualKey = key.String
|
||||
}
|
||||
if actualKey != expected.key || enabled != expected.enabled || cap != expected.cap {
|
||||
t.Errorf("%s => key=%q enabled=%v cap=%d, want key=%q enabled=%v cap=%d", id, actualKey, enabled, cap, expected.key, expected.enabled, expected.cap)
|
||||
}
|
||||
}
|
||||
for _, id := range []string{"article-yahoo", "article-stocktwits"} {
|
||||
var count int
|
||||
if err := db.QueryRow(`SELECT count(*) FROM articles WHERE id=$1`, id).Scan(&count); err != nil || count != 1 {
|
||||
t.Errorf("historical FK article %s count=%d err=%v", id, count, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceAllowlistMigrationFailsAtomicallyForMissingOrAmbiguousTargetPostgres(t *testing.T) {
|
||||
targets := []ticket13SourceRow{{"yahoo-id", "Yahoo Finance", "stocktwits", true, 83}, {"bloomberg-id", "Bloomberg", "bloomberg", false, 77}, {"watcher-id", "Watcher.Guru", "watcherguru", true, 64}}
|
||||
cases := []struct {
|
||||
name string
|
||||
mutate func([]ticket13SourceRow) []ticket13SourceRow
|
||||
}{}
|
||||
for i, target := range targets {
|
||||
missingID := target.id
|
||||
cases = append(cases, struct {
|
||||
name string
|
||||
mutate func([]ticket13SourceRow) []ticket13SourceRow
|
||||
}{
|
||||
name: "missing required " + target.name,
|
||||
mutate: func(rows []ticket13SourceRow) []ticket13SourceRow {
|
||||
out := []ticket13SourceRow{}
|
||||
for _, row := range rows {
|
||||
if row.id != missingID {
|
||||
out = append(out, row)
|
||||
}
|
||||
}
|
||||
return out
|
||||
},
|
||||
})
|
||||
duplicate := target
|
||||
duplicate.id = fmt.Sprintf("duplicate-%d", i)
|
||||
duplicate.enabled, duplicate.cap = false, 19
|
||||
cases = append(cases, struct {
|
||||
name string
|
||||
mutate func([]ticket13SourceRow) []ticket13SourceRow
|
||||
}{
|
||||
name: "duplicate exact identity " + target.name,
|
||||
mutate: func(rows []ticket13SourceRow) []ticket13SourceRow { return append(rows, duplicate) },
|
||||
})
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
db, cleanup := ticket13Database(t)
|
||||
defer cleanup()
|
||||
rows := tc.mutate(ticket13HistoricalRows())
|
||||
for _, row := range rows {
|
||||
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO articles(id,source_id,title,url) SELECT 'article-'||id,id,'fixture','https://fixture.invalid/'||id FROM sources`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
beforeSchema := ticket13SchemaSnapshot(t, db)
|
||||
beforeRows := ticket13ReadSources(t, db)
|
||||
beforeFKs := ticket13ReadArticleSources(t, db)
|
||||
err := applyTicket13Err(db)
|
||||
if err == nil {
|
||||
t.Fatal("migration succeeded without exactly one target source")
|
||||
}
|
||||
if strings.Contains(err.Error(), "read migration 000015") {
|
||||
t.Errorf("%s: atomic rollback cannot be exercised because migration 000015 is absent: %v", tc.name, err)
|
||||
}
|
||||
if after := ticket13SchemaSnapshot(t, db); after != beforeSchema {
|
||||
t.Errorf("failed migration changed schema\nbefore: %s\nafter: %s", beforeSchema, after)
|
||||
}
|
||||
if after := ticket13ReadSources(t, db); !reflect.DeepEqual(after, beforeRows) {
|
||||
t.Errorf("failed migration changed source data\nbefore: %#v\nafter: %#v", beforeRows, after)
|
||||
}
|
||||
if after := ticket13ReadArticleSources(t, db); !reflect.DeepEqual(after, beforeFKs) {
|
||||
t.Errorf("failed migration changed article/source FK rows\nbefore: %#v\nafter: %#v", beforeFKs, after)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type ticket13SourceRow struct {
|
||||
id, name, typ string
|
||||
enabled bool
|
||||
cap int
|
||||
}
|
||||
|
||||
func ticket13HistoricalRows() []ticket13SourceRow {
|
||||
return []ticket13SourceRow{{"yahoo-id", "Yahoo Finance", "stocktwits", true, 83}, {"bloomberg-id", "Bloomberg", "bloomberg", false, 77}, {"watcher-id", "Watcher.Guru", "watcherguru", true, 64}, {"stocktwits-id", "StockTwits", "stocktwits", true, 31}, {"reuters-id", "Reuters", "reuters", true, 42}}
|
||||
}
|
||||
func ticket13SchemaSnapshot(t *testing.T, db *sql.DB) string {
|
||||
t.Helper()
|
||||
parts := []string{}
|
||||
for _, q := range []string{`SELECT column_name||':'||data_type||':'||is_nullable||':'||COALESCE(column_default,'') FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='sources' ORDER BY ordinal_position`, `SELECT conname||':'||pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid='sources'::regclass ORDER BY conname`, `SELECT indexname||':'||indexdef FROM pg_indexes WHERE schemaname=current_schema() AND tablename='sources' ORDER BY indexname`} {
|
||||
rows, err := db.Query(q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var value string
|
||||
if err := rows.Scan(&value); err != nil {
|
||||
rows.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts = append(parts, value)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows.Close()
|
||||
}
|
||||
return strings.Join(parts, "\n")
|
||||
}
|
||||
func ticket13ReadSources(t *testing.T, db *sql.DB) []ticket13SourceRow {
|
||||
t.Helper()
|
||||
rows, err := db.Query(`SELECT id,name,type,enabled,article_limit FROM sources ORDER BY id`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []ticket13SourceRow{}
|
||||
for rows.Next() {
|
||||
var row ticket13SourceRow
|
||||
if err := rows.Scan(&row.id, &row.name, &row.typ, &row.enabled, &row.cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result = append(result, row)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
func ticket13ReadArticleSources(t *testing.T, db *sql.DB) []string {
|
||||
t.Helper()
|
||||
rows, err := db.Query(`SELECT id||':'||source_id FROM articles ORDER BY id`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []string{}
|
||||
for rows.Next() {
|
||||
var value string
|
||||
if err := rows.Scan(&value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result = append(result, value)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ticket13Database(t *testing.T) (*sql.DB, func()) {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
if os.Getenv("TEST_DATABASE_REQUIRED") == "1" {
|
||||
t.Fatal("TEST_DATABASE_REQUIRED=1 but TEST_DATABASE_URL is empty")
|
||||
}
|
||||
t.Skip("TEST_DATABASE_URL absent: isolated PostgreSQL required")
|
||||
}
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("ticket13_sources_%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)
|
||||
}
|
||||
for _, q := range []string{`CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT NOT NULL,type TEXT NOT NULL,enabled BOOLEAN NOT NULL,article_limit INTEGER NOT NULL DEFAULT 20)`, `CREATE TABLE articles(id TEXT PRIMARY KEY,source_id TEXT NOT NULL REFERENCES sources(id),title TEXT NOT NULL,url TEXT NOT NULL UNIQUE)`} {
|
||||
if _, err = db.Exec(q); err != nil {
|
||||
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
||||
_ = db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return db, func() { _, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`); _ = db.Close() }
|
||||
}
|
||||
func applyTicket13(t *testing.T, db *sql.DB) {
|
||||
t.Helper()
|
||||
if err := applyTicket13Err(db); err != nil {
|
||||
t.Fatalf("apply source allowlist migration: %v", err)
|
||||
}
|
||||
}
|
||||
func applyTicket13Err(db *sql.DB) error {
|
||||
up, err := os.ReadFile("000015_source_allowlist.up.sql")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migration 000015: %w", err)
|
||||
}
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(string(up)); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@ -117,14 +117,14 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
stats := map[string]int{}
|
||||
partial := false
|
||||
for _, source := range input.Sources {
|
||||
if !source.Enabled {
|
||||
if !source.Operational() {
|
||||
continue
|
||||
}
|
||||
stat := SourceStat{SourceID: source.ID, SourceType: source.Type, ArticleLimit: source.ArticleLimit, Status: "ok"}
|
||||
if stat.ArticleLimit <= 0 {
|
||||
stat.ArticleLimit = 20
|
||||
}
|
||||
feed := u.Scrapers[source.Type]
|
||||
feed := u.Scrapers[*source.SourceKey]
|
||||
var articles []scraper.Article
|
||||
if feed == nil {
|
||||
err = fmt.Errorf("unavailable")
|
||||
|
||||
@ -92,9 +92,9 @@ func (s *contractSummarizer) Summarize(_ context.Context, language string, _ []m
|
||||
|
||||
func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testing.T) {
|
||||
alphaID, betaID := "user-alpha", "user-beta"
|
||||
alphaSource := models.Source{ID: "alpha-feed", Type: "alpha", Enabled: true, ArticleLimit: 5}
|
||||
betaSource := models.Source{ID: "beta-feed", Type: "beta", Enabled: true, ArticleLimit: 5}
|
||||
disabled := models.Source{ID: "disabled-feed", Type: "disabled", Enabled: false, ArticleLimit: 5}
|
||||
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"}
|
||||
@ -107,7 +107,7 @@ func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testin
|
||||
},
|
||||
saved: map[string][]GenerationRecord{},
|
||||
}
|
||||
useCase := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"alpha": alphaScraper, "beta": betaScraper, "disabled": disabledScraper}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) }})
|
||||
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 {
|
||||
@ -148,8 +148,8 @@ func TestUseCasePreservesLayaOrderThenAppliesPerSourceAndGlobalCaps(t *testing.T
|
||||
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", Enabled: true, ArticleLimit: 1}, {ID: "b", Type: "b", Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"a": feedA, "b": feedB}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
||||
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)
|
||||
}
|
||||
@ -176,10 +176,10 @@ func TestUseCaseNoResultsInvalidLayaAndSummaryFailurePersistNoSummary(t *testing
|
||||
}
|
||||
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", Enabled: true, ArticleLimit: 10}}}}, saved: map[string][]GenerationRecord{}}
|
||||
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{"s": &contractScraper{name: "s", articles: tt.articles}}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
||||
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)
|
||||
@ -199,8 +199,8 @@ func TestUseCasePartialSourceFailureCanSummarizeRemainingSources(t *testing.T) {
|
||||
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", Enabled: true, ArticleLimit: 5}, {ID: "bad", Type: "bad", Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"good": good, "bad": bad}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
||||
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)
|
||||
@ -221,8 +221,8 @@ func TestUseCaseOutcomeContainsAggregateCountsWithoutArticleIdentifiers(t *testi
|
||||
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", Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"source": feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
||||
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)
|
||||
@ -245,8 +245,8 @@ 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", Enabled: true, ArticleLimit: 4}}}}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"source": feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
||||
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)
|
||||
@ -267,3 +267,5 @@ func candidateTitles(candidates []Candidate) []string {
|
||||
func contains(value, needle string) bool {
|
||||
return len(needle) > 0 && strings.Contains(value, needle)
|
||||
}
|
||||
|
||||
func testSourceKey(key string) *string { return &key }
|
||||
|
||||
@ -52,11 +52,12 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users (id UUID PRIMARY KEY, language TEXT NOT NULL DEFAULT 'fr', ranking_mode TEXT NOT NULL DEFAULT 'title')`,
|
||||
`CREATE TABLE user_assets (id UUID PRIMARY KEY, user_id UUID NOT NULL, symbol VARCHAR(20) NOT NULL, name TEXT NOT NULL DEFAULT '', figi TEXT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), article_limit INT NOT NULL DEFAULT 20)`,
|
||||
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), article_limit INT NOT NULL DEFAULT 20, source_key TEXT)`,
|
||||
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
|
||||
`INSERT INTO users(id,language,ranking_mode) VALUES ('` + userID + `','fr','title')`,
|
||||
`INSERT INTO user_assets(id,user_id,symbol,name,figi) VALUES ('00000000-0000-0000-0000-000000000411','` + userID + `','LEGACY','Historic asset',NULL)`,
|
||||
`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES ('00000000-0000-0000-0000-000000000421','test source','ticket4',TRUE,20)`,
|
||||
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000421','test source','ticket4',TRUE,20,'yahoo_finance')`,
|
||||
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000422','Historic enabled','reuters',TRUE,42,NULL),('00000000-0000-0000-0000-000000000423','Disabled target','bloomberg',FALSE,77,'bloomberg')`,
|
||||
`INSERT INTO settings(key,value) VALUES ('summary_max_articles','50')`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
@ -68,6 +69,9 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("load legacy generation input from PostgreSQL: %v", err)
|
||||
}
|
||||
if len(input.Sources) != 1 || input.Sources[0].SourceKey == nil || *input.Sources[0].SourceKey != models.SourceYahooFinance || input.Sources[0].ArticleLimit != 20 {
|
||||
t.Fatalf("LoadUserInput must exclude unsupported/disabled sources, preserving target caps: %+v", input.Sources)
|
||||
}
|
||||
if len(input.Assets) != 1 || input.Assets[0].Symbol != "LEGACY" || input.Assets[0].Name != "Historic asset" {
|
||||
t.Fatalf("loaded legacy asset=%+v, want symbol/name preserved", input.Assets)
|
||||
}
|
||||
@ -84,7 +88,7 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
|
||||
fakeRepository := &contractRepository{inputs: map[string]UserInput{userID: input}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{
|
||||
Repository: fakeRepository,
|
||||
Scrapers: map[string]scraper.Scraper{"ticket4": feed},
|
||||
Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed},
|
||||
Ranker: ranker,
|
||||
Summarizer: summarizer,
|
||||
Clock: func() time.Time { return time.Unix(1, 0).UTC() },
|
||||
|
||||
@ -33,7 +33,7 @@ func (r RepositoryAdapter) LoadUserInput(ctx context.Context, id string) (UserIn
|
||||
if value == "" {
|
||||
limit = 50
|
||||
}
|
||||
return UserInput{Language: p.Language, RankingMode: p.RankingMode, GlobalLimit: limit, Assets: assets, Sources: sources}, nil
|
||||
return UserInput{Language: p.Language, RankingMode: p.RankingMode, GlobalLimit: limit, Assets: assets, Sources: models.OperationalSources(sources)}, nil
|
||||
}
|
||||
func (r RepositoryAdapter) SaveGeneration(ctx context.Context, id string, record GenerationRecord) error {
|
||||
payload, err := json.Marshal(record.Outcome)
|
||||
|
||||
@ -0,0 +1,49 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t *testing.T) {
|
||||
var sources []models.Source
|
||||
if err := json.Unmarshal([]byte(`[
|
||||
{"id":"y","name":"Yahoo Finance","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":20},
|
||||
{"id":"b","name":"Bloomberg","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":20},
|
||||
{"id":"w","name":"Watcher.Guru","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":20},
|
||||
{"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":20},
|
||||
{"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":20}
|
||||
]`), &sources); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"user": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "SPX"}}, Sources: sources}}, saved: map[string][]GenerationRecord{}}
|
||||
feeds := map[string]*contractScraper{}
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru", "stocktwits", "reuters"} {
|
||||
feeds[key] = &contractScraper{name: key, articles: []scraper.Article{{Title: key}}}
|
||||
}
|
||||
scrapers := map[string]scraper.Scraper{}
|
||||
for key, feed := range feeds {
|
||||
scrapers[key] = feed
|
||||
}
|
||||
result, err := NewUseCase(Dependencies{Repository: repo, Scrapers: scrapers, Ranker: &contractRanker{}, Summarizer: &contractSummarizer{}}).Generate(context.Background(), "user")
|
||||
if err != nil || result.Summary == nil {
|
||||
t.Fatalf("generation result=%+v err=%v", result, err)
|
||||
}
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} {
|
||||
if len(feeds[key].calls) != 1 {
|
||||
t.Errorf("target %s calls=%d, want one", key, len(feeds[key].calls))
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"stocktwits", "reuters"} {
|
||||
if len(feeds[key].calls) != 0 {
|
||||
t.Errorf("unsupported enabled source %s was invoked %d times", key, len(feeds[key].calls))
|
||||
}
|
||||
}
|
||||
if result.Outcome.TotalCandidates != 3 {
|
||||
t.Errorf("target candidate count=%d, want 3", result.Outcome.TotalCandidates)
|
||||
}
|
||||
}
|
||||
@ -31,6 +31,7 @@ type UserAsset struct {
|
||||
}
|
||||
|
||||
type Source struct {
|
||||
SourceKey *string `json:"source_key"`
|
||||
ArticleLimit int `json:"article_limit"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
|
||||
@ -130,7 +130,7 @@ func (r *Repository) CountAdmins() (int, error) {
|
||||
// ── Sources ────────────────────────────────────────────────────────────────
|
||||
|
||||
func (r *Repository) ListSources() ([]Source, error) {
|
||||
rows, err := r.db.Query(`SELECT id, name, type, enabled, created_at, article_limit FROM sources ORDER BY name`)
|
||||
rows, err := r.db.Query(`SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources ORDER BY name`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -138,35 +138,44 @@ func (r *Repository) ListSources() ([]Source, error) {
|
||||
var sources []Source
|
||||
for rows.Next() {
|
||||
var s Source
|
||||
if err := rows.Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit); err != nil {
|
||||
if err := rows.Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sources = append(sources, s)
|
||||
}
|
||||
return sources, nil
|
||||
return sources, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
|
||||
s := &Source{}
|
||||
err := r.db.QueryRow(`
|
||||
SELECT id, name, type, enabled, created_at, article_limit FROM sources WHERE type=$1`, sourceType,
|
||||
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit)
|
||||
SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources WHERE type=$1 AND source_key IN ('yahoo_finance','bloomberg','watcher_guru')`, sourceType,
|
||||
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return s, err
|
||||
}
|
||||
|
||||
var ErrSourceNotSupported = errors.New("source_not_supported")
|
||||
|
||||
func (r *Repository) UpdateSource(id string, enabled bool, articleLimit *int) error {
|
||||
result, err := r.db.Exec(`UPDATE sources SET enabled=$1, article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, articleLimit, id)
|
||||
tx, err := r.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err == nil && count == 0 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var key *string
|
||||
if err = tx.QueryRow(`SELECT source_key FROM sources WHERE id=$1 FOR UPDATE`, id).Scan(&key); err != nil {
|
||||
return err
|
||||
}
|
||||
if key == nil || !SupportedSourceKey(*key) {
|
||||
return ErrSourceNotSupported
|
||||
}
|
||||
if _, err = tx.Exec(`UPDATE sources SET enabled=$1,article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, articleLimit, id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// ── Scrape Credentials ─────────────────────────────────────────────────────
|
||||
|
||||
26
backend/internal/models/source_support.go
Normal file
26
backend/internal/models/source_support.go
Normal file
@ -0,0 +1,26 @@
|
||||
package models
|
||||
|
||||
const (
|
||||
SourceYahooFinance = "yahoo_finance"
|
||||
SourceBloomberg = "bloomberg"
|
||||
SourceWatcherGuru = "watcher_guru"
|
||||
)
|
||||
|
||||
func SupportedSourceKey(key string) bool {
|
||||
switch key {
|
||||
case SourceYahooFinance, SourceBloomberg, SourceWatcherGuru:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s Source) Supported() bool { return s.SourceKey != nil && SupportedSourceKey(*s.SourceKey) }
|
||||
func (s Source) Operational() bool { return s.Enabled && s.Supported() }
|
||||
func OperationalSources(sources []Source) []Source {
|
||||
result := []Source{}
|
||||
for _, source := range sources {
|
||||
if source.Operational() {
|
||||
result = append(result, source)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
24
backend/internal/models/source_support_test.go
Normal file
24
backend/internal/models/source_support_test.go
Normal file
@ -0,0 +1,24 @@
|
||||
package models
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSourceSupportUsesOnlyCanonicalKeyAndPersistedEnabled(t *testing.T) {
|
||||
yahoo := SourceYahooFinance
|
||||
unknown := "reuters"
|
||||
sources := []Source{
|
||||
{ID: "supported", Type: "stocktwits", SourceKey: &yahoo, Enabled: true, ArticleLimit: 83},
|
||||
{ID: "disabled", SourceKey: &yahoo, Enabled: false, ArticleLimit: 77},
|
||||
{ID: "legacy", Type: "stocktwits", Name: "Yahoo Finance", Enabled: true, ArticleLimit: 42},
|
||||
{ID: "unknown", SourceKey: &unknown, Enabled: true, ArticleLimit: 31},
|
||||
}
|
||||
filtered := OperationalSources(sources)
|
||||
if len(filtered) != 1 || filtered[0].ID != "supported" || filtered[0].ArticleLimit != 83 {
|
||||
t.Fatalf("filtered=%v", filtered)
|
||||
}
|
||||
if !sources[2].Enabled || sources[2].Supported() || sources[2].Operational() {
|
||||
t.Fatal("legacy enabled must remain persisted, without operational support")
|
||||
}
|
||||
if !sources[1].Supported() || sources[1].Operational() {
|
||||
t.Fatal("disabled target support/operational mismatch")
|
||||
}
|
||||
}
|
||||
74
backend/internal/scheduler/source_allowlist_ticket13_test.go
Normal file
74
backend/internal/scheduler/source_allowlist_ticket13_test.go
Normal file
@ -0,0 +1,74 @@
|
||||
package scheduler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
type ticket13Repository struct{ input generation.UserInput }
|
||||
type ticket13Users struct{}
|
||||
|
||||
func (ticket13Users) ListUsers() ([]models.User, error) { return []models.User{{ID: "one-user"}}, nil }
|
||||
func (r ticket13Repository) LoadUserInput(context.Context, string) (generation.UserInput, error) {
|
||||
return r.input, nil
|
||||
}
|
||||
func (ticket13Repository) SaveGeneration(context.Context, string, generation.GenerationRecord) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type ticket13Ranker struct{}
|
||||
|
||||
func (ticket13Ranker) Rank(_ context.Context, _ string, _ []models.UserAsset, c []generation.Candidate) ([]generation.Candidate, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type ticket13Summary struct{}
|
||||
|
||||
func (ticket13Summary) Summarize(context.Context, string, []models.UserAsset, []generation.Candidate) (string, error) {
|
||||
return "safe aggregate", nil
|
||||
}
|
||||
|
||||
type ticket13Feed struct{ calls int }
|
||||
|
||||
func (f *ticket13Feed) Name() string { return "fake" }
|
||||
func (f *ticket13Feed) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
||||
f.calls++
|
||||
return []scraper.Article{{Title: "fixture"}}, nil
|
||||
}
|
||||
|
||||
func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *testing.T) {
|
||||
var sources []models.Source
|
||||
if err := json.Unmarshal([]byte(`[
|
||||
{"id":"y","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":10},
|
||||
{"id":"b","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":10},
|
||||
{"id":"w","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":10},
|
||||
{"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":10},
|
||||
{"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":10}]`), &sources); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
feeds := map[string]*ticket13Feed{}
|
||||
scrapers := map[string]scraper.Scraper{}
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru", "stocktwits", "reuters"} {
|
||||
f := &ticket13Feed{}
|
||||
feeds[key] = f
|
||||
scrapers[key] = f
|
||||
}
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: ticket13Repository{generation.UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "SPX"}}, Sources: sources}}, Scrapers: scrapers, Ranker: ticket13Ranker{}, Summarizer: ticket13Summary{}})
|
||||
s := &Scheduler{users: ticket13Users{}, generationUseCase: uc}
|
||||
s.run()
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} {
|
||||
if feeds[key].calls != 1 {
|
||||
t.Errorf("scheduled supported source %s calls=%d, want 1", key, feeds[key].calls)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"stocktwits", "reuters"} {
|
||||
if feeds[key].calls != 0 {
|
||||
t.Errorf("scheduled legacy source %s was called %d times", key, feeds[key].calls)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -30,11 +30,12 @@ Les migrations initiales créent toujours les tables historiques pour les ancien
|
||||
| `000011_user_preferences` | Ajoute `users.language` (`fr`/`en`, défaut `fr`) et `ranking_mode` (`title`/`title_content`, défaut `title`), non nuls avec contraintes ; anciennes lignes couvertes par les défauts. |
|
||||
| `000012_article_limits` | Ajoute `sources.article_limit`, défaut 20, contrainte 1–200. Ne réécrit pas `summary_max_articles`, y compris une valeur historique supérieure à 500. |
|
||||
| `000013_summary_generations` | Ajoute les références compte/synthèse, bilan JSONB et date avec index par compte/date. Aucun champ d’article ou prompt. |
|
||||
| `000015_source_allowlist` | Un bloc SQL atomique valide exactement une identité par source cible avant DDL/backfill. Colonne nullable et unicité partielle ; IDs, états des cibles, plafonds, FKs et anciens bilans conservés. Absence/doublon : échec sans changement des sources ou de leur schéma. |
|
||||
|
||||
Les migrations s’appliquent au démarrage backend. Les scripts `down` 11–13 enlèvent les colonnes/tables ajoutées et perdent donc les données de ces fonctionnalités ; ils ne constituent pas une procédure de rollback sans perte. Sauvegarder avant mise à jour et tester la restauration.
|
||||
|
||||
## Frontières conservées
|
||||
|
||||
Les adapters de récupération fournis et le service Node ne sont pas redéfinis. Yahoo Finance utilise historiquement le type `stocktwits`. Reuters reste présent dans les sources initiales ; pour la cible Yahoo Finance/Bloomberg/Watcher Guru, désactiver Reuters en administration. La recherche backend utilise désormais le port `indices.IndexSearcher` et l’adapter OpenFIGI v3, avec DTO transitoire `{name,symbol,figi}` ; aucun catalogue n’est persisté. Le raccordement UI relève du ticket #4. Les conditions et limites du fournisseur restent applicables.
|
||||
Les adapters de récupération fournis et le service Node ne sont pas redéfinis. Yahoo Finance utilise historiquement le type `stocktwits`. La migration 000015 attribue les clés `yahoo_finance`, `bloomberg`, `watcher_guru` uniquement aux paires type/nom historiques exactes (nom normalisé pour casse/espaces), puis désactive les sources sans clé, dont Reuters et la vraie StockTwits. Les sources exclues restent conservées et non modifiables via API (409 `source_not_supported`). Le dispatch des adapters et le filtrage des générations manuelles/planifiées utilisent `source_key`, jamais le type legacy seul. La recherche backend utilise désormais le port `indices.IndexSearcher` et l’adapter OpenFIGI v3, avec DTO transitoire `{name,symbol,figi}` ; aucun catalogue n’est persisté. Le raccordement UI relève du ticket #4. Les conditions et limites du fournisseur restent applicables.
|
||||
|
||||
Le frontend protège ses pages, mais l’autorisation reste côté API. La PWA utilise le précache statique et supprime `api-cache` à l’activation ; aucune stratégie runtime `/api/` n’est configurée. Cela ne fournit pas de mode hors ligne pour les données privées.
|
||||
|
||||
@ -34,7 +34,9 @@ Laya désigne le rôle de classement. Dans l’administration des fournisseurs I
|
||||
|
||||
Le Compose fournit un service Ollama sans configuration GPU, joignable depuis le backend à `http://ollama:11434`. Aucun modèle n’est préchargé. Choisir/installer explicitement un modèle via les fonctions Ollama disponibles ou une instance déjà administrée. Dimensionner RAM, contexte et taille des lots pour le CPU ; il n’existe pas de variable backend `LAYA_MODEL` ou `LAYA_CPU`. Le provider Ollama transmet `format: json` pour le classement. Les limites de ressources et le choix d’un modèle CPU relèvent de l’installation.
|
||||
|
||||
Sources configurées initialement : Bloomberg, Yahoo Finance (`stocktwits` dans le contrat historique), Reuters et Watcher.Guru. Seules les sources activées sont collectées par `Scrape`. Désactiver Reuters pour se limiter aux trois sources produit attendues. Les accès Bloomberg restent consommés par son adapter ; conserver la surface Credentials. Ne pas lancer un récupérateur réel pour valider les suites de tests.
|
||||
Après la migration 000015, seules Yahoo Finance (`yahoo_finance`), Bloomberg (`bloomberg`) et Watcher.Guru (`watcher_guru`) peuvent participer. Le type historique Yahoo `stocktwits` reste stocké, mais ne décide plus du dispatch. Les autres lignes historiques, dont Reuters et la vraie StockTwits, sont conservées/désactivées et leur modification admin renvoie 409 `source_not_supported`. Le GET expose la clé, `supported`, `operational` et l’état `enabled` persisté ; même si une écriture hors application réactive une ancienne ligne, la génération l’ignore et `operational` reste faux. Les credentials Bloomberg restent consommés par son adapter. Aucun récupérateur réel n’est lancé par les tests.
|
||||
|
||||
La migration 000015 refuse une installation où l’une des trois paires type/nom attendues est absente ou dupliquée, avant toute modification de schéma/données des sources. Vérifier l’inventaire et résoudre explicitement l’identité des sources après sauvegarde ; aucune fusion, création de remplacement ni purge automatique. Un échec de migration peut laisser le marqueur de version du moteur en état dirty : diagnostiquer l’échec avant toute reprise, sans forcer aveuglément la version. Le rollback de 000015 enlève la clé mais ne réactive pas les sources historiques, faute de connaître leur ancien état.
|
||||
|
||||
- `summary_max_articles` : défaut initial 50 ; nouvelles écritures admin acceptées entre 1 et 500, en transaction pour tout le lot de paramètres. Les anciennes valeurs >500 sont préservées, sans écrêtage silencieux.
|
||||
- `source.article_limit` : défaut 20, nouvelles valeurs 1–200.
|
||||
|
||||
59
frontend/e2e/ticket13-sources-responsive.spec.mjs
Normal file
59
frontend/e2e/ticket13-sources-responsive.spec.mjs
Normal file
@ -0,0 +1,59 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { readStackManifest } from './stack-manifest.mjs'
|
||||
|
||||
async function loginAsBootstrapAdmin(page, stack) {
|
||||
await page.goto(new URL('/login', stack.frontendUrl).href)
|
||||
await page.getByLabel('Adresse email').fill(stack.bootstrapAdmin.email)
|
||||
await page.getByLabel('Mot de passe').fill(stack.bootstrapAdmin.password)
|
||||
await page.getByRole('button', { name: 'Se connecter' }).click()
|
||||
await expect(page).toHaveURL(new URL('/', stack.frontendUrl).href)
|
||||
}
|
||||
|
||||
test('admin source controls stay accessible and fit at 320, 375 and 390 px', async ({ page }) => {
|
||||
const stack = readStackManifest()
|
||||
await page.context().route('**/*', async route => {
|
||||
const host = new URL(route.request().url()).hostname
|
||||
if (host !== '127.0.0.1' && host !== '[::1]') return route.abort('blockedbyclient')
|
||||
return route.continue()
|
||||
})
|
||||
|
||||
await loginAsBootstrapAdmin(page, stack)
|
||||
await page.goto(new URL('/admin/sources', stack.frontendUrl).href)
|
||||
await expect(page.getByRole('heading', { name: 'Sources et plafonds' })).toBeVisible()
|
||||
|
||||
const activationControls = page.locator('button[aria-label^="Activer "], button[aria-label^="Désactiver "]')
|
||||
await expect(activationControls).toHaveCount(3)
|
||||
const activationNames = (await activationControls.evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-label').replace(/^(Activer|Désactiver) /, '')).sort()))
|
||||
expect(activationNames).toEqual(['Bloomberg', 'Watcher.Guru', 'Yahoo Finance'])
|
||||
await expect(page.locator('form[aria-label^="Réglages de "]')).toHaveCount(3)
|
||||
|
||||
const historical = page.getByRole('region', { name: 'Anciennes sources exclues' })
|
||||
await expect(historical).toBeVisible()
|
||||
await historical.getByText(/^Consulter les anciennes sources/).click()
|
||||
const historicalRows = historical.locator('li')
|
||||
expect(await historicalRows.count()).toBeGreaterThan(0)
|
||||
await expect(historicalRows.locator('button, input, form, a')).toHaveCount(0)
|
||||
|
||||
for (const width of [320, 375, 390]) {
|
||||
await page.setViewportSize({ width, height: 844 })
|
||||
const dimensions = await page.evaluate(() => ({
|
||||
viewport: window.innerWidth,
|
||||
document: document.documentElement.scrollWidth,
|
||||
}))
|
||||
expect(dimensions.document, `horizontal overflow at ${width}px: ${JSON.stringify(dimensions)}`).toBeLessThanOrEqual(dimensions.viewport)
|
||||
|
||||
await expect(page.getByRole('spinbutton', { name: 'Articles max par résumé' })).toBeVisible()
|
||||
for (const name of ['Yahoo Finance', 'Bloomberg', 'Watcher.Guru']) {
|
||||
const toggle = page.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) })
|
||||
const cap = page.getByRole('spinbutton', { name: `Plafond ${name}` })
|
||||
await expect(toggle).toBeVisible()
|
||||
await expect(toggle).toBeEnabled()
|
||||
await expect(cap).toBeVisible()
|
||||
await expect(cap).toHaveAttribute('min', '1')
|
||||
await expect(cap).toHaveAttribute('max', '200')
|
||||
await expect(page.getByRole('button', { name: `Enregistrer le plafond ${name}` })).toBeVisible()
|
||||
}
|
||||
await expect(historical).toBeVisible()
|
||||
await expect(historicalRows.locator('button, input, form, a')).toHaveCount(0)
|
||||
}
|
||||
})
|
||||
@ -10,7 +10,10 @@ export interface OllamaModelInfo {
|
||||
name: string; size: number; modified_at: string
|
||||
details: { parameter_size: string; quantization_level: string; family: string }
|
||||
}
|
||||
export interface Source { id: string; name: string; type: string; enabled: boolean; article_limit: number }
|
||||
export interface Source {
|
||||
id: string; name: string; type: string; enabled: boolean; article_limit: number
|
||||
source_key: string | null; supported: boolean; operational: boolean
|
||||
}
|
||||
export interface Setting { key: string; value: string }
|
||||
export interface ScheduleSlot { id?: string; day_of_week: number; hour: number; minute: number }
|
||||
export interface AdminUser { id: string; email: string; role: string; created_at: string }
|
||||
|
||||
@ -5,25 +5,33 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
const SOURCE_KEYS = new Set(['yahoo_finance', 'bloomberg', 'watcher_guru'])
|
||||
|
||||
function isSupported(source: Source) {
|
||||
return source.supported === true && source.source_key !== null && SOURCE_KEYS.has(source.source_key)
|
||||
}
|
||||
|
||||
function validLimit(value: string, max: number) {
|
||||
return /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= max
|
||||
}
|
||||
|
||||
function SourceLimit({ source }: { source: Source }) {
|
||||
const [enabled, setEnabled] = useState(source.enabled)
|
||||
const [operational, setOperational] = useState(source.operational)
|
||||
const [limit, setLimit] = useState(String(source.article_limit ?? 20))
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [saved, setSaved] = useState(false)
|
||||
const [saved, setSaved] = useState('')
|
||||
const valid = validLimit(limit, 200)
|
||||
|
||||
async function toggle() {
|
||||
if (saving) return
|
||||
setSaving(true); setError(''); setSaved(false)
|
||||
setSaving(true); setError(''); setSaved('')
|
||||
try {
|
||||
// Omit the limit so even a historical out-of-range value is preserved.
|
||||
await adminApi.updateSource(source.id, !enabled)
|
||||
setEnabled(!enabled); setSaved(true)
|
||||
setEnabled(!enabled); setOperational(!enabled)
|
||||
setSaved(`${source.name} ${enabled ? 'désactivée' : 'activée'} pour les prochaines synthèses. Aucune génération n’a été lancée.`)
|
||||
} catch { setError('Impossible de modifier la source. Réessayez.') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
@ -31,10 +39,10 @@ function SourceLimit({ source }: { source: Source }) {
|
||||
async function save(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (!valid || saving || !enabled) return
|
||||
setSaving(true); setError(''); setSaved(false)
|
||||
setSaving(true); setError(''); setSaved('')
|
||||
try {
|
||||
await adminApi.updateSource(source.id, enabled, Number(limit))
|
||||
setSaved(true)
|
||||
setSaved(`Plafond ${source.name} enregistré pour les prochaines synthèses. Aucune génération n’a été lancée.`)
|
||||
} catch { setError('Impossible d’enregistrer le plafond. Votre saisie est conservée. Réessayez.') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
@ -42,19 +50,19 @@ function SourceLimit({ source }: { source: Source }) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader><CardTitle>{source.name}</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<CardContent className="space-y-4 min-w-0 break-words">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span>{enabled ? 'Activée' : 'Désactivée'}</span>
|
||||
<span>{enabled && operational ? 'Activée pour les synthèses' : 'Désactivée pour les synthèses'}</span>
|
||||
<Button type="button" variant="outline" disabled={saving} aria-label={`${enabled ? 'Désactiver' : 'Activer'} ${source.name}`} onClick={() => void toggle()}>{enabled ? 'Désactiver' : 'Activer'}</Button>
|
||||
</div>
|
||||
<form onSubmit={save} noValidate aria-label={`Réglages de ${source.name}`} aria-busy={saving} className="space-y-3">
|
||||
<Label htmlFor={`limit-${source.id}`}>Plafond {source.name}</Label>
|
||||
<Input id={`limit-${source.id}`} type="number" min="1" max="200" step="1" required className="max-w-xs" disabled={!enabled || saving} value={limit} aria-invalid={!valid} aria-describedby={`limit-help-${source.id}`} onChange={e => { setLimit(e.target.value); setSaved(false); setError('') }} />
|
||||
<Input id={`limit-${source.id}`} type="number" min="1" max="200" step="1" required className="max-w-xs" disabled={!enabled || saving} value={limit} aria-invalid={!valid} aria-describedby={`limit-help-${source.id}`} onChange={e => { setLimit(e.target.value); setSaved(''); setError('') }} />
|
||||
<p id={`limit-help-${source.id}`} className={`text-sm ${valid ? 'text-muted-foreground' : 'text-destructive'}`}>{valid ? 'De 1 à 200 articles par génération. Le plafond est conservé quand la source est désactivée.' : 'Saisissez un nombre entier de 1 à 200. La valeur actuelle est conservée tant que vous ne la modifiez pas.'}</p>
|
||||
<Button type="submit" disabled={!valid || !enabled || saving} aria-label={`Enregistrer le plafond ${source.name}`}>{saving ? 'Enregistrement…' : 'Enregistrer le plafond'}</Button>
|
||||
</form>
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
{saved && <p role="status">Source {source.name} enregistrée.</p>}
|
||||
{saved && <p role="status">{saved}</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
@ -69,6 +77,8 @@ export function Sources() {
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [saved, setSaved] = useState(false)
|
||||
const valid = validLimit(limit, 500)
|
||||
const supported = sources.filter(isSupported)
|
||||
const historical = sources.filter(source => !isSupported(source))
|
||||
|
||||
useEffect(() => { void load() }, [])
|
||||
async function load() {
|
||||
@ -95,7 +105,7 @@ export function Sources() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold">Sources et plafonds</h1>
|
||||
<p className="text-sm text-muted-foreground">Choisissez les sources utilisées pour les synthèses et leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles.</p>
|
||||
<p className="text-sm text-muted-foreground">Seules Yahoo Finance, Bloomberg et Watcher Guru peuvent participer aux synthèses manuelles et planifiées. Seules les sources activées sont utilisées, dans la limite de leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles ni génération immédiate.</p>
|
||||
{loading ? <p role="status">Chargement des sources et plafonds…</p> : loadError ? (
|
||||
<div className="space-y-3"><p role="alert">{loadError}</p><Button onClick={() => void load()}>Réessayer</Button></div>
|
||||
) : <>
|
||||
@ -105,15 +115,28 @@ export function Sources() {
|
||||
<form onSubmit={save} noValidate aria-label="Plafond global" aria-busy={saving} className="space-y-3">
|
||||
<Label htmlFor="summary-max-articles">Articles max par résumé</Label>
|
||||
<Input id="summary-max-articles" type="number" min="1" max="500" step="1" required className="max-w-xs" value={limit} disabled={saving} aria-invalid={!valid} aria-describedby="global-limit-help" onChange={e => { setLimit(e.target.value); setSaved(false); setError('') }} />
|
||||
<p id="global-limit-help" className={`text-sm ${valid ? 'text-muted-foreground' : 'text-destructive'}`}>{valid ? 'De 1 à 500 articles par génération, toutes sources confondues.' : 'Saisissez un nombre entier de 1 à 500 pour enregistrer. La valeur actuelle est conservée tant que vous ne la modifiez pas.'}</p>
|
||||
<p id="global-limit-help" className={`text-sm ${valid ? 'text-muted-foreground' : 'text-destructive'}`}>{valid ? 'De 1 à 500 articles par génération, parmi les sources autorisées et activées, après sélection par Laya et application des plafonds par source.' : 'Saisissez un nombre entier de 1 à 500 pour enregistrer. La valeur actuelle est conservée tant que vous ne la modifiez pas.'}</p>
|
||||
<Button type="submit" disabled={!valid || saving}>{saving ? 'Enregistrement…' : 'Enregistrer'}</Button>
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
{saved && <p role="status">Plafond global enregistré.</p>}
|
||||
{saved && <div role="status"><p>Plafond global enregistré.</p><p>Il s’appliquera aux prochaines synthèses. Aucune génération n’a été lancée.</p></div>}
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{sources.length === 0 && <p>Aucune source disponible.</p>}
|
||||
{sources.map(source => <SourceLimit key={source.id} source={source} />)}
|
||||
<div className="grid min-w-0 gap-4 lg:grid-cols-3">
|
||||
{supported.map(source => <SourceLimit key={source.id} source={source.source_key === 'yahoo_finance' ? { ...source, name: 'Yahoo Finance' } : source} />)}
|
||||
</div>
|
||||
{historical.length > 0 && <section aria-labelledby="historical-sources-title" className="space-y-3">
|
||||
<h2 id="historical-sources-title" className="text-lg font-semibold">Anciennes sources exclues</h2>
|
||||
<details className="rounded-md border p-4">
|
||||
<summary className="cursor-pointer font-medium">Consulter les anciennes sources ({historical.length})</summary>
|
||||
<p className="mt-3 text-sm text-muted-foreground">Ces sources sont conservées en lecture seule et exclues des synthèses manuelles et planifiées. Elles ne peuvent pas être réactivées. Les bilans des générations passées restent inchangés.</p>
|
||||
<ul className="mt-3 space-y-3">{historical.map(source => <li key={source.id} className="break-words">
|
||||
<p className="font-medium">{source.name}</p>
|
||||
<p className="text-sm text-muted-foreground">Exclue des synthèses · Plafond historique : {source.article_limit}</p>
|
||||
</li>)}</ul>
|
||||
</details>
|
||||
</section>}
|
||||
</>}
|
||||
</div>
|
||||
)
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react'
|
||||
import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
@ -23,7 +23,7 @@ describe('plafonds d’articles administrateur', () => {
|
||||
listSettings.mockResolvedValue([{ key: 'summary_max_articles', value: '700' }])
|
||||
getDefaultPrompt.mockResolvedValue({ prompt: 'system' })
|
||||
updateSettings.mockResolvedValue(undefined)
|
||||
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', enabled: true, article_limit: 240 }])
|
||||
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 240 }])
|
||||
updateSource.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
@ -93,7 +93,7 @@ describe('plafonds d’articles administrateur', () => {
|
||||
|
||||
it('initialise uniquement les valeurs absentes à 50 et 20', async () => {
|
||||
listSettings.mockResolvedValue([])
|
||||
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', enabled: true }])
|
||||
listSources.mockResolvedValue([{ id: 'source-1', name: 'Yahoo Finance', type: 'yahoo', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true }])
|
||||
render(<Sources />)
|
||||
expect(await screen.findByLabelText('Articles max par résumé')).toHaveValue(50)
|
||||
expect(screen.getByLabelText('Plafond Yahoo Finance')).toHaveValue(20)
|
||||
@ -149,4 +149,75 @@ describe('plafonds d’articles administrateur', () => {
|
||||
expect(updateSource).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ne rend activables que Yahoo, Bloomberg et Watcher Guru; garde StockTwits et Reuters en historique sans commandes', async () => {
|
||||
listSources.mockResolvedValue([
|
||||
{ id: 'y', name: 'Yahoo Finance', type: 'stocktwits', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 83 },
|
||||
{ id: 'b', name: 'Bloomberg', type: 'bloomberg', source_key: 'bloomberg', supported: true, operational: true, enabled: false, article_limit: 77 },
|
||||
{ id: 'w', name: 'Watcher.Guru', type: 'watcherguru', source_key: 'watcher_guru', supported: true, operational: true, enabled: true, article_limit: 64 },
|
||||
{ id: 's', name: 'StockTwits', type: 'stocktwits', source_key: null, supported: false, operational: false, enabled: false, article_limit: 31 },
|
||||
{ id: 'r', name: 'Reuters', type: 'reuters', source_key: null, supported: false, operational: false, enabled: false, article_limit: 42 },
|
||||
])
|
||||
render(<Sources />)
|
||||
expect(await screen.findByRole('heading', { name: 'Anciennes sources exclues' })).toBeInTheDocument()
|
||||
for (const name of ['Yahoo Finance', 'Bloomberg', 'Watcher.Guru']) {
|
||||
expect(screen.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name}$`) })).toBeInTheDocument()
|
||||
expect(screen.getByLabelText(`Plafond ${name}`)).toBeInTheDocument()
|
||||
}
|
||||
const historical = screen.getByRole('region', { name: 'Anciennes sources exclues' })
|
||||
expect(within(historical).getByText('StockTwits')).toBeInTheDocument()
|
||||
expect(within(historical).getByText('Reuters')).toBeInTheDocument()
|
||||
expect(within(historical).queryByRole('button')).not.toBeInTheDocument()
|
||||
expect(within(historical).queryByRole('spinbutton')).not.toBeInTheDocument()
|
||||
const yahooCard = screen.getByRole('form', { name: 'Réglages de Yahoo Finance' }).closest('.rounded-md')
|
||||
expect(yahooCard).not.toBeNull()
|
||||
expect(within(yahooCard as HTMLElement).queryByText(/stocktwits/i)).not.toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Plafond Yahoo Finance')).toHaveValue(83)
|
||||
expect(screen.getByLabelText('Plafond Bloomberg')).toHaveValue(77)
|
||||
expect(screen.getByLabelText('Plafond Watcher.Guru')).toHaveValue(64)
|
||||
})
|
||||
|
||||
it('garde les anciennes sources repliées et en lecture seule même si enabled est historique', async () => {
|
||||
listSources.mockResolvedValue([
|
||||
{ id: 'old', name: 'Reuters', type: 'reuters', source_key: null, supported: false, operational: false, enabled: true, article_limit: 42 },
|
||||
])
|
||||
const user = userEvent.setup()
|
||||
render(<Sources />)
|
||||
const region = await screen.findByRole('region', { name: 'Anciennes sources exclues' })
|
||||
const disclosure = region.querySelector('details')!
|
||||
expect(disclosure).not.toHaveAttribute('open')
|
||||
await user.click(within(region).getByText('Consulter les anciennes sources (1)'))
|
||||
expect(disclosure).toHaveAttribute('open')
|
||||
expect(within(region).getByText('Reuters')).toBeVisible()
|
||||
expect(within(region).queryByRole('button')).not.toBeInTheDocument()
|
||||
expect(within(region).queryByRole('spinbutton')).not.toBeInTheDocument()
|
||||
expect(updateSource).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('annonce les réglages des prochaines synthèses sans annoncer de génération lancée', async () => {
|
||||
listSources.mockResolvedValue([{ id: 'y', name: 'Stocktwits', type: 'stocktwits', source_key: 'yahoo_finance', supported: true, operational: true, enabled: true, article_limit: 83 }])
|
||||
const user = userEvent.setup()
|
||||
render(<Sources />)
|
||||
const input = await screen.findByLabelText('Plafond Yahoo Finance')
|
||||
expect(screen.queryByText('Stocktwits')).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Désactiver Yahoo Finance' }))
|
||||
expect(await screen.findByRole('status')).toHaveTextContent('Yahoo Finance désactivée pour les prochaines synthèses. Aucune génération n’a été lancée.')
|
||||
expect(input).toHaveValue(83)
|
||||
expect(input).toBeDisabled()
|
||||
await user.click(screen.getByRole('button', { name: 'Activer Yahoo Finance' }))
|
||||
await waitFor(() => expect(input).toBeEnabled())
|
||||
await user.click(screen.getByRole('button', { name: 'Enregistrer le plafond Yahoo Finance' }))
|
||||
expect(await screen.findByRole('status')).toHaveTextContent('Plafond Yahoo Finance enregistré pour les prochaines synthèses.')
|
||||
expect(updateSource).toHaveBeenLastCalledWith('y', true, 83)
|
||||
})
|
||||
|
||||
it('permet de recharger après un échec sans afficher de commandes pour des sources supposées', async () => {
|
||||
listSources.mockRejectedValueOnce(new Error('network'))
|
||||
const user = userEvent.setup()
|
||||
render(<Sources />)
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Impossible de charger')
|
||||
expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Réessayer' }))
|
||||
expect(await screen.findByLabelText('Plafond Yahoo Finance')).toHaveValue(240)
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user