package tracks import ( "context" "errors" "io" "log/slog" "os" "path/filepath" "testing" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/library" ) // --- test seed helpers (inlined; mirrors quarantine patterns) ----------- func newPool(t *testing.T) *pgxpool.Pool { t.Helper() if testing.Short() { t.Skip("skipping integration test in -short mode") } dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") if dsn == "" { t.Skip("MINSTREL_TEST_DATABASE_URL not set") } if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { t.Fatalf("migrate: %v", err) } pool, err := pgxpool.New(context.Background(), dsn) if err != nil { t.Fatalf("pool: %v", err) } t.Cleanup(pool.Close) dbtest.ResetDB(t, pool) return pool } func seedAdmin(t *testing.T, pool *pgxpool.Pool, name string) dbq.User { t.Helper() u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{ Username: dbtest.TestUserPrefix + name, PasswordHash: "x", ApiTokenHash: name + "-token", IsAdmin: true, }) if err != nil { t.Fatalf("seed admin %s: %v", name, err) } return u } // seedArtistAlbumTrack creates an artist + album + track triple. mbid is // set on both the album and the track when non-empty (the album mbid is // derived from the track mbid suffix); empty leaves both nil so the // track exercises the local-only path. filePath is the on-disk path // stored on the track row. Names are unique per call so multiple seeds // in one test don't collide on UNIQUE constraints. func seedArtistAlbumTrack(t *testing.T, pool *pgxpool.Pool, prefix, mbid, filePath string) (dbq.Artist, dbq.Album, dbq.Track) { t.Helper() q := dbq.New(pool) artist, err := q.UpsertArtist(context.Background(), dbq.UpsertArtistParams{ Name: prefix + " Artist", SortName: prefix + " Artist", }) if err != nil { t.Fatalf("artist: %v", err) } var albumMBIDPtr *string if mbid != "" { s := mbid + "-album" albumMBIDPtr = &s } album, err := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{ Title: prefix + " Album", SortTitle: prefix + " Album", ArtistID: artist.ID, Mbid: albumMBIDPtr, }) if err != nil { t.Fatalf("album: %v", err) } var trackMBIDPtr *string if mbid != "" { s := mbid trackMBIDPtr = &s } track, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{ Title: prefix + " Track", AlbumID: album.ID, ArtistID: artist.ID, DurationMs: 1000, FilePath: filePath, FileSize: 1, FileFormat: "mp3", Mbid: trackMBIDPtr, }) if err != nil { t.Fatalf("track: %v", err) } return artist, album, track } // --- tests -------------------------------------------------------------- // markMissing marks tracks as waiting for a file, as a scan that could not // find them would. func markMissing(t *testing.T, pool *pgxpool.Pool, ids ...pgtype.UUID) { t.Helper() if _, err := dbq.New(pool).MarkTracksMissing(context.Background(), ids); err != nil { t.Fatalf("mark missing: %v", err) } } func TestForgetTracks_NotFound(t *testing.T) { pool := newPool(t) admin := seedAdmin(t, pool, "alice") var bogus pgtype.UUID bogus.Bytes = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} bogus.Valid = true _, err := NewService(pool, nil, "").ForgetTracks(context.Background(), []pgtype.UUID{bogus}, admin.ID) if !errors.Is(err, ErrNotFound) { t.Errorf("err = %v, want ErrNotFound", err) } } // A track that has its file plays, and is not forgotten; nor is the waiting // track asked about with it. func TestForgetTracks_RefusesATrackThatHasItsFile(t *testing.T) { pool := newPool(t) admin := seedAdmin(t, pool, "alice") dir := t.TempDir() _, _, present := seedArtistAlbumTrack(t, pool, "Present", "", filepath.Join(dir, "p.mp3")) _, _, waiting := seedArtistAlbumTrack(t, pool, "Waiting", "", filepath.Join(dir, "w.mp3")) markMissing(t, pool, waiting.ID) _, err := NewService(pool, nil, "").ForgetTracks(context.Background(), []pgtype.UUID{waiting.ID, present.ID}, admin.ID) if !errors.Is(err, library.ErrTrackPresent) { t.Fatalf("err = %v, want library.ErrTrackPresent", err) } q := dbq.New(pool) for _, id := range []pgtype.UUID{present.ID, waiting.ID} { if _, err := q.GetTrackByID(context.Background(), id); err != nil { t.Errorf("track %v was forgotten by a refused forget: %v", id, err) } } } // Forget deletes the waiting tracks, tidies away the album and artist they // leave empty, and names each in the audit log. func TestForgetTracks_DeletesWaitingTracksAndAudits(t *testing.T) { pool := newPool(t) admin := seedAdmin(t, pool, "alice") if _, err := pool.Exec(context.Background(), `DELETE FROM audit_log`); err != nil { t.Fatalf("reset audit_log: %v", err) } path := filepath.Join(t.TempDir(), "lone.mp3") artist, album, track := seedArtistAlbumTrack(t, pool, "Lone", "", path) markMissing(t, pool, track.ID) gone, err := NewService(pool, nil, "").ForgetTracks(context.Background(), []pgtype.UUID{track.ID}, admin.ID) if err != nil { t.Fatalf("ForgetTracks: %v", err) } if len(gone) != 1 || gone[0].ID != track.ID { t.Fatalf("forgotten = %+v, want the one track", gone) } q := dbq.New(pool) if _, err := q.GetTrackByID(context.Background(), track.ID); err == nil { t.Errorf("track row still exists") } if _, err := q.GetAlbumByID(context.Background(), album.ID); err == nil { t.Errorf("album left empty still exists") } if _, err := q.GetArtistByID(context.Background(), artist.ID); err == nil { t.Errorf("artist left empty still exists") } var actor pgtype.UUID var title, filePath string if err := pool.QueryRow(context.Background(), ` SELECT actor_id, metadata->'tracks'->0->>'title', metadata->'tracks'->0->>'file_path' FROM audit_log WHERE action = 'track_forget'`).Scan(&actor, &title, &filePath); err != nil { t.Fatalf("read audit row: %v", err) } if actor != admin.ID || title != "Lone Track" || filePath != path { t.Errorf("audit = actor %v, %q, %q", actor, title, filePath) } } // An album that keeps another track is left alone. func TestForgetTracks_KeepsAnAlbumThatStillHasTracks(t *testing.T) { pool := newPool(t) admin := seedAdmin(t, pool, "alice") q := dbq.New(pool) ctx := context.Background() _, album, first := seedArtistAlbumTrack(t, pool, "Shared", "", filepath.Join(t.TempDir(), "a.mp3")) if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ Title: "Second", AlbumID: album.ID, ArtistID: first.ArtistID, DurationMs: 1000, FilePath: filepath.Join(t.TempDir(), "b.mp3"), FileSize: 1, FileFormat: "mp3", }); err != nil { t.Fatal(err) } markMissing(t, pool, first.ID) if _, err := NewService(pool, nil, "").ForgetTracks(ctx, []pgtype.UUID{first.ID}, admin.ID); err != nil { t.Fatalf("ForgetTracks: %v", err) } if _, err := q.GetAlbumByID(ctx, album.ID); err != nil { t.Errorf("album with a track left was removed: %v", err) } }