package coverart import ( "context" "fmt" "os" "path/filepath" "testing" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "github.com/Fabled-Sword/minstrel/internal/db/dbq" "github.com/Fabled-Sword/minstrel/internal/dbtest" ) // stubArtistProvider is a configurable ArtistArtProvider for artist enricher // tests. Embeds fakeProvider for the base Provider methods; overrides // FetchArtistArt with controllable byte/error responses. type stubArtistProvider struct { fakeProvider thumb, fanart []byte err error } func (f *stubArtistProvider) FetchArtistArt(_ context.Context, _ ArtistRef) ([]byte, []byte, error) { return f.thumb, f.fanart, f.err } // insertArtist seeds a fresh artist via UpsertArtist and returns its UUID. // mbid may be "" to seed a MBID-less artist. func insertArtist(t *testing.T, q *dbq.Queries, ctx context.Context, name, mbid string) pgtype.UUID { t.Helper() var mbidParam *string if mbid != "" { mbidParam = &mbid } a, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{ Name: name, SortName: name, Mbid: mbidParam, }) if err != nil { t.Fatalf("insertArtist %q: %v", name, err) } return a.ID } // An artist is asked about when it has no art source yet, or when it was // settled as "none" under an older set of providers (the version counts // provider changes). One with art, or settled "none" under the current // providers, is left alone, and no file is written for it. func TestEnrichArtist_WhichArtistsAreAsked(t *testing.T) { pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) resetRegistryForTests() t.Cleanup(resetRegistryForTests) Register(&stubArtistProvider{ fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true}, thumb: []byte("thumb_bytes"), fanart: []byte("fanart_bytes"), }) e := newTestEnricher(t, pool) current := e.settings.CurrentVersion() dataDir := t.TempDir() for i, tc := range []struct { name string source string // "" leaves it NULL version int32 wantSource string wantAsked bool }{ {"no source yet", "", 0, "stub-artist", true}, {"art already found", "theaudiodb", current, "theaudiodb", false}, {"none under the current providers", "none", current, "none", false}, {"none under older providers", "none", current - 1, "stub-artist", true}, } { artistID := insertArtist(t, q, ctx, tc.name, fmt.Sprintf("0000000%d-1111-1111-1111-111111111111", i)) if tc.source != "" { src := tc.source if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{ ID: artistID, ArtistArtSource: &src, ArtistArtSourcesVersion: tc.version, }); err != nil { t.Fatalf("%s: set: %v", tc.name, err) } } if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { t.Fatalf("%s: EnrichArtist: %v", tc.name, err) } row, err := q.GetArtistByID(ctx, artistID) if err != nil { t.Fatal(err) } if row.ArtistArtSource == nil || *row.ArtistArtSource != tc.wantSource { t.Errorf("%s: source = %v, want %q", tc.name, row.ArtistArtSource, tc.wantSource) } _, statErr := os.Stat(filepath.Join(dataDir, "artist-art", uuidString(artistID), "thumb.jpg")) if asked := statErr == nil; asked != tc.wantAsked { t.Errorf("%s: thumb written = %v, want %v", tc.name, asked, tc.wantAsked) } } } // A provider with only one of the two pictures still settles the artist as // found: the picture it has is written and its path set, and the other path // stays NULL so the clients fall back rather than load a missing file. func TestEnrichArtist_OnePictureOfTwo(t *testing.T) { pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) resetRegistryForTests() t.Cleanup(resetRegistryForTests) stub := &stubArtistProvider{fakeProvider: fakeProvider{id: "one-picture", defaultOn: true}} Register(stub) e := newTestEnricher(t, pool) dataDir := t.TempDir() for i, tc := range []struct { name string thumb, fanart []byte }{ {"a thumbnail only", []byte("thumb_only"), nil}, {"fanart only", nil, []byte("fanart_only")}, } { stub.thumb, stub.fanart = tc.thumb, tc.fanart artistID := insertArtist(t, q, ctx, tc.name, fmt.Sprintf("5555555%d-5555-5555-5555-555555555555", i)) if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { t.Fatalf("%s: EnrichArtist: %v", tc.name, err) } row, err := q.GetArtistByID(ctx, artistID) if err != nil { t.Fatal(err) } if row.ArtistArtSource == nil || *row.ArtistArtSource != "one-picture" { t.Errorf("%s: source = %v, want one-picture", tc.name, row.ArtistArtSource) } for _, pic := range []struct { kind string path *string want []byte }{{"thumbnail", row.ArtistThumbPath, tc.thumb}, {"fanart", row.ArtistFanartPath, tc.fanart}} { if pic.want == nil { if pic.path != nil { t.Errorf("%s: %s path = %q, want NULL", tc.name, pic.kind, *pic.path) } continue } if pic.path == nil { t.Errorf("%s: %s path is NULL", tc.name, pic.kind) continue } if body, err := os.ReadFile(*pic.path); err != nil || string(body) != string(pic.want) { t.Errorf("%s: %s file = %q, %v; want %q", tc.name, pic.kind, body, err, pic.want) } } } } // --- All-404 settles to 'none' --- func TestEnrichArtist_All404_SettlesNone(t *testing.T) { pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) resetRegistryForTests() t.Cleanup(resetRegistryForTests) stub := &stubArtistProvider{ fakeProvider: fakeProvider{id: "404-provider", defaultOn: true}, err: ErrNotFound, } Register(stub) e := newTestEnricher(t, pool) artistID := insertArtist(t, q, ctx, "All404 Artist", "77777777-7777-7777-7777-777777777777") dataDir := t.TempDir() if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { t.Fatalf("EnrichArtist: %v", err) } row, err := q.GetArtistByID(ctx, artistID) if err != nil { t.Fatalf("GetArtistByID: %v", err) } if row.ArtistArtSource == nil || *row.ArtistArtSource != "none" { t.Errorf("source = %v, want 'none' (all providers 404)", row.ArtistArtSource) } if row.ArtistArtSourcesVersion != e.settings.CurrentVersion() { t.Errorf("version = %d, want %d", row.ArtistArtSourcesVersion, e.settings.CurrentVersion()) } } // --- Empty providers list settles vacuously to 'none' --- func TestEnrichArtist_EmptyProviders_SettlesNone(t *testing.T) { pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) // Register a plain provider that does NOT implement ArtistArtProvider — // EnabledArtistProviders will return an empty slice. resetRegistryForTests() t.Cleanup(resetRegistryForTests) Register(&fakeProvider{id: "album-only", defaultOn: true}) e := newTestEnricher(t, pool) artistID := insertArtist(t, q, ctx, "No Provider Artist", "88888888-8888-8888-8888-888888888888") dataDir := t.TempDir() if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { t.Fatalf("EnrichArtist: %v", err) } row, err := q.GetArtistByID(ctx, artistID) if err != nil { t.Fatalf("GetArtistByID: %v", err) } if row.ArtistArtSource == nil || *row.ArtistArtSource != "none" { t.Errorf("source = %v, want 'none' (vacuous all-404 with empty provider list)", row.ArtistArtSource) } } // --- ErrTransient leaves row NULL --- func TestEnrichArtist_ErrTransient_LeavesNull(t *testing.T) { pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) resetRegistryForTests() t.Cleanup(resetRegistryForTests) stub := &stubArtistProvider{ fakeProvider: fakeProvider{id: "transient-provider", defaultOn: true}, err: ErrTransient, } Register(stub) e := newTestEnricher(t, pool) artistID := insertArtist(t, q, ctx, "Transient Artist", "99999999-9999-9999-9999-999999999999") dataDir := t.TempDir() if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { t.Fatalf("EnrichArtist: %v", err) } row, err := q.GetArtistByID(ctx, artistID) if err != nil { t.Fatalf("GetArtistByID: %v", err) } // Transient: source must remain NULL (eligible for retry). if row.ArtistArtSource != nil { t.Errorf("source = %v, want nil (transient should not settle)", row.ArtistArtSource) } } // --- Filesystem layout --- func TestEnrichArtist_FilesystemLayout(t *testing.T) { pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) resetRegistryForTests() t.Cleanup(resetRegistryForTests) thumbBytes := []byte("thumb_content") fanartBytes := []byte("fanart_content") stub := &stubArtistProvider{ fakeProvider: fakeProvider{id: "layout-provider", defaultOn: true}, thumb: thumbBytes, fanart: fanartBytes, } Register(stub) e := newTestEnricher(t, pool) artistID := insertArtist(t, q, ctx, "Layout Artist", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") dataDir := t.TempDir() if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { t.Fatalf("EnrichArtist: %v", err) } artistIDStr := uuidString(artistID) thumbPath := filepath.Join(dataDir, "artist-art", artistIDStr, "thumb.jpg") fanartPath := filepath.Join(dataDir, "artist-art", artistIDStr, "fanart.jpg") thumbBody, rerr := os.ReadFile(thumbPath) if rerr != nil { t.Fatalf("read thumb.jpg: %v", rerr) } if string(thumbBody) != string(thumbBytes) { t.Errorf("thumb.jpg = %q, want %q", thumbBody, thumbBytes) } fanartBody, rerr := os.ReadFile(fanartPath) if rerr != nil { t.Fatalf("read fanart.jpg: %v", rerr) } if string(fanartBody) != string(fanartBytes) { t.Errorf("fanart.jpg = %q, want %q", fanartBody, fanartBytes) } row, err := q.GetArtistByID(ctx, artistID) if err != nil { t.Fatalf("GetArtistByID: %v", err) } if row.ArtistThumbPath == nil || *row.ArtistThumbPath != thumbPath { t.Errorf("DB thumb_path = %v, want %s", row.ArtistThumbPath, thumbPath) } if row.ArtistFanartPath == nil || *row.ArtistFanartPath != fanartPath { t.Errorf("DB fanart_path = %v, want %s", row.ArtistFanartPath, fanartPath) } } // --- CleanupArtistArt --- func TestCleanupArtistArt_RemovesDirectory(t *testing.T) { dataDir := t.TempDir() artistID := pgtype.UUID{ Bytes: [16]byte{0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb}, Valid: true, } artistDir := filepath.Join(dataDir, "artist-art", uuidString(artistID)) if err := os.MkdirAll(artistDir, 0o755); err != nil { t.Fatalf("mkdir: %v", err) } if err := os.WriteFile(filepath.Join(artistDir, "thumb.jpg"), []byte("x"), 0o644); err != nil { t.Fatalf("write: %v", err) } if err := CleanupArtistArt(dataDir, artistID); err != nil { t.Fatalf("CleanupArtistArt: %v", err) } if _, err := os.Stat(artistDir); !os.IsNotExist(err) { t.Errorf("directory still exists after cleanup: stat err = %v", err) } } func TestCleanupArtistArt_IdempotentMissingDir(t *testing.T) { dataDir := t.TempDir() artistID := pgtype.UUID{ Bytes: [16]byte{0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc}, Valid: true, } // Directory does not exist — should be a no-op. if err := CleanupArtistArt(dataDir, artistID); err != nil { t.Fatalf("CleanupArtistArt on missing dir: %v", err) } } // --- MBID guard --- func TestEnrichArtist_NoMBID_SettlesNone(t *testing.T) { pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) resetRegistryForTests() t.Cleanup(resetRegistryForTests) // No MBID still runs the provider chain (name-based providers can // resolve without one). An MBID-only provider returns ErrNotFound // for an empty MBID; with the whole chain returning ErrNotFound the // row settles 'none' (version-stamped), NOT NULL. stub := &stubArtistProvider{ fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true}, err: ErrNotFound, } Register(stub) e := newTestEnricher(t, pool) // Seed with no MBID. artistID := insertArtist(t, q, ctx, "No MBID Artist", "") dataDir := t.TempDir() if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { t.Fatalf("EnrichArtist: %v", err) } row, err := q.GetArtistByID(ctx, artistID) if err != nil { t.Fatalf("GetArtistByID: %v", err) } if row.ArtistArtSource == nil || *row.ArtistArtSource != "none" { t.Errorf("source = %v, want 'none' (settled)", row.ArtistArtSource) } } // artistChanges counts the change-log rows for an artist: what tells a // syncing app to fetch the artist again. func artistChanges(t *testing.T, pool *pgxpool.Pool, artistID pgtype.UUID) int { t.Helper() var n int if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM library_changes WHERE entity_type = 'artist' AND entity_id = $1`, artistID.String()).Scan(&n); err != nil { t.Fatalf("count changes: %v", err) } return n } // A picture found for an artist is logged as a change to it, so an app that // synced the artist before the picture arrived fetches it again. Settling // "none" changes nothing an app shows and logs nothing. func TestEnrichArtist_APictureFoundIsInTheSyncLog(t *testing.T) { pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) resetRegistryForTests() t.Cleanup(resetRegistryForTests) stub := &stubArtistProvider{ fakeProvider: fakeProvider{id: "sync-log-provider", defaultOn: true}, thumb: []byte("thumb"), } Register(stub) e := newTestEnricher(t, pool) found := insertArtist(t, q, ctx, "Pictured Artist", "88888888-8888-8888-8888-888888888888") before := artistChanges(t, pool, found) if err := e.EnrichArtist(ctx, found, t.TempDir()); err != nil { t.Fatalf("EnrichArtist: %v", err) } if got := artistChanges(t, pool, found); got != before+1 { t.Fatalf("change rows for the pictured artist = %d, want %d", got, before+1) } stub.thumb, stub.err = nil, ErrNotFound bare := insertArtist(t, q, ctx, "Unpictured Artist", "99999999-9999-9999-9999-999999999999") before = artistChanges(t, pool, bare) if err := e.EnrichArtist(ctx, bare, t.TempDir()); err != nil { t.Fatalf("EnrichArtist: %v", err) } if got := artistChanges(t, pool, bare); got != before { t.Fatalf("change rows for an artist settled none = %d, want %d", got, before) } }