package library import ( "context" "errors" "io" "log/slog" "path/filepath" "testing" "time" "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // A gate is taken by one holder at a time; a waiter gets it once the holder // lets go, and gives up when its context ends or its limit passes. func TestGate_OneHolderAndAWaiterThatCanGiveUp(t *testing.T) { g := make(gate, 1) if !g.tryAcquire() { t.Fatal("an empty gate could not be taken") } if g.tryAcquire() { t.Fatal("a held gate was taken a second time") } if err := g.acquire(context.Background(), 20*time.Millisecond); !errors.Is(err, errFilesBusy) { t.Errorf("waiting past the limit: %v, want errFilesBusy", err) } ctx, cancel := context.WithCancel(context.Background()) cancel() if err := g.acquire(ctx, time.Minute); !errors.Is(err, context.Canceled) { t.Errorf("waiting with an ended context: %v, want context.Canceled", err) } got := make(chan error, 1) go func() { got <- g.acquire(context.Background(), time.Minute) }() select { case err := <-got: t.Fatalf("a waiter got a held gate: %v", err) case <-time.After(50 * time.Millisecond): } g.release() select { case err := <-got: if err != nil { t.Errorf("a waiter after release: %v", err) } case <-time.After(5 * time.Second): t.Fatal("a waiter did not get the gate once it was released") } } // A scan that starts while a duplicate-resolver pass holds the files reads // none of them until the pass lets go, so no file it lists is removed under // it. func TestScanner_WaitsForAPassHoldingTheFiles_Integration(t *testing.T) { ctx := context.Background() pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } root := t.TempDir() writeTestMP3(t, filepath.Join(root, "Tin Orchard/Dusk/01.mp3"), map[string]string{ "TIT2": "Dusk", "TPE1": "Tin Orchard", "TALB": "Dusk", "TRCK": "1", }) scanner := New(pool, slog.New(slog.NewTextHandler(io.Discard, nil)), []string{root}, nil) if !filesGate.tryAcquire() { t.Fatal("the files gate was already held") } type result struct { stats Stats err error } done := make(chan result, 1) go func() { stats, err := scanner.Scan(ctx, nil) done <- result{stats, err} }() select { case r := <-done: filesGate.release() t.Fatalf("the scan ran while a pass held the files: %+v, %v", r.stats, r.err) case <-time.After(200 * time.Millisecond): } filesGate.release() select { case r := <-done: if r.err != nil || r.stats.Added != 1 { t.Errorf("scan after the pass: %+v, %v; want one song added", r.stats, r.err) } case <-time.After(30 * time.Second): t.Fatal("the scan did not run once the pass let go of the files") } }