test(e2e): add isolated browser journey and cleanup supervision
Add a fake-only end-to-end stack, Firefox journey, and bounded process cleanup for normal, failed, and interrupted runs. Refs #12 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
13
Makefile
13
Makefile
@ -6,7 +6,7 @@ TRADARR_GO_CACHE_ROOT := $(or $(strip $(TMPDIR)),$(strip $(IDEA_MANAGED_TMP)),/t
|
||||
export GOCACHE ?= $(TRADARR_GO_CACHE_ROOT)/go-build
|
||||
export GOMODCACHE ?= $(TRADARR_GO_CACHE_ROOT)/gomodcache
|
||||
|
||||
.PHONY: up down build logs deps dev-backend dev-frontend test-postgres lint test verify docker-build
|
||||
.PHONY: up down build logs deps dev-backend dev-frontend test-postgres test-e2e test-e2e-supervisor test-e2e-timeout lint test verify docker-build
|
||||
|
||||
up:
|
||||
$(COMPOSE) up --build
|
||||
@ -34,6 +34,17 @@ dev-frontend:
|
||||
test-postgres:
|
||||
./backend/scripts/test-postgres.sh
|
||||
|
||||
# Dedicated offline, disposable loopback fake stack and real Playwright browser.
|
||||
test-e2e:
|
||||
@exec ./backend/scripts/test-e2e.sh
|
||||
|
||||
test-e2e-supervisor:
|
||||
python3 -E -B backend/scripts/test-e2e-supervisor.py
|
||||
|
||||
# Real stack + timeout regression; optional QA wrapper directory can be supplied.
|
||||
test-e2e-timeout:
|
||||
python3 -E -B backend/scripts/test-e2e-timeout.py $(if $(E2E_REPRO_WRAPPER),--wrapper-dir "$(E2E_REPRO_WRAPPER)",)
|
||||
|
||||
lint:
|
||||
@unformatted="$$(gofmt -l backend)"; if [ -n "$$unformatted" ]; then printf 'Go formatting required:\n%s\n' "$$unformatted"; exit 1; fi
|
||||
cd backend && go vet ./...
|
||||
|
||||
@ -99,3 +99,7 @@ make docker-build
|
||||
```
|
||||
|
||||
Sans `TEST_DATABASE_URL`, `go test ./...` seul ignore les tests DB ; `make test-postgres` est donc nécessaire pour une validation complète. `make deps` utilise `go mod download` et `npm ci` ; les mises à jour intentionnelles de dépendances se font séparément, avec revue des manifests/lockfiles.
|
||||
|
||||
## Parcours navigateur intégré
|
||||
|
||||
Après préparation des dépendances, de PostgreSQL embedded (`make test-postgres`) et du Firefox Playwright épinglé, lancer `make test-e2e`. Le runner démarre une base jetable migrée, les faux OpenFIGI/Laya/scraper sur loopback et les serveurs applicatifs, puis exécute le vrai parcours Firefox. Scheduler désactivé, aucun adapter de récupération réel instancié, aucun téléchargement pendant ce run. Le nettoyage couvre succès, échec et interruption ; les caches sont conservés. Voir [le contrat E2E](frontend/e2e/README.md) pour les prérequis, le manifeste et les assertions de confidentialité.
|
||||
|
||||
237
backend/cmd/e2e/main.go
Normal file
237
backend/cmd/e2e/main.go
Normal file
@ -0,0 +1,237 @@
|
||||
// The dedicated E2E executable never imports concrete article scraper adapters.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/database"
|
||||
"github.com/tradarr/backend/internal/e2estack"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/indices/openfigi"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/server"
|
||||
)
|
||||
|
||||
func secret() string {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
func main() {
|
||||
// Linux parent-death signals follow the creating thread; keep it alive until
|
||||
// all managed child processes have been stopped and reaped.
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := guardParentDeath(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "E2E parent guard:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := run(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "E2E:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run(ctx context.Context) error {
|
||||
work := flag.String("work", "", "private disposable directory")
|
||||
psql := flag.String("psql", "", "cached PostgreSQL psql path")
|
||||
flag.Parse()
|
||||
if *work == "" || *psql == "" || !filepath.IsAbs(*work) || !filepath.IsAbs(*psql) {
|
||||
return errors.New("E2E requires absolute private workspace and psql paths")
|
||||
}
|
||||
dsn := os.Getenv("DATABASE_URL")
|
||||
if err := e2estack.ValidateURL(dsn, true); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed, _ := url.Parse(dsn)
|
||||
if strings.TrimPrefix(parsed.Path, "/") != "tradarr_e2e" {
|
||||
return errors.New("E2E database must be the dedicated tradarr_e2e database")
|
||||
}
|
||||
// Block external Go HTTP egress even if a future code path accidentally uses
|
||||
// a default client. Explicit fake clients use the same restricted transport.
|
||||
client := e2estack.LoopbackClient()
|
||||
http.DefaultTransport = client.Transport
|
||||
http.DefaultClient = client
|
||||
db, err := database.Connect(dsn)
|
||||
if err != nil {
|
||||
return errors.New("cannot connect disposable E2E database")
|
||||
}
|
||||
defer db.Close()
|
||||
var tables int
|
||||
if err = db.QueryRow(`SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'`).Scan(&tables); err != nil || tables != 0 {
|
||||
return errors.New("refusing to migrate a nonempty E2E database")
|
||||
}
|
||||
if err = database.RunMigrations(db); err != nil {
|
||||
return fmt.Errorf("E2E migrations: %w", err)
|
||||
}
|
||||
fakes := e2estack.NewFakes()
|
||||
fakeURL, closeFakes, err := e2estack.Listen(fakes.Handler())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeFakes()
|
||||
if err = e2estack.ValidateURL(fakeURL, false); err != nil {
|
||||
return err
|
||||
}
|
||||
// Keep every migration's historical tables, but choose exactly one enabled
|
||||
// fixture source. Do not seed candidate data into any historical table.
|
||||
if err = seed(db, fakeURL); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg := &config.Config{JWTSecret: secret(), EncryptionKey: []byte(secret()[:32]), AdminEmail: "bootstrap-e2e@example.test", AdminPassword: secret()}
|
||||
repo := models.NewRepository(db)
|
||||
if err = server.EnsureAdmin(repo, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
feeds := map[string]scraper.Scraper{"stocktwits": e2estack.FakeScraper{URL: fakeURL, Client: client}}
|
||||
provider := e2estack.FakeProvider{URL: fakeURL, Client: client}
|
||||
gin.SetMode(gin.TestMode)
|
||||
gin.DefaultWriter = io.Discard
|
||||
app := server.New(repo, cfg, server.Dependencies{Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
|
||||
return p.NewGenerationUseCaseWithProviders(feeds, provider, provider)
|
||||
}})
|
||||
defer app.Close()
|
||||
apiURL, closeAPI, err := e2estack.Listen(app.Router)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeAPI()
|
||||
frontend, err := filepath.Abs("../frontend")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
listener.Close()
|
||||
frontendURL := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
baseConfig, _ := json.Marshal(filepath.Join(frontend, "vite.config.ts"))
|
||||
root, _ := json.Marshal(frontend)
|
||||
target, _ := json.Marshal(apiURL)
|
||||
viteConfig := filepath.Join(*work, "vite.e2e.config.mjs")
|
||||
content := fmt.Sprintf(`import base from %s; export default {...base,root:%s,plugins:[...base.plugins,{name:'e2e-no-external-links',transformIndexHtml(html){return html.replace(/<link[^>]*https?:[^>]*>/g,'')}}],server:{headers:{'Content-Security-Policy':"default-src 'self' blob: data:; connect-src 'self' ws://127.0.0.1:*; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:"},host:'127.0.0.1',port:%d,strictPort:true,proxy:{'/api':{target:%s,changeOrigin:true}}}};`, baseConfig, root, port, target)
|
||||
if err = os.WriteFile(viteConfig, []byte(content), 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
logFile, err := os.OpenFile(filepath.Join(*work, "frontend.log"), os.O_CREATE|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer logFile.Close()
|
||||
vite := exec.Command("node", filepath.Join(frontend, "node_modules/vite/bin/vite.js"), "--config", viteConfig)
|
||||
vite.Dir = frontend
|
||||
vite.Stdout = logFile
|
||||
vite.Stderr = logFile
|
||||
vite.SysProcAttr = e2estack.ChildProcessAttrs()
|
||||
if err = vite.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = syscall.Kill(-vite.Process.Pid, syscall.SIGKILL); _ = vite.Wait() }()
|
||||
readyCtx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
defer cancel()
|
||||
if err = waitReady(readyCtx, client, frontendURL); err != nil {
|
||||
data, _ := os.ReadFile(filepath.Join(*work, "frontend.log"))
|
||||
fmt.Fprintln(os.Stderr, string(data))
|
||||
return err
|
||||
}
|
||||
manifest := map[string]any{"networkPolicy": "loopback-only", "generationProvider": "fake-laya", "frontendUrl": frontendURL, "apiUrl": apiURL, "databaseUrl": dsn, "openFigiFakeUrl": fakeURL, "scraperFakeUrl": fakeURL, "layaFakeUrl": fakeURL, "fakeControlUrl": fakeURL, "psqlPath": *psql, "fakeAuditPath": "/audit", "bootstrapAdmin": map[string]string{"email": cfg.AdminEmail, "password": cfg.AdminPassword}, "fixtures": fakes.Fixture}
|
||||
path := filepath.Join(*work, "stack.json")
|
||||
encoded, _ := json.Marshal(manifest)
|
||||
if err = os.WriteFile(path, encoded, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(path)
|
||||
pw := exec.CommandContext(ctx, "node", filepath.Join(frontend, "node_modules/@playwright/test/cli.js"), "test", "--config=playwright.e2e.config.mjs", "--output", filepath.Join(*work, "playwright"))
|
||||
pw.Dir = frontend
|
||||
pw.Env = append(os.Environ(), "TRADARR_E2E_STACK_MANIFEST="+path)
|
||||
pw.Stdout = os.Stdout
|
||||
pw.Stderr = os.Stderr
|
||||
pw.SysProcAttr = e2estack.ChildProcessAttrs()
|
||||
if err = pw.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = syscall.Kill(-pw.Process.Pid, syscall.SIGKILL) }()
|
||||
err = pw.Wait()
|
||||
audit, _ := os.OpenFile(filepath.Join(*work, "fake-audit.json"), os.O_CREATE|os.O_WRONLY, 0600)
|
||||
if audit != nil {
|
||||
fakes.Handler().ServeHTTP(auditWriter{audit}, mustRequest(fakeURL+"/audit"))
|
||||
audit.Close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type auditWriter struct{ io.Writer }
|
||||
|
||||
func (a auditWriter) Header() http.Header { return http.Header{} }
|
||||
func (a auditWriter) WriteHeader(int) {}
|
||||
func mustRequest(u string) *http.Request { r, _ := http.NewRequest("GET", u, nil); return r }
|
||||
func waitReady(ctx context.Context, client *http.Client, address string) error {
|
||||
for {
|
||||
attempt, cancel := context.WithTimeout(ctx, time.Second)
|
||||
req, _ := http.NewRequestWithContext(attempt, "GET", address, nil)
|
||||
resp, err := client.Do(req)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == 200 {
|
||||
cancel()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return errors.New("E2E frontend readiness timed out")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
func seed(db *sql.DB, fakeURL string) error {
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
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 {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
for _, role := range []string{"filter", "summary", "report"} {
|
||||
if _, err = tx.Exec(`INSERT INTO settings(key,value) VALUES($1,'00000000-0000-0000-0000-000000001202') ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value`, "ai_role_"+role+"_provider"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
23
backend/cmd/e2e/parent_death_linux.go
Normal file
23
backend/cmd/e2e/parent_death_linux.go
Normal file
@ -0,0 +1,23 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Arm the signal after NotifyContext, before creating any resources. Unlike a
|
||||
// shell trap, Linux delivers it even when the CLI parent is killed with SIGKILL.
|
||||
func guardParentDeath() error {
|
||||
parent := os.Getppid()
|
||||
_, _, errno := syscall.RawSyscall6(syscall.SYS_PRCTL, 1, uintptr(syscall.SIGTERM), 0, 0, 0, 0)
|
||||
if errno != 0 {
|
||||
return errno
|
||||
}
|
||||
if os.Getppid() != parent {
|
||||
return errors.New("E2E parent exited during setup")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
7
backend/cmd/e2e/parent_death_other.go
Normal file
7
backend/cmd/e2e/parent_death_other.go
Normal file
@ -0,0 +1,7 @@
|
||||
//go:build !linux
|
||||
|
||||
package main
|
||||
|
||||
import "errors"
|
||||
|
||||
func guardParentDeath() error { return errors.New("E2E supervision requires Linux") }
|
||||
@ -4,21 +4,17 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/api"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/crypto"
|
||||
"github.com/tradarr/backend/internal/database"
|
||||
"github.com/tradarr/backend/internal/indices/openfigi"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scheduler"
|
||||
"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"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@ -39,34 +35,22 @@ func main() {
|
||||
|
||||
repo := models.NewRepository(db)
|
||||
enc := crypto.New(cfg.EncryptionKey)
|
||||
pipeline := ai.NewPipeline(repo, enc)
|
||||
|
||||
if err := ensureAdmin(repo, cfg); err != nil {
|
||||
log.Printf("ensure admin: %v", err)
|
||||
}
|
||||
|
||||
registry := scraper.NewRegistry(repo)
|
||||
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
|
||||
}
|
||||
useCase := pipeline.NewGenerationUseCase(feeds)
|
||||
|
||||
sched := scheduler.New(registry, pipeline, repo)
|
||||
sched.SetGenerationUseCase(useCase)
|
||||
if err := sched.Start(); err != nil {
|
||||
log.Printf("scheduler: %v", err)
|
||||
}
|
||||
defer sched.Stop()
|
||||
|
||||
h := handlers.New(repo, cfg, enc, registry, pipeline, sched)
|
||||
h.SetGenerationUseCase(useCase)
|
||||
h.SetIndexSearcher(openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil))
|
||||
r := api.SetupRouter(h, cfg.JWTSecret)
|
||||
app := server.New(repo, cfg, server.Dependencies{Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
|
||||
defer app.Close()
|
||||
|
||||
addr := fmt.Sprintf(":%s", cfg.Port)
|
||||
log.Printf("server listening on %s", addr)
|
||||
if err := r.Run(addr); err != nil {
|
||||
if err := app.Router.Run(addr); err != nil {
|
||||
log.Fatalf("server: %v", err)
|
||||
}
|
||||
}
|
||||
@ -77,27 +61,5 @@ type adminRepository interface {
|
||||
}
|
||||
|
||||
func ensureAdmin(repo adminRepository, cfg *config.Config) error {
|
||||
if cfg.AdminEmail == "" {
|
||||
return nil
|
||||
}
|
||||
existing, err := repo.GetUserByEmail(cfg.AdminEmail)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing != nil {
|
||||
return nil
|
||||
}
|
||||
if cfg.AdminPassword == "" {
|
||||
return fmt.Errorf("ADMIN_PASSWORD is required to create the bootstrap admin")
|
||||
}
|
||||
hash, err := auth.HashPassword(cfg.AdminPassword)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = repo.CreateUser(cfg.AdminEmail, hash, models.RoleAdmin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("admin account created: %s", cfg.AdminEmail)
|
||||
return nil
|
||||
return server.EnsureAdmin(repo, cfg)
|
||||
}
|
||||
|
||||
@ -11,10 +11,17 @@ import (
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
type generationRanker struct{ p *Pipeline }
|
||||
type generationRanker struct {
|
||||
p *Pipeline
|
||||
provider Provider
|
||||
}
|
||||
|
||||
func (a generationRanker) Rank(ctx context.Context, mode string, assets []models.UserAsset, candidates []generation.Candidate) ([]generation.Candidate, error) {
|
||||
provider, _, err := a.p.buildProviderForRole("filter")
|
||||
provider := a.provider
|
||||
var err error
|
||||
if provider == nil {
|
||||
provider, _, err = a.p.buildProviderForRole("filter")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -44,10 +51,17 @@ func (a generationRanker) Rank(ctx context.Context, mode string, assets []models
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type generationSummarizer struct{ p *Pipeline }
|
||||
type generationSummarizer struct {
|
||||
p *Pipeline
|
||||
provider Provider
|
||||
}
|
||||
|
||||
func (a generationSummarizer) Summarize(ctx context.Context, language string, assets []models.UserAsset, candidates []generation.Candidate) (string, error) {
|
||||
provider, _, err := a.p.buildProviderForRole("summary")
|
||||
provider := a.provider
|
||||
var err error
|
||||
if provider == nil {
|
||||
provider, _, err = a.p.buildProviderForRole("summary")
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@ -75,7 +89,18 @@ func (a generationSummarizer) Summarize(ctx context.Context, language string, as
|
||||
return provider.Summarize(ctx, prompt, GenOptions{NumCtx: 32768})
|
||||
}
|
||||
func (p *Pipeline) NewGenerationUseCase(feeds map[string]scraper.Scraper) generation.UseCase {
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: p.repo}, Scrapers: feeds, Ranker: generationRanker{p}, Summarizer: generationSummarizer{p}})
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: p.repo}, Scrapers: feeds, Ranker: generationRanker{p: p}, Summarizer: generationSummarizer{p: p}})
|
||||
p.generationUseCase = uc
|
||||
return uc
|
||||
}
|
||||
|
||||
// NewGenerationUseCaseWithProviders keeps provider selection explicit for isolated
|
||||
// compositions. It never resolves a provider from database configuration.
|
||||
func (p *Pipeline) NewGenerationUseCaseWithProviders(feeds map[string]scraper.Scraper, ranker, summary Provider) generation.UseCase {
|
||||
if ranker == nil || summary == nil {
|
||||
panic("explicit generation providers required")
|
||||
}
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: p.repo}, Scrapers: feeds, Ranker: generationRanker{p: p, provider: ranker}, Summarizer: generationSummarizer{p: p, provider: summary}})
|
||||
p.generationUseCase = uc
|
||||
return uc
|
||||
}
|
||||
|
||||
193
backend/internal/e2estack/fakes.go
Normal file
193
backend/internal/e2estack/fakes.go
Normal file
@ -0,0 +1,193 @@
|
||||
package e2estack
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
type Fixtures struct {
|
||||
IndexQuery string `json:"indexQuery"`
|
||||
IndexName string `json:"indexName"`
|
||||
IndexSymbol string `json:"indexSymbol"`
|
||||
IndexFIGI string `json:"indexFIGI"`
|
||||
SummarySentinel string `json:"summarySentinel"`
|
||||
ArticleTitle string `json:"articleTitle"`
|
||||
ArticleURL string `json:"articleURL"`
|
||||
ArticleContent string `json:"articleContent"`
|
||||
CandidateID string `json:"candidateID"`
|
||||
}
|
||||
|
||||
func DefaultFixtures() Fixtures {
|
||||
return Fixtures{"E2E index", "E2E Financial Index", "E2EIDX", "BBG000E2E001", "E2E synthesized financial summary", "E2E private article title", "https://fixture.invalid/private-article", "E2E private article body", "pending-candidate-id"}
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
Kind string `json:"kind"`
|
||||
Symbols []string `json:"symbols,omitempty"`
|
||||
CandidateID string `json:"candidate_id,omitempty"`
|
||||
}
|
||||
type Fakes struct {
|
||||
mu sync.Mutex
|
||||
Fixture Fixtures
|
||||
Events []Event
|
||||
counts map[string]int
|
||||
}
|
||||
|
||||
func NewFakes() *Fakes {
|
||||
return &Fakes{Fixture: DefaultFixtures(), Events: []Event{}, counts: map[string]int{}}
|
||||
}
|
||||
func (f *Fakes) record(event Event) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.Events = append(f.Events, event)
|
||||
f.counts[event.Kind]++
|
||||
}
|
||||
func (f *Fakes) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/audit", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"openfigiSearches": f.counts["openfigiSearches"], "scraperCalls": f.counts["scraperCalls"], "layaRankingCalls": f.counts["layaRankingCalls"], "layaSummaryCalls": f.counts["layaSummaryCalls"], "events": f.Events})
|
||||
})
|
||||
mux.HandleFunc("/v3/search", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Query string `json:"query"`
|
||||
Market string `json:"marketSecDes"`
|
||||
}
|
||||
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&req) != nil || req.Market != "Index" {
|
||||
http.Error(w, "invalid fixture search", 400)
|
||||
return
|
||||
}
|
||||
f.record(Event{Kind: "openfigiSearches"})
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]string{{"name": f.Fixture.IndexName, "ticker": f.Fixture.IndexSymbol, "figi": f.Fixture.IndexFIGI, "marketSector": "Index"}}})
|
||||
})
|
||||
mux.HandleFunc("/scrape", func(w http.ResponseWriter, r *http.Request) {
|
||||
var symbols []string
|
||||
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&symbols) != nil {
|
||||
http.Error(w, "invalid fixture scrape", 400)
|
||||
return
|
||||
}
|
||||
f.record(Event{Kind: "scraperCalls", Symbols: symbols})
|
||||
_ = json.NewEncoder(w).Encode([]scraper.Article{{Title: f.Fixture.ArticleTitle, Content: f.Fixture.ArticleContent, URL: f.Fixture.ArticleURL}})
|
||||
})
|
||||
mux.HandleFunc("/api/generate", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Prompt string `json:"prompt"`
|
||||
Format string `json:"format"`
|
||||
}
|
||||
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&req) != nil {
|
||||
http.Error(w, "invalid fixture provider", 400)
|
||||
return
|
||||
}
|
||||
response := f.Fixture.SummarySentinel
|
||||
if req.Format == "json" {
|
||||
// The candidate UUID is generated by the real use case; never hard-code it.
|
||||
start := strings.LastIndex(req.Prompt, "\n{")
|
||||
if start < 0 {
|
||||
http.Error(w, "ranking payload missing", 400)
|
||||
return
|
||||
}
|
||||
var payload struct {
|
||||
Articles []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"articles"`
|
||||
}
|
||||
if json.Unmarshal([]byte(req.Prompt[start+1:]), &payload) != nil || len(payload.Articles) != 1 {
|
||||
http.Error(w, "ranking candidate missing", 400)
|
||||
return
|
||||
}
|
||||
id := payload.Articles[0].ID
|
||||
f.mu.Lock()
|
||||
f.Fixture.CandidateID = id
|
||||
f.mu.Unlock()
|
||||
f.record(Event{Kind: "layaRankingCalls", CandidateID: id})
|
||||
encoded, _ := json.Marshal(map[string]any{"ranked_article_ids": []string{id}})
|
||||
response = string(encoded)
|
||||
} else {
|
||||
f.record(Event{Kind: "layaSummaryCalls"})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"response": response})
|
||||
})
|
||||
return mux
|
||||
}
|
||||
func Listen(handler http.Handler) (string, func(), error) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
server := &http.Server{Handler: handler}
|
||||
go server.Serve(listener)
|
||||
return "http://" + listener.Addr().String(), func() { _ = server.Close() }, nil
|
||||
}
|
||||
|
||||
type FakeScraper struct {
|
||||
URL string
|
||||
Client *http.Client
|
||||
}
|
||||
|
||||
func (FakeScraper) Name() string { return "e2e" }
|
||||
func (s FakeScraper) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
|
||||
if err := ValidateURL(s.URL, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, _ := json.Marshal(symbols)
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", s.URL+"/scrape", bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := s.Client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("fake scraper failed")
|
||||
}
|
||||
var articles []scraper.Article
|
||||
err = json.NewDecoder(resp.Body).Decode(&articles)
|
||||
return articles, err
|
||||
}
|
||||
|
||||
type FakeProvider struct {
|
||||
URL string
|
||||
Client *http.Client
|
||||
}
|
||||
|
||||
func (FakeProvider) Name() string { return "fake-laya" }
|
||||
func (FakeProvider) ListModels(context.Context) ([]string, error) { return []string{"fake-laya"}, nil }
|
||||
func (p FakeProvider) Summarize(ctx context.Context, prompt string, opts ai.GenOptions) (string, error) {
|
||||
if err := ValidateURL(p.URL, false); err != nil {
|
||||
return "", err
|
||||
}
|
||||
body := map[string]any{"prompt": prompt, "model": "fake-laya", "stream": false}
|
||||
if opts.JSONMode {
|
||||
body["format"] = "json"
|
||||
}
|
||||
raw, _ := json.Marshal(body)
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", p.URL+"/api/generate", bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := p.Client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
return "", fmt.Errorf("fake provider failed")
|
||||
}
|
||||
var result struct {
|
||||
Response string `json:"response"`
|
||||
}
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
return result.Response, err
|
||||
}
|
||||
49
backend/internal/e2estack/network.go
Normal file
49
backend/internal/e2estack/network.go
Normal file
@ -0,0 +1,49 @@
|
||||
// Package e2estack contains test-only loopback adapters. Production does not import it.
|
||||
package e2estack
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
func ValidateURL(raw string, database bool) error {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return errors.New("invalid E2E URL")
|
||||
}
|
||||
scheme := u.Scheme == "http" || u.Scheme == "https"
|
||||
if database {
|
||||
scheme = u.Scheme == "postgres" || u.Scheme == "postgresql"
|
||||
}
|
||||
ip := net.ParseIP(u.Hostname())
|
||||
if !scheme || ip == nil || !ip.IsLoopback() || u.Port() == "" {
|
||||
return errors.New("E2E URL must use a literal loopback IP and explicit port")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type loopbackTransport struct{ base *http.Transport }
|
||||
|
||||
func (t loopbackTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
if err := ValidateURL(r.URL.String(), false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t.base.RoundTrip(r)
|
||||
}
|
||||
func LoopbackClient() *http.Client {
|
||||
transport := &http.Transport{Proxy: nil, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
host, _, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil || !ip.IsLoopback() {
|
||||
return nil, errors.New("E2E external egress forbidden")
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, address)
|
||||
}}
|
||||
return &http.Client{Transport: loopbackTransport{transport}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
}
|
||||
11
backend/internal/e2estack/process_linux.go
Normal file
11
backend/internal/e2estack/process_linux.go
Normal file
@ -0,0 +1,11 @@
|
||||
//go:build linux
|
||||
|
||||
package e2estack
|
||||
|
||||
import "syscall"
|
||||
|
||||
// ChildProcessAttrs prevents a Vite/Playwright launcher surviving e2e-stack.
|
||||
// The subreaper separately owns and cleans their detached descendants.
|
||||
func ChildProcessAttrs() *syscall.SysProcAttr {
|
||||
return &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGKILL}
|
||||
}
|
||||
7
backend/internal/e2estack/process_other.go
Normal file
7
backend/internal/e2estack/process_other.go
Normal file
@ -0,0 +1,7 @@
|
||||
//go:build !linux
|
||||
|
||||
package e2estack
|
||||
|
||||
import "syscall"
|
||||
|
||||
func ChildProcessAttrs() *syscall.SysProcAttr { return &syscall.SysProcAttr{Setpgid: true} }
|
||||
50
backend/internal/e2estack/safety_test.go
Normal file
50
backend/internal/e2estack/safety_test.go
Normal file
@ -0,0 +1,50 @@
|
||||
package e2estack
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
func TestRejectNonLoopbackDestinationsWithoutEgress(t *testing.T) {
|
||||
for _, destination := range []string{"https://api.openfigi.com:443", "http://203.0.113.10:80", "http://localhost:8080", "http://127.0.0.1.evil.test:80", "file:///tmp/fixture"} {
|
||||
if ValidateURL(destination, false) == nil {
|
||||
t.Fatalf("unsafe base URL accepted: %s", destination)
|
||||
}
|
||||
request, err := http.NewRequest("GET", destination, nil)
|
||||
if err == nil {
|
||||
if _, err = LoopbackClient().Do(request); err == nil {
|
||||
t.Fatal("external request accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
if ValidateURL("postgres://127.0.0.1:5432/tradarr_e2e", true) != nil {
|
||||
t.Fatal("loopback DB rejected")
|
||||
}
|
||||
}
|
||||
func TestFakesRankActualCandidateIDAndJournalCalls(t *testing.T) {
|
||||
fake := NewFakes()
|
||||
base, closeServer, err := Listen(fake.Handler())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer closeServer()
|
||||
provider := FakeProvider{URL: base, Client: LoopbackClient()}
|
||||
articles := []models.Article{{ID: "runtime-candidate-uuid", Title: fake.Fixture.ArticleTitle, Content: fake.Fixture.ArticleContent}}
|
||||
ranked, err := ai.RankArticles(context.Background(), provider, []string{"Index (IDX)"}, articles, 20, "title_content")
|
||||
if err != nil || len(ranked) != 1 || ranked[0].ID != articles[0].ID {
|
||||
t.Fatalf("ranking=%v err=%v", ranked, err)
|
||||
}
|
||||
fake.mu.Lock()
|
||||
defer fake.mu.Unlock()
|
||||
if fake.counts["layaRankingCalls"] != 1 || fake.Events[0].CandidateID != "runtime-candidate-uuid" {
|
||||
t.Fatal("ranking call not journaled")
|
||||
}
|
||||
if strings.Contains(fake.Fixture.SummarySentinel, fake.Fixture.ArticleTitle) {
|
||||
t.Fatal("unsafe summary fixture")
|
||||
}
|
||||
}
|
||||
39
backend/internal/server/bootstrap.go
Normal file
39
backend/internal/server/bootstrap.go
Normal file
@ -0,0 +1,39 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"log"
|
||||
)
|
||||
|
||||
type AdminRepository interface {
|
||||
GetUserByEmail(string) (*models.User, error)
|
||||
CreateUser(string, string, models.Role) (*models.User, error)
|
||||
}
|
||||
|
||||
func EnsureAdmin(repo AdminRepository, cfg *config.Config) error {
|
||||
if cfg.AdminEmail == "" {
|
||||
return nil
|
||||
}
|
||||
existing, err := repo.GetUserByEmail(cfg.AdminEmail)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing != nil {
|
||||
return nil
|
||||
}
|
||||
if cfg.AdminPassword == "" {
|
||||
return fmt.Errorf("ADMIN_PASSWORD is required to create the bootstrap admin")
|
||||
}
|
||||
hash, err := auth.HashPassword(cfg.AdminPassword)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = repo.CreateUser(cfg.AdminEmail, hash, models.RoleAdmin); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("admin account created: %s", cfg.AdminEmail)
|
||||
return nil
|
||||
}
|
||||
51
backend/internal/server/server.go
Normal file
51
backend/internal/server/server.go
Normal file
@ -0,0 +1,51 @@
|
||||
// Package server composes HTTP and optional scheduled application execution.
|
||||
// Concrete retrieval/provider adapters belong to the executable's composition root.
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/api"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/crypto"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/indices"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scheduler"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"log"
|
||||
)
|
||||
|
||||
type Dependencies struct {
|
||||
Feeds map[string]scraper.Scraper
|
||||
IndexSearcher indices.IndexSearcher
|
||||
GenerationFactory func(*ai.Pipeline) generation.UseCase
|
||||
EnableScheduler bool
|
||||
}
|
||||
type App struct {
|
||||
Router *gin.Engine
|
||||
scheduler *scheduler.Scheduler
|
||||
}
|
||||
|
||||
func New(repo *models.Repository, cfg *config.Config, deps Dependencies) *App {
|
||||
enc := crypto.New(cfg.EncryptionKey)
|
||||
pipeline := ai.NewPipeline(repo, enc)
|
||||
registry := scraper.NewRegistry(repo)
|
||||
uc := pipeline.NewGenerationUseCase(deps.Feeds)
|
||||
if deps.GenerationFactory != nil {
|
||||
uc = deps.GenerationFactory(pipeline)
|
||||
}
|
||||
sched := scheduler.New(registry, pipeline, repo)
|
||||
sched.SetGenerationUseCase(uc)
|
||||
if deps.EnableScheduler {
|
||||
if err := sched.Start(); err != nil {
|
||||
log.Printf("scheduler: %v", err)
|
||||
}
|
||||
}
|
||||
h := handlers.New(repo, cfg, enc, registry, pipeline, sched)
|
||||
h.SetGenerationUseCase(uc)
|
||||
h.SetIndexSearcher(deps.IndexSearcher)
|
||||
return &App{Router: api.SetupRouter(h, cfg.JWTSecret), scheduler: sched}
|
||||
}
|
||||
func (a *App) Close() { a.scheduler.Stop() }
|
||||
40
backend/internal/server/server_test.go
Normal file
40
backend/internal/server/server_test.go
Normal file
@ -0,0 +1,40 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/indices"
|
||||
)
|
||||
|
||||
type fakeGeneration struct{}
|
||||
|
||||
func (fakeGeneration) Generate(context.Context, string) (generation.Result, error) {
|
||||
return generation.Result{Outcome: generation.GenerationOutcome{Status: "no_results"}}, nil
|
||||
}
|
||||
|
||||
type fakeSearch struct{ calls int }
|
||||
|
||||
func (f *fakeSearch) Search(context.Context, string, int) ([]indices.Index, error) {
|
||||
f.calls++
|
||||
return []indices.Index{}, nil
|
||||
}
|
||||
func TestInjectableCompositionDoesNotStartSchedulerOrNeedDatabase(t *testing.T) {
|
||||
search := &fakeSearch{}
|
||||
factoryCalls := 0
|
||||
app := New(nil, &config.Config{JWTSecret: "composition-test"}, Dependencies{IndexSearcher: search, GenerationFactory: func(*ai.Pipeline) generation.UseCase { factoryCalls++; return fakeGeneration{} }, EnableScheduler: false})
|
||||
defer app.Close()
|
||||
token, _ := auth.GenerateToken("owner", "owner@example.test", "user", "composition-test")
|
||||
request := httptest.NewRequest("GET", "/api/indices/search?q=test", nil)
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
response := httptest.NewRecorder()
|
||||
app.Router.ServeHTTP(response, request)
|
||||
if response.Code != 200 || search.calls != 1 || factoryCalls != 1 {
|
||||
t.Fatalf("status=%d search=%d factory=%d", response.Code, search.calls, factoryCalls)
|
||||
}
|
||||
}
|
||||
270
backend/scripts/e2e-supervisor.py
Normal file
270
backend/scripts/e2e-supervisor.py
Normal file
@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Linux-only E2E lifecycle owner, independent of make's signal disposition.
|
||||
|
||||
The detached watcher outlives a killed launcher/make, acts as child subreaper,
|
||||
then terminates and reaps the whole descendant tree before removing its workspace.
|
||||
Never scans/kills by executable name and never removes shared caches.
|
||||
"""
|
||||
import ctypes
|
||||
import json
|
||||
import os
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
import select
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
PR_SET_CHILD_SUBREAPER = 36
|
||||
PR_SET_PDEATHSIG = 1
|
||||
|
||||
|
||||
def process(pid):
|
||||
"""Identity includes start ticks to avoid acting on a recycled PID."""
|
||||
try:
|
||||
fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
|
||||
return int(fields[1]), fields[19], fields[0] # ppid, starttime, state
|
||||
except (OSError, ValueError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def same_process(pid, identity):
|
||||
current = process(pid)
|
||||
return current is not None and current[1] == identity[1] and current[2] != "Z"
|
||||
|
||||
|
||||
def descendants(root):
|
||||
records = {}
|
||||
for item in Path("/proc").iterdir():
|
||||
if item.name.isdigit():
|
||||
identity = process(int(item.name))
|
||||
if identity is not None:
|
||||
records[int(item.name)] = identity
|
||||
owned = {root}
|
||||
while True:
|
||||
found = {pid for pid, identity in records.items() if identity[0] in owned}
|
||||
if found <= owned:
|
||||
break
|
||||
owned |= found
|
||||
return {pid: records[pid] for pid in owned if pid != root and pid in records}
|
||||
|
||||
|
||||
def direct_children(root):
|
||||
# Unlike a cross-process ancestry scan, these lists come from the kernel's
|
||||
# actual child ownership. Include every thread, not just the group leader.
|
||||
records = {}
|
||||
for entry in Path(f"/proc/{root}/task").glob("*/children"):
|
||||
for value in entry.read_text().split():
|
||||
pid = int(value)
|
||||
identity = process(pid)
|
||||
if identity is not None and identity[0] == root:
|
||||
records[pid] = identity
|
||||
return records
|
||||
|
||||
|
||||
def reap():
|
||||
"""Return True while the kernel still owns a live child, False on ECHILD."""
|
||||
while True:
|
||||
try:
|
||||
pid, _ = os.waitpid(-1, os.WNOHANG)
|
||||
if pid == 0:
|
||||
return True
|
||||
except ChildProcessError:
|
||||
return False
|
||||
|
||||
|
||||
def stop_tree(worker):
|
||||
root = os.getpid()
|
||||
known = {}
|
||||
identity = process(worker.pid)
|
||||
if identity is not None:
|
||||
known[worker.pid] = identity
|
||||
signalled = set()
|
||||
grace = time.monotonic() + 1.5
|
||||
deadline = grace + 3
|
||||
empty_confirmations = 0
|
||||
while time.monotonic() < deadline:
|
||||
# Never forget previously observed live identities when an ancestry
|
||||
# snapshot temporarily loses a parent during exit/adoption.
|
||||
known.update(descendants(root))
|
||||
known.update(direct_children(root))
|
||||
force = time.monotonic() >= grace
|
||||
for pid, identity in known.items():
|
||||
if same_process(pid, identity):
|
||||
key = (pid, identity[1])
|
||||
if force or key not in signalled:
|
||||
try:
|
||||
os.kill(pid, signal.SIGKILL if force else signal.SIGTERM)
|
||||
signalled.add(key)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
worker.poll()
|
||||
has_children = reap()
|
||||
alive = any(same_process(pid, identity) for pid, identity in known.items())
|
||||
if not has_children and not alive:
|
||||
empty_confirmations += 1
|
||||
if empty_confirmations >= 2:
|
||||
return
|
||||
else:
|
||||
empty_confirmations = 0
|
||||
time.sleep(0.03)
|
||||
raise RuntimeError("E2E kernel-owned descendants failed to terminate; workspace retained")
|
||||
|
||||
|
||||
def timeout_duration(arguments):
|
||||
"""Read a GNU timeout soft duration; never extend an enclosing deadline."""
|
||||
position = 1
|
||||
while position < len(arguments):
|
||||
value = arguments[position]
|
||||
if value == "--":
|
||||
position += 1
|
||||
break
|
||||
if value in ("-k", "--kill-after", "-s", "--signal"):
|
||||
position += 2
|
||||
elif value in ("--foreground", "--preserve-status", "--verbose", "-v") or value.startswith(("--signal=", "--kill-after=")):
|
||||
position += 1
|
||||
elif value.startswith("-"):
|
||||
return None
|
||||
else:
|
||||
break
|
||||
if position >= len(arguments):
|
||||
return None
|
||||
match = re.fullmatch(r"([0-9]+(?:\.[0-9]+)?)([smhd]?)", arguments[position])
|
||||
if not match:
|
||||
return None
|
||||
duration = float(match[1]) * {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400}[match[2]]
|
||||
return duration if duration > 0 and math.isfinite(duration) else None
|
||||
|
||||
|
||||
def enclosing_deadline(pid):
|
||||
deadlines = []
|
||||
for _ in range(64):
|
||||
identity = process(pid)
|
||||
if identity is None:
|
||||
break
|
||||
try:
|
||||
executable = Path(os.readlink(f"/proc/{pid}/exe")).name
|
||||
if executable == "timeout":
|
||||
arguments = Path(f"/proc/{pid}/cmdline").read_bytes().decode().strip("\0").split("\0")
|
||||
duration = timeout_duration(arguments)
|
||||
if duration is not None:
|
||||
boot_now = time.clock_gettime(time.CLOCK_BOOTTIME)
|
||||
started = int(identity[1]) / os.sysconf("SC_CLK_TCK")
|
||||
remaining = max(0, duration - (boot_now - started))
|
||||
deadlines.append(time.monotonic() + remaining)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if identity[0] <= 0 or identity[0] == pid:
|
||||
break
|
||||
pid = identity[0]
|
||||
return min(deadlines) if deadlines else None
|
||||
|
||||
|
||||
def watcher(project, owner_pid, owner_start, life_fd, deadline=None):
|
||||
libc = ctypes.CDLL(None, use_errno=True)
|
||||
if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0:
|
||||
raise OSError(ctypes.get_errno(), "E2E subreaper setup failed")
|
||||
interrupted = []
|
||||
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
|
||||
signal.signal(sig, lambda received, _frame: interrupted.append(received))
|
||||
base = os.environ.get("TMPDIR") or os.environ.get("IDEA_MANAGED_TMP") or "/tmp"
|
||||
work = Path(tempfile.mkdtemp(prefix="tradarr-e2e.", dir=base))
|
||||
worker = None
|
||||
expected_parent = os.getpid()
|
||||
|
||||
def parent_death_guard():
|
||||
if libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) != 0:
|
||||
os._exit(125)
|
||||
if os.getppid() != expected_parent:
|
||||
os._exit(125)
|
||||
|
||||
try:
|
||||
env = dict(os.environ, TRADARR_E2E_RUN_DIR=str(work))
|
||||
worker = subprocess.Popen(
|
||||
["bash", str(project / "backend/scripts/test-e2e-worker.sh")],
|
||||
cwd=project, env=env, start_new_session=True, preexec_fn=parent_death_guard,
|
||||
)
|
||||
# Diagnostic process identities only; never credentials or DSNs.
|
||||
(work / "supervisor.json").write_text(json.dumps({
|
||||
"watcher": os.getpid(), "worker": worker.pid, "owner": owner_pid,
|
||||
}))
|
||||
while True:
|
||||
result = worker.poll()
|
||||
if result is not None:
|
||||
return result if result >= 0 else 128 - result
|
||||
ready, _, _ = select.select([life_fd], [], [], 0.05)
|
||||
alive = process(owner_pid)
|
||||
if (deadline is not None and time.monotonic() >= deadline) or interrupted or alive is None or alive[1] != owner_start or alive[2] == "Z":
|
||||
return 130
|
||||
if ready and os.read(life_fd, 1) == b"":
|
||||
return 130
|
||||
finally:
|
||||
if worker is not None:
|
||||
stop_tree(worker)
|
||||
shutil.rmtree(work)
|
||||
os.close(life_fd)
|
||||
|
||||
|
||||
def launch(project):
|
||||
if sys.platform != "linux" or not Path("/proc/self/stat").exists():
|
||||
raise RuntimeError("E2E supervision requires Linux /proc and child-subreaper support")
|
||||
owner_pid = os.getppid()
|
||||
owner = process(owner_pid)
|
||||
if owner is None:
|
||||
raise RuntimeError("E2E owner disappeared before supervision")
|
||||
read_fd, write_fd = os.pipe()
|
||||
watch = None
|
||||
pending = []
|
||||
|
||||
def forward(received, _frame):
|
||||
pending.append(received)
|
||||
if watch is not None:
|
||||
try:
|
||||
os.kill(watch.pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
|
||||
signal.signal(sig, forward)
|
||||
# Kernel notification complements polling when make itself is SIGKILLed.
|
||||
# Install handlers first, then close the setup race by rechecking the parent.
|
||||
libc = ctypes.CDLL(None, use_errno=True)
|
||||
if libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) != 0:
|
||||
raise OSError(ctypes.get_errno(), "E2E launcher parent-death guard failed")
|
||||
if os.getppid() != owner_pid:
|
||||
os.close(read_fd)
|
||||
os.close(write_fd)
|
||||
raise RuntimeError("E2E owner disappeared during launcher setup")
|
||||
try:
|
||||
watch = subprocess.Popen(
|
||||
[sys.executable, "-E", __file__, "--watch", str(project),
|
||||
str(owner_pid), owner[1], str(read_fd), str(enclosing_deadline(owner_pid) or 0)],
|
||||
pass_fds=(read_fd,), start_new_session=True,
|
||||
)
|
||||
os.close(read_fd)
|
||||
if pending:
|
||||
os.kill(watch.pid, signal.SIGTERM)
|
||||
return watch.wait()
|
||||
finally:
|
||||
os.close(write_fd) # abrupt launcher death closes it in the kernel too
|
||||
if watch is not None and watch.poll() is None:
|
||||
os.kill(watch.pid, signal.SIGTERM)
|
||||
watch.wait(timeout=6)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
if len(sys.argv) == 7 and sys.argv[1] == "--watch":
|
||||
code = watcher(Path(sys.argv[2]), int(sys.argv[3]), sys.argv[4], int(sys.argv[5]), float(sys.argv[6]) or None)
|
||||
elif len(sys.argv) == 2:
|
||||
code = launch(Path(sys.argv[1]))
|
||||
else:
|
||||
raise RuntimeError("invalid E2E supervisor invocation")
|
||||
sys.exit(code)
|
||||
except Exception as error:
|
||||
print(f"E2E supervisor: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
126
backend/scripts/test-e2e-supervisor.py
Normal file
126
backend/scripts/test-e2e-supervisor.py
Normal file
@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline lifecycle regression: kill the owner/launcher, not their process group."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import json
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
|
||||
SUPERVISOR = Path(__file__).with_name("e2e-supervisor.py")
|
||||
spec = importlib.util.spec_from_file_location("e2e_supervisor", SUPERVISOR)
|
||||
supervision = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(supervision)
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "linux", "Linux /proc supervision")
|
||||
class Lifecycle(unittest.TestCase):
|
||||
def run_case(self, victim, normal_exit=False):
|
||||
with tempfile.TemporaryDirectory(prefix="e2e-supervisor-test-", dir=os.environ.get("TMPDIR")) as temporary:
|
||||
root = Path(temporary)
|
||||
project = root / "project"
|
||||
scripts = project / "backend/scripts"
|
||||
scripts.mkdir(parents=True)
|
||||
sleeper = "import signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);time.sleep(60)"
|
||||
code = (
|
||||
"import subprocess,sys,signal,time;"
|
||||
f"subprocess.Popen([sys.executable,'-E','-c',{sleeper!r}],start_new_session=True);"
|
||||
"signal.signal(signal.SIGTERM,signal.SIG_IGN);"
|
||||
+ ("time.sleep(.2)" if normal_exit else "time.sleep(60)")
|
||||
)
|
||||
(scripts / "test-e2e-worker.sh").write_text(
|
||||
"#!/bin/sh\nexec " + shlex.quote(sys.executable) + " -E -c " + shlex.quote(code) + "\n"
|
||||
)
|
||||
owner_code = (
|
||||
"import subprocess,sys,time;"
|
||||
f"p=subprocess.Popen([sys.executable,'-E',{str(SUPERVISOR)!r},{str(project)!r}]);"
|
||||
"p.wait();time.sleep(60)"
|
||||
)
|
||||
with (root / "output.log").open("w") as output:
|
||||
owner = subprocess.Popen([sys.executable, "-E", "-c", owner_code], env=dict(os.environ, TMPDIR=str(root)), stdout=output, stderr=output)
|
||||
identities = {}
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
info = None
|
||||
while time.monotonic() < deadline:
|
||||
files = list(root.glob("tradarr-e2e.*/supervisor.json"))
|
||||
if files:
|
||||
try:
|
||||
info = json.loads(files[0].read_text())
|
||||
identities = supervision.descendants(info["watcher"])
|
||||
if len(identities) >= 2:
|
||||
workspace = files[0].parent
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(.02)
|
||||
else:
|
||||
self.fail("supervised descendants did not start")
|
||||
if not normal_exit:
|
||||
if victim == "owner":
|
||||
os.kill(owner.pid, signal.SIGKILL)
|
||||
else:
|
||||
launcher = supervision.process(info["watcher"])[0]
|
||||
os.kill(launcher, signal.SIGKILL)
|
||||
deadline = time.monotonic() + 7
|
||||
while time.monotonic() < deadline:
|
||||
alive = [pid for pid, identity in identities.items() if supervision.same_process(pid, identity)]
|
||||
if not alive and not workspace.exists():
|
||||
break
|
||||
time.sleep(.02)
|
||||
self.assertFalse(alive, f"surviving descendants: {alive}")
|
||||
self.assertFalse(workspace.exists(), "workspace leaked")
|
||||
if victim == "launcher":
|
||||
self.assertIsNone(owner.poll(), "owner should remain alive for broken-pipe case")
|
||||
finally:
|
||||
# Tests never kill by a name/shared group, even on failure.
|
||||
for pid, identity in identities.items():
|
||||
if supervision.same_process(pid, identity):
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
if owner.poll() is None:
|
||||
owner.kill()
|
||||
owner.wait(timeout=5)
|
||||
|
||||
def test_empty_proc_snapshot_is_not_cleanup_confirmation(self):
|
||||
# /proc traversal is not atomic during exit/reparenting. Even an empty
|
||||
# ancestry snapshot must not override the kernel's live-child state.
|
||||
code = "import signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);print('ready',flush=True);time.sleep(60)"
|
||||
child = subprocess.Popen([sys.executable, "-E", "-c", code], stdout=subprocess.PIPE, text=True)
|
||||
original = supervision.descendants
|
||||
try:
|
||||
self.assertEqual(child.stdout.readline().strip(), "ready")
|
||||
supervision.descendants = lambda _root: {}
|
||||
supervision.stop_tree(child)
|
||||
self.assertIsNotNone(child.poll(), "empty /proc snapshot left a live child")
|
||||
finally:
|
||||
supervision.descendants = original
|
||||
if child.poll() is None:
|
||||
child.kill()
|
||||
child.wait()
|
||||
child.stdout.close()
|
||||
|
||||
def test_gnu_timeout_duration_parsing(self):
|
||||
self.assertEqual(supervision.timeout_duration(["timeout", "--foreground", "--preserve-status", "--signal=INT", "--kill-after=8s", "8s", "make", "test-e2e"]), 8)
|
||||
self.assertEqual(supervision.timeout_duration(["timeout", "-k", "8s", "-s", "INT", "1.5m", "make"]), 90)
|
||||
self.assertIsNone(supervision.timeout_duration(["timeout", "0", "make"]))
|
||||
self.assertIsNone(supervision.timeout_duration(["timeout", "--unknown", "8s", "make"]))
|
||||
|
||||
def test_sigkill_owner_only(self):
|
||||
self.run_case("owner")
|
||||
|
||||
def test_sigkill_launcher_broken_liveness_pipe(self):
|
||||
self.run_case("launcher")
|
||||
|
||||
def test_normal_worker_exit_reaps_detached_grandchildren(self):
|
||||
self.run_case("normal", normal_exit=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
123
backend/scripts/test-e2e-timeout.py
Normal file
123
backend/scripts/test-e2e-timeout.py
Normal file
@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Integration regression: real make/embedded PG/E2E runner, single-PID timeout.
|
||||
|
||||
Pass --wrapper-dir to use QA's exact node wrapper. Without it, Playwright is
|
||||
blocked before execution, after the real Vite server has started.
|
||||
"""
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
spec = importlib.util.spec_from_file_location("supervisor", Path(__file__).with_name("e2e-supervisor.py"))
|
||||
supervision = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(supervision)
|
||||
|
||||
|
||||
def run(wrapper_dir):
|
||||
base = Path(os.environ.get("TMPDIR") or os.environ.get("IDEA_MANAGED_TMP") or "/tmp")
|
||||
with tempfile.TemporaryDirectory(prefix="ticket12-timeout-integration.", dir=base) as temporary:
|
||||
evidence = Path(temporary)
|
||||
if wrapper_dir:
|
||||
wrapper = Path(wrapper_dir).resolve()
|
||||
if not (wrapper / "node").is_file():
|
||||
raise RuntimeError("QA wrapper node is absent; exact reproduction refused")
|
||||
else:
|
||||
wrapper = evidence / "wrapper"
|
||||
wrapper.mkdir()
|
||||
node = shutil.which("node")
|
||||
(wrapper / "node").write_text(
|
||||
'#!/bin/bash\nif [[ "$*" == *playwright* ]]; then\n'
|
||||
' exec sleep 60\nelse\n exec ' + shlex.quote(node) + ' "$@"\nfi\n'
|
||||
)
|
||||
(wrapper / "node").chmod(0o755)
|
||||
command = ["timeout", "--foreground", "--preserve-status", "--signal=INT", "--kill-after=8s", "8s", "make", "test-e2e"]
|
||||
known = {}
|
||||
workspace = None
|
||||
process = None
|
||||
watcher = None
|
||||
names = set()
|
||||
real_ready = False
|
||||
try:
|
||||
with (evidence / "runner.log").open("w") as log:
|
||||
process = subprocess.Popen(command, cwd=ROOT, env=dict(os.environ, PATH=str(wrapper) + ":" + os.environ["PATH"]), stdout=log, stderr=log)
|
||||
deadline = time.monotonic() + 35
|
||||
while process.poll() is None and time.monotonic() < deadline:
|
||||
if workspace is None:
|
||||
for metadata in base.glob("tradarr-e2e.*/supervisor.json"):
|
||||
try:
|
||||
info = json.loads(metadata.read_text())
|
||||
owner = supervision.process(info["owner"])
|
||||
if owner is not None and owner[0] == process.pid:
|
||||
workspace = metadata.parent
|
||||
watcher = info["watcher"]
|
||||
identity = supervision.process(watcher)
|
||||
if identity:
|
||||
known[watcher] = identity
|
||||
break
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
if watcher:
|
||||
known.update(supervision.descendants(watcher))
|
||||
if workspace is not None and (workspace / "stack.json").exists():
|
||||
real_ready = True
|
||||
for pid in known:
|
||||
try:
|
||||
names.add(Path(f"/proc/{pid}/comm").read_text().strip())
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(.03)
|
||||
code = process.wait(timeout=2)
|
||||
if workspace is None:
|
||||
raise RuntimeError("real runner did not create a supervised workspace")
|
||||
if not real_ready or not {"postgres", "e2e-stack", "sleep"}.issubset(names):
|
||||
raise RuntimeError(f"real stack incomplete: ready={real_ready}, observed process names={sorted(names)}")
|
||||
# This assertion is deliberately immediate. Waiting after timeout
|
||||
# returns keeps the test supervisor alive and masked the QA leak.
|
||||
if watcher:
|
||||
known.update(supervision.descendants(watcher))
|
||||
survivors = [pid for pid, identity in known.items() if supervision.same_process(pid, identity)]
|
||||
if survivors or workspace.exists():
|
||||
raise RuntimeError(f"timeout returned before cleanup: {len(survivors)} survivors; workspace remains={workspace.exists()}")
|
||||
if code not in (130, 2):
|
||||
raise RuntimeError(f"runner failed to clean during timeout grace period: exit={code}")
|
||||
print(f"PASS real runner + exact timeout flags: exit={code}, observed={len(known)}, no survivor/workspace when timeout returns")
|
||||
except Exception:
|
||||
print((evidence / "runner.log").read_text()[-5000:] if (evidence / "runner.log").exists() else "", file=sys.stderr)
|
||||
raise
|
||||
finally:
|
||||
# Independent fallback so a red regression does not itself leak.
|
||||
if watcher:
|
||||
known.update(supervision.descendants(watcher))
|
||||
for pid, identity in known.items():
|
||||
if supervision.same_process(pid, identity):
|
||||
try:
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
if process is not None and process.poll() is None:
|
||||
process.kill()
|
||||
process.wait()
|
||||
if workspace is not None and workspace.exists():
|
||||
shutil.rmtree(workspace)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--wrapper-dir")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
run(args.wrapper_dir)
|
||||
except Exception as error:
|
||||
print(f"FAIL E2E timeout integration: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
28
backend/scripts/test-e2e-worker.sh
Executable file
28
backend/scripts/test-e2e-worker.sh
Executable file
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
managed_tmp="${TMPDIR:-${IDEA_MANAGED_TMP:-/tmp}}"
|
||||
pg_home="$managed_tmp/tradarr-embedded-postgres"
|
||||
cli="$pg_home/bin/embedded-postgres"
|
||||
if [[ ! -x "$cli" ]] || [[ "$("$cli" version)" != *'"version":"v2.0.1"'* ]]; then
|
||||
echo 'E2E requires cached embedded-postgres v2.0.1; prepare with make test-postgres.' >&2
|
||||
exit 2
|
||||
fi
|
||||
psql_path="$(find "$pg_home/cache" -type f -path '*/postgresql-16.15.1-*/bin/psql' -print -quit)"
|
||||
if [[ -z "$psql_path" ]]; then
|
||||
echo 'E2E requires cached PostgreSQL 16.15.1; prepare with make test-postgres.' >&2
|
||||
exit 2
|
||||
fi
|
||||
# The independent supervisor owns this directory and every process below us.
|
||||
: "${TRADARR_E2E_RUN_DIR:?invoke make test-e2e through its supervisor}"
|
||||
run_dir="$TRADARR_E2E_RUN_DIR"
|
||||
export GOCACHE="${GOCACHE:-$managed_tmp/go-build}"
|
||||
export GOMODCACHE="${GOMODCACHE:-$managed_tmp/gomodcache}"
|
||||
# No dependency installation/network downloads during an E2E run.
|
||||
export GOPROXY=off GOSUMDB=off npm_config_update_notifier=false
|
||||
unset DATABASE_URL TEST_DATABASE_URL PGHOST PGPORT PGUSER PGPASSWORD PGDATABASE PGSSLMODE TRADARR_E2E_STACK_MANIFEST NO_COLOR FORCE_COLOR
|
||||
cd "$project_root/backend"
|
||||
go build -o "$run_dir/e2e-stack" ./cmd/e2e
|
||||
exec "$cli" exec --offline --postgres-version 16.15.1 --database tradarr_e2e \
|
||||
--cache-dir "$pg_home/cache" --work-dir "$run_dir/db" \
|
||||
-- "$run_dir/e2e-stack" -work "$run_dir" -psql "$psql_path"
|
||||
6
backend/scripts/test-e2e.sh
Executable file
6
backend/scripts/test-e2e.sh
Executable file
@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
# exec preserves our parent (make) identity; Python -E ignores bundled-app
|
||||
# PYTHONHOME/PYTHONPATH without altering the caller's environment.
|
||||
exec python3 -E -B "$project_root/backend/scripts/e2e-supervisor.py" "$project_root"
|
||||
21
frontend/e2e/README.md
Normal file
21
frontend/e2e/README.md
Normal file
@ -0,0 +1,21 @@
|
||||
# Ticket #12 — isolated browser E2E
|
||||
|
||||
The supervisor requires Linux `/proc`, child-subreaper support and Python 3 (standard library only). Run `make test-e2e` from the project root after `make deps` and `make test-postgres`. The latter prepares the pinned embedded-postgres CLI v2.0.1/PostgreSQL 16.15.1 cache. Install Playwright's pinned Firefox beforehand if it is not already cached (`cd frontend && npx playwright install firefox`). These preparation steps may require network access; the E2E runner itself uses offline caches and never installs dependencies.
|
||||
|
||||
The runner builds the dedicated `backend/cmd/e2e` executable, starts a disposable `tradarr_e2e` database, applies the real migrations, and refuses a nonempty database. It ignores inherited application/test database URLs, chooses loopback ports, and bootstraps a reserved disposable admin. Exactly one fixture source is enabled. Provider roles refer to the loopback fake; the injected generation providers and scraper are fakes, with no concrete retrieval adapter instantiated. Production uses the same `internal/server` constructor with its existing real composition and scheduler enabled.
|
||||
|
||||
OpenFIGI, an Ollama-compatible fake Laya and a fake scraper share a loopback HTTP service with `/audit` counters and structured call events. The ranking fake extracts the real candidate UUID from the request prompt and returns it in `ranked_article_ids`; the browser assertion checks that actual UUID in audit events against the saved outcome. No hard-coded fixture ID selects a candidate.
|
||||
|
||||
The temporary private manifest declares `networkPolicy: loopback-only` and `generationProvider: fake-laya`, along with frontend/API/database/fake URLs, disposable bootstrap credentials and the cached `psql` path. The Playwright global guard validates it before opening Firefox. The manifest is generated by the runner, not a reusable configuration file. A new private work directory is created per run, with mode-0600 manifest/logs. It is removed on success, failure or interruption, along with processes and disposable DB files; build and PostgreSQL binary caches remain.
|
||||
|
||||
The Make recipe execs a launcher whose parent is make. A detached Python watchdog owns a separate worker session, monitors the original make PID/start time and a liveness pipe, and acts as a Linux child subreaper. It detects parent SIGKILL or a killed launcher without depending on shell traps. On exit it retains every observed PID/start-time identity, discovers direct children through `/proc/self/task/*/children`, signals all owned descendants (including detached groups/sessions), and escalates to SIGKILL after 1.5 seconds. An empty ancestry snapshot is never treated as proof of cleanup: completion requires the kernel's `waitpid`/`ECHILD` confirmation plus no live retained identity. It then removes the workspace. Kernel parent-death signals additionally protect the launcher, CLI worker, e2e-stack, Vite and Playwright launchers. The E2E Go main thread is kept alive for these thread-sensitive Linux guards. Cleanup is bounded; failure to terminate a process retains the workspace and reports an error. It never kills by executable name or removes shared build caches. As with any userspace watchdog, killing the watchdog itself with SIGKILL is outside this guarantee.
|
||||
|
||||
`make test-e2e-supervisor` runs offline regressions for owner/launcher SIGKILL, TERM-resistant detached grandchildren, and a deliberately empty `/proc` ancestry snapshot while a kernel-owned child remains alive. The latter fails on the original implementation; the initial three tests did not cover it.
|
||||
|
||||
`make test-e2e-timeout` launches the real runner via `timeout --foreground --preserve-status --signal=INT --kill-after=8s 8s make test-e2e`, with real disposable PostgreSQL/backend/Vite and a PATH wrapper that blocks Playwright **before** browser execution. It requires observing those real processes and a ready manifest, then verifies no surviving observed identity or workspace **immediately when timeout returns**. The test does not keep its own parent alive waiting for post-return cleanup. To use QA's actual wrapper instead of the built-in one, run `make test-e2e-timeout E2E_REPRO_WRAPPER=/absolute/QA/wrapper-directory`; a missing wrapper fails closed rather than silently running without the intended reproduction. The real E2E cleanup should also be checked with the QA PATH-wrapper/`timeout --foreground --preserve-status --signal=INT --kill-after=8s 8s make test-e2e` reproducer. The supervisor inherits the nearest enclosing GNU timeout's soft deadline from its `/proc` arguments and start time. It begins cancellation at that deadline even when make does not forward SIGINT to its recipe. For the 8s INT / 8s kill-after reproducer, cleanup must finish during the grace interval and return 130 (or make's error status), rather than relying on a watcher after exit 137. This matters when the outer execution environment tears down remaining processes as soon as timeout returns. An arbitrary SIGKILL of the entire execution namespace cannot leave a userspace watcher running.
|
||||
|
||||
The E2E executable rejects nonliteral/nonloopback destination URLs and installs an HTTP transport that refuses external egress without DNS/proxy fallback. The temporary Vite configuration removes external font/preconnect links and adds a restrictive CSP. Playwright blocks nonloopback page requests and service workers; Firefox prefetch/speculative connections are disabled. No production frontend file or retrieval adapter is changed for this policy.
|
||||
|
||||
The Firefox journey covers admin login/account creation, new-user login, explicit OpenFIGI search/selection/follow, language/ranking preferences and fake-backed generation. It compares counts and hashes for `articles`, `article_symbols` and `scrape_jobs`, verifies retired routes are 404, reads the authenticated aggregate history, verifies its single-source counters, and rejects fixture article fields and actual candidate IDs in that outcome. HTTP success through the real application is required; API/provider routes are not mocked in the browser.
|
||||
|
||||
`npm run test:e2e` alone still fails closed without a valid running stack manifest. Use `make test-e2e` for complete lifecycle management. The scenario has no automatic retry. Browser traces and logs can contain disposable credentials and are deliberately kept inside the cleaned workspace.
|
||||
7
frontend/e2e/global-setup.mjs
Normal file
7
frontend/e2e/global-setup.mjs
Normal file
@ -0,0 +1,7 @@
|
||||
import { readStackManifest } from './stack-manifest.mjs'
|
||||
|
||||
export default async function globalSetup() {
|
||||
// Fail closed before launching Firefox or making any request if the local fake
|
||||
// composition has not been supplied. This prevents accidental live-provider runs.
|
||||
readStackManifest()
|
||||
}
|
||||
86
frontend/e2e/stack-manifest.mjs
Normal file
86
frontend/e2e/stack-manifest.mjs
Normal file
@ -0,0 +1,86 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { isIP } from 'node:net'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
const requiredURLs = [
|
||||
'frontendUrl',
|
||||
'apiUrl',
|
||||
'databaseUrl',
|
||||
'openFigiFakeUrl',
|
||||
'scraperFakeUrl',
|
||||
'layaFakeUrl',
|
||||
'fakeControlUrl',
|
||||
]
|
||||
|
||||
function loopbackURL(value, field, protocols) {
|
||||
let parsed
|
||||
try {
|
||||
parsed = new URL(value)
|
||||
} catch {
|
||||
throw new Error(`E2E fake stack manifest field ${field} must be a URL.`)
|
||||
}
|
||||
if (!protocols.includes(parsed.protocol)) {
|
||||
throw new Error(`E2E fake stack manifest field ${field} uses an unsupported protocol.`)
|
||||
}
|
||||
const hostname = parsed.hostname.replace(/^\[|\]$/g, '')
|
||||
const loopback = hostname === 'localhost' || hostname.endsWith('.localhost') ||
|
||||
(isIP(hostname) === 4 && hostname.startsWith('127.')) || hostname === '::1'
|
||||
if (!loopback) {
|
||||
throw new Error(`E2E fake stack manifest field ${field} must use a loopback host.`)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
export function stackManifestPath() {
|
||||
return process.env.TRADARR_E2E_STACK_MANIFEST ||
|
||||
path.join(process.env.TMPDIR || tmpdir(), 'tradarr-e2e', 'stack.json')
|
||||
}
|
||||
|
||||
export function readStackManifest() {
|
||||
const manifestPath = stackManifestPath()
|
||||
let manifest
|
||||
try {
|
||||
manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
|
||||
} catch {
|
||||
throw new Error([
|
||||
`Safe E2E composition is missing: no readable stack manifest at ${manifestPath}.`,
|
||||
'No browser, application server, database, or provider was started by this run.',
|
||||
'The manifest must be produced by a loopback-only fake stack and point to a disposable E2E database.',
|
||||
].join(' '))
|
||||
}
|
||||
|
||||
if (manifest.networkPolicy !== 'loopback-only') {
|
||||
throw new Error('E2E fake stack manifest must declare networkPolicy "loopback-only".')
|
||||
}
|
||||
if (manifest.generationProvider !== 'fake-laya') {
|
||||
throw new Error('E2E fake stack manifest must declare generationProvider "fake-laya".')
|
||||
}
|
||||
for (const field of requiredURLs) {
|
||||
if (typeof manifest[field] !== 'string' || !manifest[field]) {
|
||||
throw new Error(`E2E fake stack manifest is missing ${field}.`)
|
||||
}
|
||||
loopbackURL(manifest[field], field, field === 'databaseUrl' ? ['postgres:', 'postgresql:'] : ['http:', 'https:'])
|
||||
}
|
||||
if (typeof manifest.psqlPath !== 'string' || !manifest.psqlPath.startsWith('/')) {
|
||||
throw new Error('E2E fake stack manifest must provide an absolute psqlPath for database assertions.')
|
||||
}
|
||||
if (!manifest.bootstrapAdmin?.email || !manifest.bootstrapAdmin?.password) {
|
||||
throw new Error('E2E fake stack manifest must provide disposable bootstrap admin credentials.')
|
||||
}
|
||||
for (const field of ['indexQuery', 'indexName', 'indexSymbol', 'indexFIGI', 'summarySentinel', 'articleTitle', 'articleURL', 'articleContent', 'candidateID']) {
|
||||
if (typeof manifest.fixtures?.[field] !== 'string' || !manifest.fixtures[field]) {
|
||||
throw new Error(`E2E fake stack manifest is missing fixtures.${field}.`)
|
||||
}
|
||||
}
|
||||
|
||||
const databaseURL = new URL(manifest.databaseUrl)
|
||||
const databaseName = decodeURIComponent(databaseURL.pathname.replace(/^\//, ''))
|
||||
if (!/(^|[-_])(e2e|test)([-_]|$)/i.test(databaseName)) {
|
||||
throw new Error('E2E database name must identify a disposable database with an e2e or test marker.')
|
||||
}
|
||||
if (!manifest.fakeAuditPath || !manifest.fakeAuditPath.startsWith('/')) {
|
||||
throw new Error('E2E fake stack manifest must provide an absolute fakeAuditPath.')
|
||||
}
|
||||
return { ...manifest, databaseURL }
|
||||
}
|
||||
133
frontend/e2e/ticket12-happy-path.spec.mjs
Normal file
133
frontend/e2e/ticket12-happy-path.spec.mjs
Normal file
@ -0,0 +1,133 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { readStackManifest } from './stack-manifest.mjs'
|
||||
|
||||
function articleAndJobSnapshot(stack) {
|
||||
const env = {
|
||||
...process.env,
|
||||
PGHOST: stack.databaseURL.hostname,
|
||||
PGPORT: stack.databaseURL.port || '5432',
|
||||
PGUSER: decodeURIComponent(stack.databaseURL.username),
|
||||
PGPASSWORD: decodeURIComponent(stack.databaseURL.password),
|
||||
PGDATABASE: decodeURIComponent(stack.databaseURL.pathname.slice(1)),
|
||||
PGSSLMODE: stack.databaseURL.searchParams.get('sslmode') || 'disable',
|
||||
}
|
||||
const sql = `SELECT
|
||||
(SELECT count(*)::text || ':' || coalesce(md5(string_agg(md5(row_to_json(a)::text), ',' ORDER BY row_to_json(a)::text)), md5('')) FROM public.articles a)
|
||||
|| '|' ||
|
||||
(SELECT count(*)::text || ':' || coalesce(md5(string_agg(md5(row_to_json(s)::text), ',' ORDER BY row_to_json(s)::text)), md5('')) FROM public.article_symbols s)
|
||||
|| '|' ||
|
||||
(SELECT count(*)::text || ':' || coalesce(md5(string_agg(md5(row_to_json(j)::text), ',' ORDER BY row_to_json(j)::text)), md5('')) FROM public.scrape_jobs j);`
|
||||
return execFileSync(stack.psqlPath, ['--no-psqlrc', '--tuples-only', '--no-align', '--set', 'ON_ERROR_STOP=1', '--command', sql], {
|
||||
env,
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
timeout: 10_000,
|
||||
}).trim()
|
||||
}
|
||||
|
||||
async function login(page, baseURL, email, password) {
|
||||
await page.goto(new URL('/login', baseURL).href)
|
||||
await page.getByLabel('Adresse email').fill(email)
|
||||
await page.getByLabel('Mot de passe').fill(password)
|
||||
await page.getByRole('button', { name: 'Se connecter' }).click()
|
||||
await expect(page).toHaveURL(new URL('/', baseURL).href)
|
||||
}
|
||||
|
||||
test('admin creates a user who follows a fake index and generates a private summary without article/job writes', async ({ page, request }) => {
|
||||
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()
|
||||
})
|
||||
const baseURL = stack.frontendUrl
|
||||
const fixture = stack.fixtures
|
||||
const email = `e2e-${randomUUID()}@example.test`
|
||||
const password = `E2e-${randomUUID()}!`
|
||||
const before = articleAndJobSnapshot(stack)
|
||||
|
||||
await test.step('admin bootstrap login and account creation', async () => {
|
||||
await login(page, baseURL, stack.bootstrapAdmin.email, stack.bootstrapAdmin.password)
|
||||
await page.goto(new URL('/admin/users', baseURL).href)
|
||||
await page.getByRole('button', { name: 'Créer un compte' }).click()
|
||||
const form = page.getByRole('form', { name: 'Créer un compte' })
|
||||
await form.getByLabel('Email').fill(email)
|
||||
await form.getByLabel('Mot de passe initial').fill(password)
|
||||
await form.getByRole('button', { name: 'Créer', exact: true }).click()
|
||||
await expect(form.getByRole('status')).toHaveText('Compte créé avec succès.')
|
||||
await page.getByRole('button', { name: 'Déconnexion' }).click()
|
||||
})
|
||||
|
||||
await test.step('new user login and explicit fake OpenFIGI selection', async () => {
|
||||
await login(page, baseURL, email, password)
|
||||
await page.goto(new URL('/assets', baseURL).href)
|
||||
const query = page.getByRole('textbox', { name: 'Nom ou symbole' })
|
||||
await query.fill(fixture.indexQuery)
|
||||
await page.getByRole('button', { name: 'Rechercher' }).click()
|
||||
const results = page.getByRole('region', { name: 'Résultats de recherche' })
|
||||
await expect(results.getByText(fixture.indexName)).toBeVisible()
|
||||
await expect(results.getByText(fixture.indexSymbol)).toBeVisible()
|
||||
await results.getByRole('button', { name: 'Suivre cet indice' }).click()
|
||||
await expect(page.getByRole('region', { name: 'Indices suivis' })).toContainText(fixture.indexSymbol)
|
||||
})
|
||||
|
||||
await test.step('user saves language and ranking preferences', async () => {
|
||||
await page.goto(new URL('/preferences', baseURL).href)
|
||||
await page.getByLabel('Langue des synthèses').selectOption('en')
|
||||
await page.getByLabel('Informations utilisées par Laya pour classer les articles').selectOption('title_content')
|
||||
await page.getByRole('button', { name: 'Enregistrer' }).click()
|
||||
await expect(page.getByRole('status')).toHaveText('Préférences enregistrées.')
|
||||
})
|
||||
|
||||
await test.step('fake scraper and Laya produce an aggregate summary', async () => {
|
||||
await page.goto(new URL('/', baseURL).href)
|
||||
await page.getByRole('button', { name: 'Générer une synthèse' }).click()
|
||||
await expect(page.getByText(fixture.summarySentinel, { exact: false })).toBeVisible({ timeout: 90_000 })
|
||||
await expect(page.getByText('Langue de cette synthèse : English', { exact: true })).toBeVisible()
|
||||
for (const forbidden of [fixture.articleTitle, fixture.articleURL, fixture.articleContent, fixture.candidateID]) {
|
||||
await expect(page.getByText(forbidden, { exact: false })).toHaveCount(0)
|
||||
}
|
||||
})
|
||||
|
||||
await test.step('legacy article/job routes stay closed and database rows remain unchanged', async () => {
|
||||
const api = stack.apiUrl
|
||||
expect((await request.get(new URL('/api/articles', api).href)).status()).toBe(404)
|
||||
expect((await request.get(new URL('/api/articles/e2e-forbidden', api).href)).status()).toBe(404)
|
||||
expect((await request.get(new URL('/api/admin/scrape-jobs', api).href)).status()).toBe(404)
|
||||
expect((await request.post(new URL('/api/admin/scrape-jobs/trigger', api).href)).status()).toBe(404)
|
||||
expect(articleAndJobSnapshot(stack)).toBe(before)
|
||||
})
|
||||
|
||||
await test.step('fake-provider audit confirms every dependency stayed local', async () => {
|
||||
const response = await request.get(new URL(stack.fakeAuditPath, stack.fakeControlUrl).href)
|
||||
expect(response.ok()).toBeTruthy()
|
||||
const events = await response.json()
|
||||
expect(events.openfigiSearches).toBeGreaterThan(0)
|
||||
expect(events.scraperCalls).toBeGreaterThan(0)
|
||||
expect(events.layaRankingCalls).toBeGreaterThan(0)
|
||||
expect(events.layaSummaryCalls).toBeGreaterThan(0)
|
||||
const token = await page.evaluate(() => localStorage.getItem('token'))
|
||||
const history = await request.get(new URL('/api/summaries/generations', stack.apiUrl).href, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(history.status()).toBe(200)
|
||||
const generations = await history.json()
|
||||
expect(generations.data.length).toBe(1)
|
||||
const outcome = generations.data[0].outcome
|
||||
expect(outcome.status).toBe('succeeded')
|
||||
expect(outcome.total_candidates).toBe(1)
|
||||
expect(outcome.source_stats).toHaveLength(1)
|
||||
const serialized = JSON.stringify(outcome)
|
||||
const candidateIDs = events.events.filter(event => event.kind === 'layaRankingCalls').map(event => event.candidate_id)
|
||||
expect(candidateIDs.length).toBeGreaterThan(0)
|
||||
for (const forbidden of [fixture.articleTitle, fixture.articleURL, fixture.articleContent, ...candidateIDs]) {
|
||||
expect(serialized).not.toContain(forbidden)
|
||||
await expect(page.getByText(forbidden, { exact: false })).toHaveCount(0)
|
||||
}
|
||||
for (const field of ['title', 'url', 'content', 'prompt', 'candidate_id']) {
|
||||
expect(serialized).not.toContain(`"${field}":`)
|
||||
}
|
||||
})
|
||||
})
|
||||
64
frontend/package-lock.json
generated
64
frontend/package-lock.json
generated
@ -29,6 +29,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.5",
|
||||
"@playwright/test": "1.60.0",
|
||||
"@testing-library/jest-dom": "^8.0.0",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
@ -2464,6 +2465,22 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.60.0",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz",
|
||||
"integrity": "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.60.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@radix-ui/number": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
|
||||
@ -8995,6 +9012,53 @@
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.60.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz",
|
||||
"integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.60.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.60.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz",
|
||||
"integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright/node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/possible-typed-array-names": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||
|
||||
@ -8,7 +8,8 @@
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint .",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"test:e2e": "playwright test --config=playwright.e2e.config.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-avatar": "^1.1.3",
|
||||
@ -32,6 +33,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.5",
|
||||
"@playwright/test": "1.60.0",
|
||||
"@testing-library/jest-dom": "^8.0.0",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
|
||||
20
frontend/playwright.e2e.config.mjs
Normal file
20
frontend/playwright.e2e.config.mjs
Normal file
@ -0,0 +1,20 @@
|
||||
import { defineConfig } from '@playwright/test'
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
testMatch: '**/*.spec.mjs',
|
||||
fullyParallel: false,
|
||||
forbidOnly: Boolean(process.env.CI),
|
||||
retries: 0,
|
||||
workers: 1,
|
||||
reporter: 'list',
|
||||
timeout: 120_000,
|
||||
globalSetup: './e2e/global-setup.mjs',
|
||||
use: {
|
||||
browserName: 'firefox',
|
||||
serviceWorkers: 'block',
|
||||
launchOptions: { firefoxUserPrefs: { 'network.dns.disablePrefetch': true, 'network.prefetch-next': false, 'network.http.speculative-parallel-limit': 0 } },
|
||||
headless: true,
|
||||
trace: 'retain-on-failure',
|
||||
},
|
||||
})
|
||||
@ -1,4 +1,4 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import { configDefaults, defineConfig } from 'vitest/config'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import path from 'node:path'
|
||||
|
||||
@ -9,5 +9,6 @@ export default defineConfig({
|
||||
environment: 'jsdom',
|
||||
setupFiles: ['./vitest.setup.ts'],
|
||||
clearMocks: true,
|
||||
exclude: [...configDefaults.exclude, 'e2e/**'],
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user