test: invented artists, albums and MusicBrainz ids in place of real ones
release / web (push) Failing after 1m16s
release / go (push) Successful in 1m48s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m0s
release / android (push) Successful in 4m34s
release / Build signed APK (push) Successful in 5m9s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped

Test data and example comments named real artists, records and songs, and
carried real MusicBrainz ids. One mapping swaps them for invented ones
throughout (Fields of Ontario, Plastic Apes, Marlo Davies, ...), keeping
what each case tests: sort order, index letter, escaping, title keys,
artist-prefix stripping. A test username is no longer the operator's name.

The cover-art and Last.fm connection checks still query real releases;
they reach live services and need something that exists there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 13:21:34 -05:00
co-authored by Claude Opus 5.5
parent 4244d81dfd
commit 4e1807cbba
80 changed files with 570 additions and 570 deletions
@@ -22,9 +22,9 @@ import kotlin.test.assertEquals
class AdminQuarantineViewModelTest { class AdminQuarantineViewModelTest {
private val row = AdminQuarantineItemRef( private val row = AdminQuarantineItemRef(
trackId = "t1", trackId = "t1",
trackTitle = "Roygbiv", trackTitle = "Prismatic",
artistName = "Boards of Canada", artistName = "Fields of Ontario",
albumTitle = "Geogaddi", albumTitle = "Geomantic",
albumId = "al1", albumId = "al1",
reportCount = 1, reportCount = 1,
) )
@@ -71,10 +71,10 @@ class HomeRepositoryTest {
assertEquals("al1", skeleton[0].id) assertEquals("al1", skeleton[0].id)
assertNull(skeleton[0].value) // skeleton in position assertNull(skeleton[0].value) // skeleton in position
albumFlow.value = AlbumRef(id = "al1", title = "Geogaddi", artistId = "a1") albumFlow.value = AlbumRef(id = "al1", title = "Geomantic", artistId = "a1")
val revealed = awaitItem() val revealed = awaitItem()
assertEquals("al1", revealed[0].id) assertEquals("al1", revealed[0].id)
assertEquals("Geogaddi", revealed[0].value?.title) // tile reveals assertEquals("Geomantic", revealed[0].value?.title) // tile reveals
cancelAndIgnoreRemainingEvents() cancelAndIgnoreRemainingEvents()
} }
} }
@@ -55,7 +55,7 @@ class LibraryRepositoryTest {
every { artistDao.observeAll() } returns every { artistDao.observeAll() } returns
flowOf( flowOf(
listOf( listOf(
CachedArtistEntity(id = "a1", name = "Boards of Canada", sortName = "Boards of Canada"), CachedArtistEntity(id = "a1", name = "Fields of Ontario", sortName = "Fields of Ontario"),
), ),
) )
// observeArtists now combines with albums (to derive the tile // observeArtists now combines with albums (to derive the tile
@@ -67,7 +67,7 @@ class LibraryRepositoryTest {
val first = awaitItem() val first = awaitItem()
assertEquals(1, first.size) assertEquals(1, first.size)
assertEquals("a1", first[0].id) assertEquals("a1", first[0].id)
assertEquals("Boards of Canada", first[0].name) assertEquals("Fields of Ontario", first[0].name)
awaitComplete() awaitComplete()
} }
} }
@@ -82,13 +82,13 @@ class LibraryRepositoryTest {
""" """
{ {
"id": "a1", "id": "a1",
"name": "Boards of Canada", "name": "Fields of Ontario",
"sort_name": "Boards of Canada", "sort_name": "Fields of Ontario",
"album_count": 2, "album_count": 2,
"cover_url": "", "cover_url": "",
"albums": [ "albums": [
{"id": "al1", "title": "Music Has the Right to Children", "artist_id": "a1", "sort_title": "Music Has the Right to Children"}, {"id": "al1", "title": "Music Has the Right to Wander", "artist_id": "a1", "sort_title": "Music Has the Right to Wander"},
{"id": "al2", "title": "Geogaddi", "artist_id": "a1", "sort_title": "Geogaddi"} {"id": "al2", "title": "Geomantic", "artist_id": "a1", "sort_title": "Geomantic"}
] ]
} }
""".trimIndent(), """.trimIndent(),
@@ -73,9 +73,9 @@ class LibraryViewModelTest {
fun `Success when DAOs emit content`() = runTest { fun `Success when DAOs emit content`() = runTest {
val repo = mockk<LibraryRepository>() val repo = mockk<LibraryRepository>()
every { repo.observeArtists() } returns every { repo.observeArtists() } returns
flowOf(listOf(ArtistRef(id = "a1", name = "Boards of Canada", sortName = "Boards"))) flowOf(listOf(ArtistRef(id = "a1", name = "Fields of Ontario", sortName = "Fields")))
every { repo.observeAlbums() } returns every { repo.observeAlbums() } returns
flowOf(listOf(AlbumRef(id = "al1", title = "Geogaddi", artistId = "a1"))) flowOf(listOf(AlbumRef(id = "al1", title = "Geomantic", artistId = "a1")))
val vm = LibraryViewModel( val vm = LibraryViewModel(
repo, repo,
+7 -7
View File
@@ -20,13 +20,13 @@ const docSample = `{
"status": "ok", "status": "ok",
"results": [{ "results": [{
"score": 1.0, "score": 1.0,
"id": "9ff43b6a-4f16-427c-93c2-92307ca505e0", "id": "0a11ce00-0000-4000-8000-000000000008",
"recordings": [{ "recordings": [{
"duration": 639, "duration": 639,
"releasegroups": [{"type": "Album", "id": "ddaa2d4d-314e-3e7c-b1d0-f6d207f5aa2f", "title": "Before the Dawn Heals Us"}], "releasegroups": [{"type": "Album", "id": "0a11ce00-0000-4000-8000-000000000006", "title": "Before the Dusk Finds Us"}],
"title": "Lower Your Eyelids to Die With the Sun", "title": "Lower Your Voice to Sing With the Moon",
"id": "cd2e7c47-16f5-46c6-a37c-a1eb7bf599ff", "id": "0a11ce00-0000-4000-8000-000000000005",
"artists": [{"id": "6d7b7cd4-254b-4c25-83f6-dd20f98ceacd", "name": "M83"}] "artists": [{"id": "0a11ce00-0000-4000-8000-000000000007", "name": "K47"}]
}] }]
}] }]
}` }`
@@ -55,8 +55,8 @@ func TestParseLookup(t *testing.T) {
}{ }{
{"single match", docSample, []Candidate{{ {"single match", docSample, []Candidate{{
Recording: Recording{ Recording: Recording{
ID: "cd2e7c47-16f5-46c6-a37c-a1eb7bf599ff", Title: "Lower Your Eyelids to Die With the Sun", ID: "0a11ce00-0000-4000-8000-000000000005", Title: "Lower Your Voice to Sing With the Moon",
DurationSec: 639, Artists: []string{"M83"}, DurationSec: 639, Artists: []string{"K47"},
}, },
Score: 1.0, Score: 1.0,
}}}, }}},
+4 -4
View File
@@ -28,14 +28,14 @@ func TestFoldDuplicateGroups(t *testing.T) {
rows := []dbq.ListPendingDuplicateGroupMembersRow{ rows := []dbq.ListPendingDuplicateGroupMembersRow{
// Group 1: identical audio, sizes tie, the older copy should be kept. // Group 1: identical audio, sizes tie, the older copy should be kept.
{GroupID: dupUUID(1), Tier: "exact", DetectedAt: dupTS(newer), TrackID: dupUUID(10), {GroupID: dupUUID(1), Tier: "exact", DetectedAt: dupTS(newer), TrackID: dupUUID(10),
Title: "WWW", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(newer), PlayCount: 3}, Title: "XYZ", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(newer), PlayCount: 3},
{GroupID: dupUUID(1), Tier: "exact", DetectedAt: dupTS(newer), TrackID: dupUUID(11), {GroupID: dupUUID(1), Tier: "exact", DetectedAt: dupTS(newer), TrackID: dupUUID(11),
Title: "WWW", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(older), LikeCount: 1}, Title: "XYZ", FileFormat: "mp3", FileSize: 6_900_000, DurationMs: 215_400, AddedAt: dupTS(older), LikeCount: 1},
// Group 2: the same recording, FLAC against MP3. // Group 2: the same recording, FLAC against MP3.
{GroupID: dupUUID(2), Tier: "acoustic", WorstBitErrorRate: &ber, DetectedAt: dupTS(older), TrackID: dupUUID(20), {GroupID: dupUUID(2), Tier: "acoustic", WorstBitErrorRate: &ber, DetectedAt: dupTS(older), TrackID: dupUUID(20),
Title: "Lovesick", FileFormat: "mp3", FileSize: 9_000_000, DurationMs: 198_000, AddedAt: dupTS(older)}, Title: "Homesick", FileFormat: "mp3", FileSize: 9_000_000, DurationMs: 198_000, AddedAt: dupTS(older)},
{GroupID: dupUUID(2), Tier: "acoustic", WorstBitErrorRate: &ber, DetectedAt: dupTS(older), TrackID: dupUUID(21), {GroupID: dupUUID(2), Tier: "acoustic", WorstBitErrorRate: &ber, DetectedAt: dupTS(older), TrackID: dupUUID(21),
Title: "Lovesick", FileFormat: "flac", FileSize: 30_000_000, DurationMs: 198_000, AddedAt: dupTS(newer)}, Title: "Homesick", FileFormat: "flac", FileSize: 30_000_000, DurationMs: 198_000, AddedAt: dupTS(newer)},
} }
got := foldDuplicateGroups(rows) got := foldDuplicateGroups(rows)
@@ -15,11 +15,11 @@ func TestHandleExportMissingTracks_Integration(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
admin := seedUser(t, pool, "export-admin", "pw", true) admin := seedUser(t, pool, "export-admin", "pw", true)
artist := seedArtist(t, pool, "Boards of Canada") artist := seedArtist(t, pool, "Fields of Ontario")
album := seedAlbum(t, pool, artist.ID, "Geogaddi", 2002) album := seedAlbum(t, pool, artist.ID, "Geomantic", 2002)
gone := seedTrack(t, pool, album.ID, artist.ID, "Music Is Math", 0, 300_000) gone := seedTrack(t, pool, album.ID, artist.ID, "Music Is Maps", 0, 300_000)
removed := seedTrack(t, pool, album.ID, artist.ID, "Dawn Chorus", 2, 240_000) removed := seedTrack(t, pool, album.ID, artist.ID, "Dusk Chorus", 2, 240_000)
seedTrack(t, pool, album.ID, artist.ID, "Julie and Candy", 3, 200_000) seedTrack(t, pool, album.ID, artist.ID, "Julia and Cane", 3, 200_000)
ctx := context.Background() ctx := context.Background()
if _, err := pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE id = $1`, gone.ID); err != nil { if _, err := pool.Exec(ctx, `UPDATE tracks SET missing_since = now() WHERE id = $1`, gone.ID); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -46,10 +46,10 @@ func TestHandleExportMissingTracks_Integration(t *testing.T) {
for _, r := range rows[1:] { for _, r := range rows[1:] {
byTitle[r[4]] = r byTitle[r[4]] = r
} }
if r := byTitle["Music Is Math"]; r == nil || r[3] != "" || r[5] != "" || r[7] != "missing" { if r := byTitle["Music Is Maps"]; r == nil || r[3] != "" || r[5] != "" || r[7] != "missing" {
t.Errorf("untagged missing row = %v, want no track number, no mbid, why missing", r) t.Errorf("untagged missing row = %v, want no track number, no mbid, why missing", r)
} }
if r := byTitle["Dawn Chorus"]; r == nil || r[3] != "2" || r[5] != "rec-dawn" || r[7] != "report" { if r := byTitle["Dusk Chorus"]; r == nil || r[3] != "2" || r[5] != "rec-dawn" || r[7] != "report" {
t.Errorf("removed row = %v, want track 2, its mbid, why report", r) t.Errorf("removed row = %v, want track 2, its mbid, why report", r)
} }
} }
@@ -60,8 +60,8 @@ func TestHandleForgetMissingTracks_Integration(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
admin := seedUser(t, pool, "forget-admin", "pw", true) admin := seedUser(t, pool, "forget-admin", "pw", true)
artist := seedArtist(t, pool, "Autechre") artist := seedArtist(t, pool, "Autoglyph")
album := seedAlbum(t, pool, artist.ID, "Amber", 1994) album := seedAlbum(t, pool, artist.ID, "Ochre", 1994)
waiting := seedTrack(t, pool, album.ID, artist.ID, "Foil", 1, 300_000) waiting := seedTrack(t, pool, album.ID, artist.ID, "Foil", 1, 300_000)
present := seedTrack(t, pool, album.ID, artist.ID, "Montreal", 2, 300_000) present := seedTrack(t, pool, album.ID, artist.ID, "Montreal", 2, 300_000)
ctx := context.Background() ctx := context.Background()
+4 -4
View File
@@ -29,9 +29,9 @@ func TestGroupMissingByDirectory(t *testing.T) {
t.Run("consecutive rows in one directory collapse to one group", func(t *testing.T) { t.Run("consecutive rows in one directory collapse to one group", func(t *testing.T) {
groups := groupMissingByDirectory([]dbq.ListMissingTracksRow{ groups := groupMissingByDirectory([]dbq.ListMissingTracksRow{
missingRow("/music/Linkin Park/Minutes to Midnight", "Given Up", base), missingRow("/music/Lincoln Yard/Minutes to Noon", "Given Up", base),
missingRow("/music/Linkin Park/Minutes to Midnight", "Leave Out All the Rest", base), missingRow("/music/Lincoln Yard/Minutes to Noon", "Leave Out All the Rest", base),
missingRow("/music/Linkin Park/Minutes to Midnight", "Bleed It Out", base), missingRow("/music/Lincoln Yard/Minutes to Noon", "Bleed It Out", base),
}) })
if len(groups) != 1 { if len(groups) != 1 {
@@ -40,7 +40,7 @@ func TestGroupMissingByDirectory(t *testing.T) {
if got := len(groups[0].Tracks); got != 3 { if got := len(groups[0].Tracks); got != 3 {
t.Errorf("want 3 tracks in the group, got %d", got) t.Errorf("want 3 tracks in the group, got %d", got)
} }
if groups[0].Directory != "/music/Linkin Park/Minutes to Midnight" { if groups[0].Directory != "/music/Lincoln Yard/Minutes to Noon" {
t.Errorf("unexpected directory %q", groups[0].Directory) t.Errorf("unexpected directory %q", groups[0].Directory)
} }
}) })
+1 -1
View File
@@ -38,7 +38,7 @@ type suspectTrackView struct {
} }
// suspectGroupView is a folder's worth of flagged tracks. As on the // suspectGroupView is a folder's worth of flagged tracks. As on the
// missing-files report, the folder is the unit of decision: Humanz was 62 rows // missing-files report, the folder is the unit of decision: Mammalz was 62 rows
// in one folder, which is one problem to look at, not 62. // in one folder, which is one problem to look at, not 62.
type suspectGroupView struct { type suspectGroupView struct {
Directory string `json:"directory"` Directory string `json:"directory"`
+15 -15
View File
@@ -16,14 +16,14 @@ func TestHandleListSuspectSources_Integration(t *testing.T) {
truncateLibrary(t, pool) truncateLibrary(t, pool)
admin := seedUser(t, pool, "suspect-admin", "pw", true) admin := seedUser(t, pool, "suspect-admin", "pw", true)
artist := seedArtist(t, pool, "Gorillaz") artist := seedArtist(t, pool, "Plastic Apes")
humanz := seedAlbum(t, pool, artist.ID, "Humanz", 2017) mammalz := seedAlbum(t, pool, artist.ID, "Mammalz", 2017)
seedTrack(t, pool, humanz.ID, artist.ID, "Saturnz Barz (Official Video)", 1, 180_000) seedTrack(t, pool, mammalz.ID, artist.ID, "Neptunez Barz (Official Video)", 1, 180_000)
seedTrack(t, pool, humanz.ID, artist.ID, "Momentz (Visualizer)", 2, 200_000) seedTrack(t, pool, mammalz.ID, artist.ID, "Minutez (Visualizer)", 2, 200_000)
seedTrack(t, pool, humanz.ID, artist.ID, "Andromeda [Audio]", 3, 190_000) seedTrack(t, pool, mammalz.ID, artist.ID, "Cassiopeia [Audio]", 3, 190_000)
seedTrack(t, pool, humanz.ID, artist.ID, "Chain Reaction", 4, 190_000) seedTrack(t, pool, mammalz.ID, artist.ID, "Chain Reaction", 4, 190_000)
seedTrack(t, pool, humanz.ID, artist.ID, "Busted and Blue", 5, 190_000) seedTrack(t, pool, mammalz.ID, artist.ID, "Bruised and Grey", 5, 190_000)
gone := seedTrack(t, pool, humanz.ID, artist.ID, "Ascension (Lyric Video)", 6, 156_000) gone := seedTrack(t, pool, mammalz.ID, artist.ID, "Elevation (Lyric Video)", 6, 156_000)
if _, err := pool.Exec(context.Background(), if _, err := pool.Exec(context.Background(),
`UPDATE tracks SET missing_since = now() WHERE id = $1`, gone.ID); err != nil { `UPDATE tracks SET missing_since = now() WHERE id = $1`, gone.ID); err != nil {
t.Fatalf("mark missing: %v", err) t.Fatalf("mark missing: %v", err)
@@ -54,9 +54,9 @@ func TestHandleListSuspectSources_Integration(t *testing.T) {
got[tr.Title] = tr.Markers got[tr.Title] = tr.Markers
} }
want := map[string][]string{ want := map[string][]string{
"Saturnz Barz (Official Video)": {"music video"}, "Neptunez Barz (Official Video)": {"music video"},
"Momentz (Visualizer)": {"visualiser"}, "Minutez (Visualizer)": {"visualiser"},
"Andromeda [Audio]": {"[Audio]"}, "Cassiopeia [Audio]": {"[Audio]"},
} }
if len(got) != len(want) { if len(got) != len(want) {
t.Fatalf("tracks = %v, want %v", got, want) t.Fatalf("tracks = %v, want %v", got, want)
@@ -74,10 +74,10 @@ func TestHandleRemoveSuspectSourceFile_Integration(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
admin := seedUser(t, pool, "suspect-remover", "pw", true) admin := seedUser(t, pool, "suspect-remover", "pw", true)
artist := seedArtist(t, pool, "Gorillaz") artist := seedArtist(t, pool, "Plastic Apes")
humanz := seedAlbum(t, pool, artist.ID, "Humanz", 2017) mammalz := seedAlbum(t, pool, artist.ID, "Mammalz", 2017)
rip := seedTrack(t, pool, humanz.ID, artist.ID, "Saturnz Barz (Official Video)", 1, 180_000) rip := seedTrack(t, pool, mammalz.ID, artist.ID, "Neptunez Barz (Official Video)", 1, 180_000)
clean := seedTrack(t, pool, humanz.ID, artist.ID, "Chain Reaction", 4, 190_000) clean := seedTrack(t, pool, mammalz.ID, artist.ID, "Chain Reaction", 4, 190_000)
remove := func(id string) int { remove := func(id string) int {
req := httptest.NewRequest(http.MethodPost, "/api/admin/library/suspect-sources/"+id+"/remove", nil) req := httptest.NewRequest(http.MethodPost, "/api/admin/library/suspect-sources/"+id+"/remove", nil)
+8 -8
View File
@@ -80,12 +80,12 @@ func TestCoverURLAndStreamURL(t *testing.T) {
func TestArtistRefFrom(t *testing.T) { func TestArtistRefFrom(t *testing.T) {
var id pgtype.UUID var id pgtype.UUID
_ = id.Scan("00112233-4455-6677-8899-aabbccddeeff") _ = id.Scan("00112233-4455-6677-8899-aabbccddeeff")
a := dbq.Artist{ID: id, Name: "Beatles", SortName: "Beatles"} a := dbq.Artist{ID: id, Name: "Copper Lanterns", SortName: "Copper Lanterns"}
got := artistRefFrom(a, 7) got := artistRefFrom(a, 7)
if got.ID != "00112233-4455-6677-8899-aabbccddeeff" { if got.ID != "00112233-4455-6677-8899-aabbccddeeff" {
t.Errorf("ID = %q", got.ID) t.Errorf("ID = %q", got.ID)
} }
if got.Name != "Beatles" || got.AlbumCount != 7 { if got.Name != "Copper Lanterns" || got.AlbumCount != 7 {
t.Errorf("ref = %+v", got) t.Errorf("ref = %+v", got)
} }
} }
@@ -96,9 +96,9 @@ func TestAlbumRefFrom(t *testing.T) {
_ = artID.Scan("00000000-0000-0000-0000-000000000002") _ = artID.Scan("00000000-0000-0000-0000-000000000002")
var rel pgtype.Date var rel pgtype.Date
_ = rel.Scan("1969-09-26") _ = rel.Scan("1969-09-26")
a := dbq.Album{ID: aid, Title: "Abbey Road", ArtistID: artID, ReleaseDate: rel} a := dbq.Album{ID: aid, Title: "Harbour Street", ArtistID: artID, ReleaseDate: rel}
got := albumRefFrom(a, "Beatles", 17, 2820) got := albumRefFrom(a, "Copper Lanterns", 17, 2820)
if got.Title != "Abbey Road" || got.ArtistName != "Beatles" { if got.Title != "Harbour Street" || got.ArtistName != "Copper Lanterns" {
t.Errorf("ref = %+v", got) t.Errorf("ref = %+v", got)
} }
if got.TrackCount != 17 || got.DurationSec != 2820 { if got.TrackCount != 17 || got.DurationSec != 2820 {
@@ -120,12 +120,12 @@ func TestTrackRefFrom(t *testing.T) {
trackNum := int32(3) trackNum := int32(3)
discNum := int32(1) discNum := int32(1)
t2 := dbq.Track{ t2 := dbq.Track{
ID: tid, Title: "Something", AlbumID: aid, ArtistID: artID, ID: tid, Title: "Somewhere Near", AlbumID: aid, ArtistID: artID,
TrackNumber: &trackNum, DiscNumber: &discNum, TrackNumber: &trackNum, DiscNumber: &discNum,
DurationMs: 183_000, DurationMs: 183_000,
} }
got := trackRefFrom(t2, "Abbey Road", "Beatles") got := trackRefFrom(t2, "Harbour Street", "Copper Lanterns")
if got.Title != "Something" || got.AlbumTitle != "Abbey Road" || got.ArtistName != "Beatles" { if got.Title != "Somewhere Near" || got.AlbumTitle != "Harbour Street" || got.ArtistName != "Copper Lanterns" {
t.Errorf("ref = %+v", got) t.Errorf("ref = %+v", got)
} }
if got.TrackNumber != 3 || got.DiscNumber != 1 { if got.TrackNumber != 3 || got.DiscNumber != 1 {
+4 -4
View File
@@ -28,8 +28,8 @@ func TestHandleEvents_PlayStartedReturnsIDs(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
user := seedUser(t, pool, "alice", "x", false) user := seedUser(t, pool, "alice", "x", false)
artist := seedArtist(t, pool, "Beatles") artist := seedArtist(t, pool, "Copper Lanterns")
album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969)
track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)
body, _ := json.Marshal(map[string]any{ body, _ := json.Marshal(map[string]any{
@@ -56,8 +56,8 @@ func TestHandleEvents_PlayEndedClosesRow(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
user := seedUser(t, pool, "alice", "x", false) user := seedUser(t, pool, "alice", "x", false)
artist := seedArtist(t, pool, "Beatles") artist := seedArtist(t, pool, "Copper Lanterns")
album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969)
track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)
startedID := postPlayStartedHelper(t, h, user, track.ID) startedID := postPlayStartedHelper(t, h, user, track.ID)
+3 -3
View File
@@ -12,7 +12,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/library" "git.fabledsword.com/bvandeusen/minstrel/internal/library"
) )
const removeTestPath = "/music/Moe Shop/WWW (2020)/01 - WWW.mp3" const removeTestPath = "/music/Mochi Shop/XYZ (2020)/01 - XYZ.mp3"
// removeFailure builds the error a delete service returns when the file would // removeFailure builds the error a delete service returns when the file would
// not go, wrapped the way quarantine.DeleteFile and quarantine.RemoveFile // not go, wrapped the way quarantine.DeleteFile and quarantine.RemoveFile
@@ -35,7 +35,7 @@ func TestFileRemoveAPIError(t *testing.T) {
{ {
name: "read-only mount", errno: syscall.EROFS, name: "read-only mount", errno: syscall.EROFS,
wantStatus: http.StatusConflict, wantCode: "library_not_writable", wantStatus: http.StatusConflict, wantCode: "library_not_writable",
wantIn: []string{"uid 1000, gid 1000", "/music/Moe Shop/WWW (2020)", "read-only file system", "Nothing was deleted"}, wantIn: []string{"uid 1000, gid 1000", "/music/Mochi Shop/XYZ (2020)", "read-only file system", "Nothing was deleted"},
}, },
{ {
name: "permission denied", errno: syscall.EACCES, name: "permission denied", errno: syscall.EACCES,
@@ -77,7 +77,7 @@ func TestFileRemoveAPIError(t *testing.T) {
// plain "contains the directory" check could never catch that regression. // plain "contains the directory" check could never catch that regression.
func TestFileRemoveAPIError_NotWritableNamesTheDirectoryNotTheFile(t *testing.T) { func TestFileRemoveAPIError_NotWritableNamesTheDirectoryNotTheFile(t *testing.T) {
apiErr, _ := fileRemoveAPIError(removeFailure(syscall.EROFS)) apiErr, _ := fileRemoveAPIError(removeFailure(syscall.EROFS))
if strings.Contains(apiErr.Message, "01 - WWW.mp3") { if strings.Contains(apiErr.Message, "01 - XYZ.mp3") {
t.Fatalf("message names the file rather than its directory: %q", apiErr.Message) t.Fatalf("message names the file rather than its directory: %q", apiErr.Message)
} }
} }
+1 -1
View File
@@ -53,7 +53,7 @@ func TestLibrarySync_AfterArtistUpsert_ReturnsHydratedPayload(t *testing.T) {
var artistID string var artistID string
if err := tx.QueryRow(ctx, if err := tx.QueryRow(ctx,
`INSERT INTO artists (name, sort_name) VALUES ($1, $2) RETURNING id::text`, `INSERT INTO artists (name, sort_name) VALUES ($1, $2) RETURNING id::text`,
"Boards of Canada", "Boards of Canada", "Fields of Ontario", "Fields of Ontario",
).Scan(&artistID); err != nil { ).Scan(&artistID); err != nil {
t.Fatalf("insert artist: %v", err) t.Fatalf("insert artist: %v", err)
} }
+3 -3
View File
@@ -41,7 +41,7 @@ func assertJSONKeys(t *testing.T, label string, b []byte, want []string) {
} }
func TestArtistSyncView_WireKeys(t *testing.T) { func TestArtistSyncView_WireKeys(t *testing.T) {
a := dbq.Artist{ID: validUUID, Name: "Aphex Twin", SortName: "Aphex Twin"} a := dbq.Artist{ID: validUUID, Name: "Apex Sibling", SortName: "Apex Sibling"}
b, err := json.Marshal(toArtistSyncView(a)) b, err := json.Marshal(toArtistSyncView(a))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -53,7 +53,7 @@ func TestArtistSyncView_WireKeys(t *testing.T) {
} }
func TestAlbumSyncView_WireKeys(t *testing.T) { func TestAlbumSyncView_WireKeys(t *testing.T) {
a := dbq.Album{ID: validUUID, ArtistID: validUUID, Title: "Drukqs", SortTitle: "Drukqs"} a := dbq.Album{ID: validUUID, ArtistID: validUUID, Title: "Drumkits", SortTitle: "Drumkits"}
b, err := json.Marshal(toAlbumSyncView(a, library.ReplayGain{})) b, err := json.Marshal(toAlbumSyncView(a, library.ReplayGain{}))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -67,7 +67,7 @@ func TestAlbumSyncView_WireKeys(t *testing.T) {
func TestTrackSyncView_WireKeys(t *testing.T) { func TestTrackSyncView_WireKeys(t *testing.T) {
tr := dbq.Track{ tr := dbq.Track{
ID: validUUID, AlbumID: validUUID, ArtistID: validUUID, ID: validUUID, AlbumID: validUUID, ArtistID: validUUID,
Title: "Avril 14th", DurationMs: 121_000, Title: "Juin 21st", DurationMs: 121_000,
FilePath: "x", FileFormat: "flac", FilePath: "x", FileFormat: "flac",
} }
b, err := json.Marshal(toTrackSyncView(tr, library.ReplayGain{})) b, err := json.Marshal(toTrackSyncView(tr, library.ReplayGain{}))
+25 -25
View File
@@ -59,9 +59,9 @@ func injectFakeUserForTest(next http.Handler) http.Handler {
func TestHandleGetTrack_HappyPath(t *testing.T) { func TestHandleGetTrack_HappyPath(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
artist := seedArtist(t, pool, "Beatles") artist := seedArtist(t, pool, "Copper Lanterns")
album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969)
track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) track := seedTrack(t, pool, album.ID, artist.ID, "Somewhere Near", 3, 183_000)
req := httptest.NewRequest(http.MethodGet, "/api/tracks/"+uuidToString(track.ID), nil) req := httptest.NewRequest(http.MethodGet, "/api/tracks/"+uuidToString(track.ID), nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@@ -74,7 +74,7 @@ func TestHandleGetTrack_HappyPath(t *testing.T) {
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v body=%s", err, w.Body.String()) t.Fatalf("decode: %v body=%s", err, w.Body.String())
} }
if got.Title != "Something" || got.AlbumTitle != "Abbey Road" || got.ArtistName != "Beatles" { if got.Title != "Somewhere Near" || got.AlbumTitle != "Harbour Street" || got.ArtistName != "Copper Lanterns" {
t.Errorf("ref = %+v", got) t.Errorf("ref = %+v", got)
} }
if got.TrackNumber != 3 || got.DurationSec != 183 { if got.TrackNumber != 3 || got.DurationSec != 183 {
@@ -111,10 +111,10 @@ func TestHandleGetTrack_NotFound(t *testing.T) {
func TestHandleGetAlbum_HappyPath(t *testing.T) { func TestHandleGetAlbum_HappyPath(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
artist := seedArtist(t, pool, "Beatles") artist := seedArtist(t, pool, "Copper Lanterns")
album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969)
seedTrack(t, pool, album.ID, artist.ID, "Come Together", 1, 259_000) seedTrack(t, pool, album.ID, artist.ID, "Come Along", 1, 259_000)
seedTrack(t, pool, album.ID, artist.ID, "Something", 2, 183_000) seedTrack(t, pool, album.ID, artist.ID, "Somewhere Near", 2, 183_000)
req := httptest.NewRequest(http.MethodGet, "/api/albums/"+uuidToString(album.ID), nil) req := httptest.NewRequest(http.MethodGet, "/api/albums/"+uuidToString(album.ID), nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@@ -127,13 +127,13 @@ func TestHandleGetAlbum_HappyPath(t *testing.T) {
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v body=%s", err, w.Body.String()) t.Fatalf("decode: %v body=%s", err, w.Body.String())
} }
if got.Title != "Abbey Road" || got.ArtistName != "Beatles" || got.Year != 1969 { if got.Title != "Harbour Street" || got.ArtistName != "Copper Lanterns" || got.Year != 1969 {
t.Errorf("album = %+v", got) t.Errorf("album = %+v", got)
} }
if len(got.Tracks) != 2 { if len(got.Tracks) != 2 {
t.Fatalf("tracks len = %d, want 2", len(got.Tracks)) t.Fatalf("tracks len = %d, want 2", len(got.Tracks))
} }
if got.Tracks[0].Title != "Come Together" || got.Tracks[1].Title != "Something" { if got.Tracks[0].Title != "Come Along" || got.Tracks[1].Title != "Somewhere Near" {
t.Errorf("tracks = %+v", got.Tracks) t.Errorf("tracks = %+v", got.Tracks)
} }
if got.TrackCount != 2 || got.DurationSec != 442 { // 259 + 183 if got.TrackCount != 2 || got.DurationSec != 442 { // 259 + 183
@@ -180,7 +180,7 @@ func TestHandleGetAlbum_EachTrackNamesItsOwnArtist(t *testing.T) {
func TestHandleGetAlbum_NoTracks(t *testing.T) { func TestHandleGetAlbum_NoTracks(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
artist := seedArtist(t, pool, "Beatles") artist := seedArtist(t, pool, "Copper Lanterns")
album := seedAlbum(t, pool, artist.ID, "Empty", 0) album := seedAlbum(t, pool, artist.ID, "Empty", 0)
req := httptest.NewRequest(http.MethodGet, "/api/albums/"+uuidToString(album.ID), nil) req := httptest.NewRequest(http.MethodGet, "/api/albums/"+uuidToString(album.ID), nil)
@@ -230,11 +230,11 @@ func TestHandleGetAlbum_NotFound(t *testing.T) {
func TestHandleGetArtist_HappyPath(t *testing.T) { func TestHandleGetArtist_HappyPath(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
artist := seedArtist(t, pool, "Beatles") artist := seedArtist(t, pool, "Copper Lanterns")
album1 := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) album1 := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969)
album2 := seedAlbum(t, pool, artist.ID, "Let It Be", 1970) album2 := seedAlbum(t, pool, artist.ID, "Let It Ride", 1970)
seedTrack(t, pool, album1.ID, artist.ID, "Something", 3, 183_000) seedTrack(t, pool, album1.ID, artist.ID, "Somewhere Near", 3, 183_000)
seedTrack(t, pool, album2.ID, artist.ID, "Get Back", 1, 189_000) seedTrack(t, pool, album2.ID, artist.ID, "Get Going", 1, 189_000)
req := httptest.NewRequest(http.MethodGet, "/api/artists/"+uuidToString(artist.ID), nil) req := httptest.NewRequest(http.MethodGet, "/api/artists/"+uuidToString(artist.ID), nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@@ -247,7 +247,7 @@ func TestHandleGetArtist_HappyPath(t *testing.T) {
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v body=%s", err, w.Body.String()) t.Fatalf("decode: %v body=%s", err, w.Body.String())
} }
if got.Name != "Beatles" { if got.Name != "Copper Lanterns" {
t.Errorf("name = %q", got.Name) t.Errorf("name = %q", got.Name)
} }
if got.AlbumCount != 2 { if got.AlbumCount != 2 {
@@ -256,13 +256,13 @@ func TestHandleGetArtist_HappyPath(t *testing.T) {
if len(got.Albums) != 2 { if len(got.Albums) != 2 {
t.Fatalf("albums len = %d, want 2", len(got.Albums)) t.Fatalf("albums len = %d, want 2", len(got.Albums))
} }
// ListAlbumsByArtist orders by release_date then sort_title; Abbey Road // ListAlbumsByArtist orders by release_date then sort_title; Harbour Street
// (1969) first. // (1969) first.
if got.Albums[0].Title != "Abbey Road" { if got.Albums[0].Title != "Harbour Street" {
t.Errorf("first album = %q, want Abbey Road", got.Albums[0].Title) t.Errorf("first album = %q, want Harbour Street", got.Albums[0].Title)
} }
for _, a := range got.Albums { for _, a := range got.Albums {
if a.ArtistName != "Beatles" { if a.ArtistName != "Copper Lanterns" {
t.Errorf("album.artist_name = %q", a.ArtistName) t.Errorf("album.artist_name = %q", a.ArtistName)
} }
if a.CoverURL == "" { if a.CoverURL == "" {
@@ -321,9 +321,9 @@ func TestHandleGetArtist_NotFound(t *testing.T) {
func TestHandleListArtists_DefaultAlpha(t *testing.T) { func TestHandleListArtists_DefaultAlpha(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
seedArtist(t, pool, "Beatles") seedArtist(t, pool, "Copper Lanterns")
seedArtist(t, pool, "ABBA") seedArtist(t, pool, "ABAB")
seedArtist(t, pool, "Zeppelin") seedArtist(t, pool, "Zephyrine")
req := httptest.NewRequest(http.MethodGet, "/api/artists", nil) req := httptest.NewRequest(http.MethodGet, "/api/artists", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@@ -345,7 +345,7 @@ func TestHandleListArtists_DefaultAlpha(t *testing.T) {
if len(got.Items) != 3 { if len(got.Items) != 3 {
t.Fatalf("items len = %d", len(got.Items)) t.Fatalf("items len = %d", len(got.Items))
} }
if got.Items[0].Name != "ABBA" || got.Items[2].Name != "Zeppelin" { if got.Items[0].Name != "ABAB" || got.Items[2].Name != "Zephyrine" {
t.Errorf("alpha order wrong: %q, %q, %q", got.Items[0].Name, got.Items[1].Name, got.Items[2].Name) t.Errorf("alpha order wrong: %q, %q, %q", got.Items[0].Name, got.Items[1].Name, got.Items[2].Name)
} }
} }
+4 -4
View File
@@ -41,8 +41,8 @@ func TestLikeTrack_Idempotent(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
user := seedUser(t, pool, "alice", "x", false) user := seedUser(t, pool, "alice", "x", false)
artist := seedArtist(t, pool, "Beatles") artist := seedArtist(t, pool, "Copper Lanterns")
album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969)
track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)
w := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID)) w := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID))
@@ -84,8 +84,8 @@ func TestUnlikeTrack_IdempotentEvenWhenAbsent(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
user := seedUser(t, pool, "alice", "x", false) user := seedUser(t, pool, "alice", "x", false)
artist := seedArtist(t, pool, "Beatles") artist := seedArtist(t, pool, "Copper Lanterns")
album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969) album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969)
track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)
w := callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(track.ID)) w := callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(track.ID))
+8 -8
View File
@@ -10,11 +10,11 @@ import (
func TestHandleSearch_ThreeFacets(t *testing.T) { func TestHandleSearch_ThreeFacets(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
artist := seedArtist(t, pool, "Beatles") artist := seedArtist(t, pool, "Copper Lanterns")
album := seedAlbum(t, pool, artist.ID, "Beatles Greatest", 1982) album := seedAlbum(t, pool, artist.ID, "Copper Lanterns Greatest", 1982)
seedTrack(t, pool, album.ID, artist.ID, "Beatles Jam", 1, 60_000) seedTrack(t, pool, album.ID, artist.ID, "Copper Lanterns Jam", 1, 60_000)
req := httptest.NewRequest(http.MethodGet, "/api/search?q=beatles", nil) req := httptest.NewRequest(http.MethodGet, "/api/search?q=copper", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
newLibraryRouter(h).ServeHTTP(w, req) newLibraryRouter(h).ServeHTTP(w, req)
@@ -34,13 +34,13 @@ func TestHandleSearch_ThreeFacets(t *testing.T) {
if got.Tracks.Total != 1 || len(got.Tracks.Items) != 1 { if got.Tracks.Total != 1 || len(got.Tracks.Items) != 1 {
t.Errorf("tracks = %+v", got.Tracks) t.Errorf("tracks = %+v", got.Tracks)
} }
if got.Artists.Items[0].Name != "Beatles" { if got.Artists.Items[0].Name != "Copper Lanterns" {
t.Errorf("artist name = %q", got.Artists.Items[0].Name) t.Errorf("artist name = %q", got.Artists.Items[0].Name)
} }
if got.Albums.Items[0].ArtistName != "Beatles" { if got.Albums.Items[0].ArtistName != "Copper Lanterns" {
t.Errorf("album.artist_name = %q", got.Albums.Items[0].ArtistName) t.Errorf("album.artist_name = %q", got.Albums.Items[0].ArtistName)
} }
if got.Tracks.Items[0].AlbumTitle != "Beatles Greatest" { if got.Tracks.Items[0].AlbumTitle != "Copper Lanterns Greatest" {
t.Errorf("track.album_title = %q", got.Tracks.Items[0].AlbumTitle) t.Errorf("track.album_title = %q", got.Tracks.Items[0].AlbumTitle)
} }
} }
@@ -48,7 +48,7 @@ func TestHandleSearch_ThreeFacets(t *testing.T) {
func TestHandleSearch_NoMatches(t *testing.T) { func TestHandleSearch_NoMatches(t *testing.T) {
h, pool := testHandlers(t) h, pool := testHandlers(t)
truncateLibrary(t, pool) truncateLibrary(t, pool)
seedArtist(t, pool, "Beatles") seedArtist(t, pool, "Copper Lanterns")
req := httptest.NewRequest(http.MethodGet, "/api/search?q=nothinghere", nil) req := httptest.NewRequest(http.MethodGet, "/api/search?q=nothinghere", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
+1 -1
View File
@@ -42,7 +42,7 @@ type Page[T any] struct {
// ArtistRef is the lightweight artist shape used in lists and search results. // ArtistRef is the lightweight artist shape used in lists and search results.
// SortName is exposed so the SPA's alphabetical-grid divider can group rows // SortName is exposed so the SPA's alphabetical-grid divider can group rows
// by the catalogue sort order ("The Beatles" → "B"). CoverURL is derived from // by the catalogue sort order ("The Copper Lanterns" → "C"). CoverURL is derived from
// a representative album (most-recent with cover_art_path); empty when the // a representative album (most-recent with cover_art_path); empty when the
// artist's discography has no cover art. // artist's discography has no cover art.
type ArtistRef struct { type ArtistRef struct {
+1 -1
View File
@@ -60,7 +60,7 @@ func TestUriEncodeKeepsOnlyUnreservedCharacters(t *testing.T) {
for in, want := range map[string]string{ for in, want := range map[string]string{
"01 - Song.flac": "01%20-%20Song.flac", "01 - Song.flac": "01%20-%20Song.flac",
"a+b=c&d": "a%2Bb%3Dc%26d", "a+b=c&d": "a%2Bb%3Dc%26d",
"Björk~_.": "Bj%C3%B6rk~_.", "Höla~_.": "H%C3%B6la~_.",
"a/b": "a%2Fb", "a/b": "a%2Fb",
} { } {
if got := uriEncode(in); got != want { if got := uriEncode(in); got != want {
+19 -19
View File
@@ -42,10 +42,10 @@ func newPool(t *testing.T) *pgxpool.Pool {
} }
const ( const (
gorillaz = "e21857d5-3256-4547-afb3-4b6ded592596" apes = "0a11ce00-0000-4000-8000-000000000001"
demonDays = "0c4d5b5f-2f3c-3d31-9c4e-4b4f6b4c1a01" ghostNights = "0a11ce00-0000-4000-8000-000000000002"
demonDaysR = "1a2b3c4d-0000-4000-8000-000000000001" ghostNightsR = "1a2b3c4d-0000-4000-8000-000000000001"
demonDaysJ = "1a2b3c4d-0000-4000-8000-000000000002" ghostNightsJ = "1a2b3c4d-0000-4000-8000-000000000002"
) )
// fakeMB is a MusicBrainz with one album in two editions. down makes every // fakeMB is a MusicBrainz with one album in two editions. down makes every
@@ -67,19 +67,19 @@ func newFakeMB(t *testing.T) *fakeMB {
} }
q := r.URL.Query() q := r.URL.Query()
switch { switch {
case r.URL.Path == "/release-group/"+demonDays: case r.URL.Path == "/release-group/"+ghostNights:
_, _ = fmt.Fprintf(w, `{"id": %q, "title": "Demon Days", "primary-type": "Album", "first-release-date": "2005-05-11", _, _ = fmt.Fprintf(w, `{"id": %q, "title": "Ghost Nights", "primary-type": "Album", "first-release-date": "2005-05-11",
"artist-credit": [{"name": "Gorillaz", "artist": {"id": %q}}]}`, demonDays, gorillaz) "artist-credit": [{"name": "Plastic Apes", "artist": {"id": %q}}]}`, ghostNights, apes)
case r.URL.Path == "/release" && q.Get("release-group") == demonDays: case r.URL.Path == "/release" && q.Get("release-group") == ghostNights:
_, _ = fmt.Fprintf(w, `{"release-count": 2, "releases": [ _, _ = fmt.Fprintf(w, `{"release-count": 2, "releases": [
{"id": %q, "title": "Demon Days", "status": "Promotion", "date": "2005-04", "country": "JP", {"id": %q, "title": "Ghost Nights", "status": "Promotion", "date": "2005-04", "country": "JP",
"media": [{"position": 1, "format": "CD", "tracks": [ "media": [{"position": 1, "format": "CD", "tracks": [
{"position": 1, "number": "1", "title": "Intro", "length": 63000, "recording": {"id": "rec-intro"}}]}]}, {"position": 1, "number": "1", "title": "Intro", "length": 63000, "recording": {"id": "rec-intro"}}]}]},
{"id": %q, "title": "Demon Days", "status": "Official", "date": "2005-05-11", "country": "GB", {"id": %q, "title": "Ghost Nights", "status": "Official", "date": "2005-05-11", "country": "GB",
"media": [{"position": 1, "format": "CD", "tracks": [ "media": [{"position": 1, "format": "CD", "tracks": [
{"position": 1, "number": "1", "title": "Intro", "length": 63000, "recording": {"id": "rec-intro"}}, {"position": 1, "number": "1", "title": "Intro", "length": 63000, "recording": {"id": "rec-intro"}},
{"position": 2, "number": "2", "title": "Last Living Souls", "length": 190000, "recording": {"id": "rec-lls"}}]}]} {"position": 2, "number": "2", "title": "Last Living Souls", "length": 190000, "recording": {"id": "rec-lls"}}]}]}
]}`, demonDaysJ, demonDaysR) ]}`, ghostNightsJ, ghostNightsR)
default: default:
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@@ -100,17 +100,17 @@ func TestRefreshReleaseGroup_ReadsEditionsAndTrackLists_Integration(t *testing.T
q := dbq.New(pool) q := dbq.New(pool)
// The group isn't held yet: it is looked up first. // The group isn't held yet: it is looked up first.
if err := s.RefreshReleaseGroup(ctx, demonDays); err != nil { if err := s.RefreshReleaseGroup(ctx, ghostNights); err != nil {
t.Fatal(err) t.Fatal(err)
} }
group, err := q.GetMBReleaseGroup(ctx, demonDays) group, err := q.GetMBReleaseGroup(ctx, ghostNights)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if group.Title != "Demon Days" || !group.ReleasesRefreshedAt.Valid { if group.Title != "Ghost Nights" || !group.ReleasesRefreshedAt.Valid {
t.Fatalf("group = %+v", group) t.Fatalf("group = %+v", group)
} }
tracks, err := q.ListMBReleaseTracksForGroup(ctx, demonDays) tracks, err := q.ListMBReleaseTracksForGroup(ctx, ghostNights)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -123,15 +123,15 @@ func TestRefreshReleaseGroup_ReadsEditionsAndTrackLists_Integration(t *testing.T
lls = &tracks[i] lls = &tracks[i]
} }
} }
if lls == nil || lls.ReleaseMbid != demonDaysR || lls.LengthMs != 190000 { if lls == nil || lls.ReleaseMbid != ghostNightsR || lls.LengthMs != 190000 {
t.Errorf("Last Living Souls = %+v", lls) t.Errorf("Last Living Souls = %+v", lls)
} }
// Refreshing replaces rather than adds. // Refreshing replaces rather than adds.
if err := s.RefreshReleaseGroup(ctx, demonDays); err != nil { if err := s.RefreshReleaseGroup(ctx, ghostNights); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if again, _ := q.ListMBReleaseTracksForGroup(ctx, demonDays); len(again) != 3 { if again, _ := q.ListMBReleaseTracksForGroup(ctx, ghostNights); len(again) != 3 {
t.Errorf("after a refresh: %d tracks, want 3", len(again)) t.Errorf("after a refresh: %d tracks, want 3", len(again))
} }
} }
@@ -145,7 +145,7 @@ func TestRefreshReleaseGroup_UnknownAndUnreachable_Integration(t *testing.T) {
t.Errorf("unknown group: err = %v, want ErrNotFound", err) t.Errorf("unknown group: err = %v, want ErrNotFound", err)
} }
mb.down.Store(true) mb.down.Store(true)
if err := s.RefreshReleaseGroup(ctx, demonDays); !errors.Is(err, musicbrainz.ErrUnreachable) { if err := s.RefreshReleaseGroup(ctx, ghostNights); !errors.Is(err, musicbrainz.ErrUnreachable) {
t.Errorf("MusicBrainz down: err = %v, want ErrUnreachable", err) t.Errorf("MusicBrainz down: err = %v, want ErrUnreachable", err)
} }
} }
+2 -2
View File
@@ -44,7 +44,7 @@ func TestDeezer_FetchArtistArt_Success(t *testing.T) {
mux.HandleFunc("/search/artist", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/search/artist", func(w http.ResponseWriter, r *http.Request) {
imgURL := "http://" + r.Host + "/img/cp.jpg" imgURL := "http://" + r.Host + "/img/cp.jpg"
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"name":"Caravan Palace","picture_xl":"` + imgURL + `"}]}`)) _, _ = w.Write([]byte(`{"data":[{"name":"Caravel Palace","picture_xl":"` + imgURL + `"}]}`))
}) })
mux.HandleFunc("/img/", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/img/", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/jpeg") w.Header().Set("Content-Type", "image/jpeg")
@@ -52,7 +52,7 @@ func TestDeezer_FetchArtistArt_Success(t *testing.T) {
}) })
p := newDeezerTestProvider(t, srv.URL) p := newDeezerTestProvider(t, srv.URL)
thumb, fanart, err := p.FetchArtistArt(context.Background(), ArtistRef{Name: "Caravan Palace"}) thumb, fanart, err := p.FetchArtistArt(context.Background(), ArtistRef{Name: "Caravel Palace"})
if err != nil { if err != nil {
t.Fatalf("err = %v, want nil", err) t.Fatalf("err = %v, want nil", err)
} }
+15 -15
View File
@@ -53,7 +53,7 @@ func TestLastfm_FetchArtistArt_ByMBID(t *testing.T) {
} }
imgURL := "http://" + r.Host + "/img/a.jpg" imgURL := "http://" + r.Host + "/img/a.jpg"
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"artist":{"name":"Radiohead","image":[ _, _ = w.Write([]byte(`{"artist":{"name":"Signal Tower","image":[
{"#text":"` + imgURL + `","size":"extralarge"} {"#text":"` + imgURL + `","size":"extralarge"}
]}}`)) ]}}`))
}) })
@@ -64,8 +64,8 @@ func TestLastfm_FetchArtistArt_ByMBID(t *testing.T) {
p := newLastfmTestProvider(t, srv.URL+"/", "test-key") p := newLastfmTestProvider(t, srv.URL+"/", "test-key")
thumb, fanart, err := p.FetchArtistArt(context.Background(), ArtistRef{ thumb, fanart, err := p.FetchArtistArt(context.Background(), ArtistRef{
MBID: "a74b1b7f-71a5-4011-9441-d0b5e4122711", MBID: "0a11ce00-0000-4000-8000-000000000003",
Name: "Radiohead", Name: "Signal Tower",
}) })
if err != nil { if err != nil {
t.Fatalf("err = %v, want nil", err) t.Fatalf("err = %v, want nil", err)
@@ -92,22 +92,22 @@ func TestLastfm_FetchArtistArt_ByName(t *testing.T) {
} }
imgURL := "http://" + r.Host + "/img/b.jpg" imgURL := "http://" + r.Host + "/img/b.jpg"
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"artist":{"name":"Björk","image":[ _, _ = w.Write([]byte(`{"artist":{"name":"Höla","image":[
{"#text":"` + imgURL + `","size":"large"} {"#text":"` + imgURL + `","size":"large"}
]}}`)) ]}}`))
}) })
mux.HandleFunc("/img/", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/img/", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "image/jpeg") w.Header().Set("Content-Type", "image/jpeg")
_, _ = w.Write([]byte("bjork-bytes")) _, _ = w.Write([]byte("hola-bytes"))
}) })
p := newLastfmTestProvider(t, srv.URL+"/", "test-key") p := newLastfmTestProvider(t, srv.URL+"/", "test-key")
thumb, _, err := p.FetchArtistArt(context.Background(), ArtistRef{Name: "Björk"}) thumb, _, err := p.FetchArtistArt(context.Background(), ArtistRef{Name: "Höla"})
if err != nil { if err != nil {
t.Fatalf("err = %v, want nil", err) t.Fatalf("err = %v, want nil", err)
} }
if string(thumb) != "bjork-bytes" { if string(thumb) != "hola-bytes" {
t.Errorf("thumb = %q, want bjork-bytes", thumb) t.Errorf("thumb = %q, want hola-bytes", thumb)
} }
} }
@@ -242,7 +242,7 @@ func TestLastfm_FetchAlbumCover_Success(t *testing.T) {
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
imgURL := "http://" + r.Host + "/img/c.jpg" imgURL := "http://" + r.Host + "/img/c.jpg"
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"album":{"name":"OK Computer","image":[ _, _ = w.Write([]byte(`{"album":{"name":"OK Calculator","image":[
{"#text":"` + imgURL + `","size":"mega"} {"#text":"` + imgURL + `","size":"mega"}
]}}`)) ]}}`))
}) })
@@ -253,8 +253,8 @@ func TestLastfm_FetchAlbumCover_Success(t *testing.T) {
p := newLastfmTestProvider(t, srv.URL+"/", "test-key") p := newLastfmTestProvider(t, srv.URL+"/", "test-key")
body, err := p.FetchAlbumCover(context.Background(), AlbumRef{ body, err := p.FetchAlbumCover(context.Background(), AlbumRef{
ArtistName: "Radiohead", ArtistName: "Signal Tower",
AlbumTitle: "OK Computer", AlbumTitle: "OK Calculator",
}) })
if err != nil { if err != nil {
t.Fatalf("err = %v, want nil", err) t.Fatalf("err = %v, want nil", err)
@@ -275,7 +275,7 @@ func TestLastfm_FetchAlbumCover_WithMBIDHint(t *testing.T) {
} }
imgURL := "http://" + r.Host + "/img/d.jpg" imgURL := "http://" + r.Host + "/img/d.jpg"
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"album":{"name":"Kid A","image":[ _, _ = w.Write([]byte(`{"album":{"name":"Kid B","image":[
{"#text":"` + imgURL + `","size":"extralarge"} {"#text":"` + imgURL + `","size":"extralarge"}
]}}`)) ]}}`))
}) })
@@ -286,9 +286,9 @@ func TestLastfm_FetchAlbumCover_WithMBIDHint(t *testing.T) {
p := newLastfmTestProvider(t, srv.URL+"/", "test-key") p := newLastfmTestProvider(t, srv.URL+"/", "test-key")
body, err := p.FetchAlbumCover(context.Background(), AlbumRef{ body, err := p.FetchAlbumCover(context.Background(), AlbumRef{
MBID: "b80a8a53-c9bf-3a3a-9a8c-bf76bf9a553a", MBID: "0a11ce00-0000-4000-8000-000000000004",
ArtistName: "Radiohead", ArtistName: "Signal Tower",
AlbumTitle: "Kid A", AlbumTitle: "Kid B",
}) })
if err != nil { if err != nil {
t.Fatalf("err = %v, want nil", err) t.Fatalf("err = %v, want nil", err)
+2 -1
View File
@@ -21,7 +21,8 @@ type FetcherConfig struct {
HTTPClient *http.Client // optional override for tests HTTPClient *http.Client // optional override for tests
} }
// Sample MBID used by TestConnection. Beatles' "Abbey Road" UK release. // Sample MBID used by TestConnection: a long-established release that the
// Cover Art Archive has always held art for.
const mbcaaTestSampleMBID = "f4b3df80-8a6c-3e87-b51e-5c1ee70a78ee" const mbcaaTestSampleMBID = "f4b3df80-8a6c-3e87-b51e-5c1ee70a78ee"
// mbcaaProvider implements Provider, AlbumCoverProvider, and // mbcaaProvider implements Provider, AlbumCoverProvider, and
+2 -3
View File
@@ -31,9 +31,8 @@ const (
// 5xx before giving up and surfacing ErrTransient. // 5xx before giving up and surfacing ErrTransient.
theAudioDBMaxRetries = 3 theAudioDBMaxRetries = 3
// theAudioDBTestSampleMBID is used by TestConnection. Pink Floyd's // theAudioDBTestSampleMBID is used by TestConnection: a stable,
// "The Dark Side of the Moon" — a stable popular release verified // widely known release verified present in TheAudioDB at design time.
// present in TheAudioDB at design time.
theAudioDBTestSampleMBID = "f5093c06-23e3-404f-aeaa-40f72885ee3a" theAudioDBTestSampleMBID = "f5093c06-23e3-404f-aeaa-40f72885ee3a"
) )
+3 -3
View File
@@ -27,7 +27,7 @@ type artistCredit struct {
// featuring finds where a guest credit starts: "X feat. Y", "X ft. Y", // featuring finds where a guest credit starts: "X feat. Y", "X ft. Y",
// "X featuring Y", "X (feat. Y)". Outside brackets the abbreviations need // "X featuring Y", "X (feat. Y)". Outside brackets the abbreviations need
// their full stop, so a band called "Little Feat" is not cut short; inside // their full stop, so a band called "Tiny Feat" is not cut short; inside
// brackets the stop is optional. // brackets the stop is optional.
var featuring = regexp.MustCompile(`(?i)\s+(?:[(\[]\s*(?:feat\.?|ft\.?|featuring)|feat\.|ft\.|featuring)\s`) var featuring = regexp.MustCompile(`(?i)\s+(?:[(\[]\s*(?:feat\.?|ft\.?|featuring)|feat\.|ft\.|featuring)\s`)
@@ -36,7 +36,7 @@ var featuring = regexp.MustCompile(`(?i)\s+(?:[(\[]\s*(?:feat\.?|ft\.?|featuring
// - A file that lists its artists one by one (Picard's ARTISTS tag, two or // - A file that lists its artists one by one (Picard's ARTISTS tag, two or
// more values) is filed under the first. This is the only way a // more values) is filed under the first. This is the only way a
// collaboration is split: "A & B" may be two artists or one band // collaboration is split: "A & B" may be two artists or one band
// ("Simon & Garfunkel", "St. Paul & The Broken Bones"), and only the // ("Simone & Garfield", "St. Mark & The Mended Bones"), and only the
// list says which. // list says which.
// - Otherwise a featured guest is cut from the credit: "X feat. Y" is filed // - Otherwise a featured guest is cut from the credit: "X feat. Y" is filed
// under X. // under X.
@@ -116,7 +116,7 @@ func readTagList(meta tag.Metadata, rs io.ReadSeeker, vorbisKey, textName string
// id3TextList reads the TXXX field called name. dhowden/tag files each TXXX // id3TextList reads the TXXX field called name. dhowden/tag files each TXXX
// frame under "TXXX", "TXXX_0", … as a *tag.Comm. ID3v2.4 separates the // frame under "TXXX", "TXXX_0", … as a *tag.Comm. ID3v2.4 separates the
// values of one frame with NUL. ID3v2.3 has no separator, and a "/" there // values of one frame with NUL. ID3v2.3 has no separator, and a "/" there
// may be part of a name (AC/DC), so a v2.3 frame is one value. // may be part of a name (AM/FM), so a v2.3 frame is one value.
func id3TextList(meta tag.Metadata, name string) []string { func id3TextList(meta tag.Metadata, name string) []string {
var out []string var out []string
for key, v := range meta.Raw() { for key, v := range meta.Raw() {
+14 -14
View File
@@ -16,13 +16,13 @@ func TestWithoutGuests(t *testing.T) {
{"Low Tide Choir [ft Ruby Calloway]", "Low Tide Choir"}, {"Low Tide Choir [ft Ruby Calloway]", "Low Tide Choir"},
{"Low Tide Choir FEAT. Ruby Calloway & Mae", "Low Tide Choir"}, {"Low Tide Choir FEAT. Ruby Calloway & Mae", "Low Tide Choir"},
// Names that only look like a credit stay whole. // Names that only look like a credit stay whole.
{"Little Feat", "Little Feat"}, {"Tiny Feat", "Tiny Feat"},
{"Little Feat featuring Bonnie Raitt", "Little Feat"}, {"Tiny Feat featuring Bonnie Rains", "Tiny Feat"},
{"Daft Punk", "Daft Punk"}, {"Deft Monks", "Deft Monks"},
{"Soft Cell", "Soft Cell"}, {"Loft Cell", "Loft Cell"},
{"Featuring Fools", "Featuring Fools"}, {"Featuring Fools", "Featuring Fools"},
{"Simon & Garfunkel", "Simon & Garfunkel"}, {"Simone & Garfield", "Simone & Garfield"},
{"St. Paul & The Broken Bones", "St. Paul & The Broken Bones"}, {"St. Mark & The Mended Bones", "St. Mark & The Mended Bones"},
} }
for _, tc := range tests { for _, tc := range tests {
if got := withoutGuests(tc.credit); got != tc.want { if got := withoutGuests(tc.credit); got != tc.want {
@@ -65,15 +65,15 @@ func TestReadArtistCredit_ID3(t *testing.T) {
}, },
{ {
name: "an & the file does not list is one artist", name: "an & the file does not list is one artist",
artist: "St. Paul & The Broken Bones", artist: "St. Mark & The Mended Bones",
raw: map[string]interface{}{"TXXX": &tag.Comm{Description: "ARTISTS", Text: "St. Paul & The Broken Bones"}}, raw: map[string]interface{}{"TXXX": &tag.Comm{Description: "ARTISTS", Text: "St. Mark & The Mended Bones"}},
want: artistCredit{Name: "St. Paul & The Broken Bones"}, want: artistCredit{Name: "St. Mark & The Mended Bones"},
}, },
{ {
name: "a v2.3 list has no separator, so a slash stays in the name", name: "a v2.3 list has no separator, so a slash stays in the name",
artist: "AC/DC", artist: "AM/FM",
raw: map[string]interface{}{"TXXX_0": &tag.Comm{Description: "Artists", Text: "AC/DC"}}, raw: map[string]interface{}{"TXXX_0": &tag.Comm{Description: "Artists", Text: "AM/FM"}},
want: artistCredit{Name: "AC/DC"}, want: artistCredit{Name: "AM/FM"},
}, },
{ {
name: "no artist at all", name: "no artist at all",
@@ -116,14 +116,14 @@ func TestReadArtistCredit_FLACListsItsArtists(t *testing.T) {
} }
func TestReadArtistCredit_FLACWithOneArtist(t *testing.T) { func TestReadArtistCredit_FLACWithOneArtist(t *testing.T) {
data := buildFLAC(false, "ARTIST=Marina & the Kats", "ARTISTS=Marina & the Kats", "MUSICBRAINZ_ARTISTID=id-kats") data := buildFLAC(false, "ARTIST=Marisa & the Cats", "ARTISTS=Marisa & the Cats", "MUSICBRAINZ_ARTISTID=id-kats")
rs := bytes.NewReader(data) rs := bytes.NewReader(data)
meta, err := tag.ReadFrom(rs) meta, err := tag.ReadFrom(rs)
if err != nil { if err != nil {
t.Fatalf("tag.ReadFrom: %v", err) t.Fatalf("tag.ReadFrom: %v", err)
} }
got := readArtistCredit(meta, rs, ReadTagMBIDs(meta)) got := readArtistCredit(meta, rs, ReadTagMBIDs(meta))
if want := (artistCredit{Name: "Marina & the Kats", MBID: "id-kats"}); got != want { if want := (artistCredit{Name: "Marisa & the Cats", MBID: "id-kats"}); got != want {
t.Errorf("readArtistCredit = %+v, want %+v", got, want) t.Errorf("readArtistCredit = %+v, want %+v", got, want)
} }
} }
+8 -8
View File
@@ -17,13 +17,13 @@ import (
// a song once, so the extra copies are the ones to fold away. // a song once, so the extra copies are the ones to fold away.
// - cross_release: the copies are on different albums. A single and the // - cross_release: the copies are on different albums. A single and the
// album it came from, a deluxe edition and the standard one, or one // album it came from, a deluxe edition and the standard one, or one
// recording a later release retitled ("The Ragtime Cat", "F.O.D. (live)", // recording a later release retitled ("The Ragtime Cat", "F.O.E. (live)",
// a romanized title): each copy belongs to its own release, so none is // a romanized title): each copy belongs to its own release, so none is
// deleted (unless it is a video rip; the resolver decides). Copies under // deleted (unless it is a video rip; the resolver decides). Copies under
// different titles on different releases are retitles, not different // different titles on different releases are retitles, not different
// songs. // songs.
// - distinct: one album, two versions of a song that sound alike, named as // - distinct: one album, two versions of a song that sound alike, named as
// such ("Lovesick", "Lovesick (Instrumental)"). Not duplicates. // such ("Homesick", "Homesick (Instrumental)"). Not duplicates.
// - mismatch: one album holds the same audio under different song titles: // - mismatch: one album holds the same audio under different song titles:
// one file filling several track slots, a broken download. Which slot is // one file filling several track slots, a broken download. Which slot is
// right is the resolver's to decide from MusicBrainz's track lengths. // right is the resolver's to decide from MusicBrainz's track lengths.
@@ -54,7 +54,7 @@ type ClassifyMember struct {
// adds to a title (featuring credits, remaster notes, video markers) and keeps // adds to a title (featuring credits, remaster notes, video markers) and keeps
// what names a different recording (live, demo, remix, instrumental). On one // what names a different recording (live, demo, remix, instrumental). On one
// album, titles that differ only by such a word are two versions (distinct) // album, titles that differ only by such a word are two versions (distinct)
// unless the bytes are identical, which is one file twice: "WWW" and "WWW // unless the bytes are identical, which is one file twice: "XYZ" and "XYZ
// (instrumental)" holding the same file is a wrong slot. // (instrumental)" holding the same file is a wrong slot.
func ClassifyDuplicateGroup(tier string, members []ClassifyMember) DuplicateClass { func ClassifyDuplicateGroup(tier string, members []ClassifyMember) DuplicateClass {
if len(members) < 2 { if len(members) < 2 {
@@ -98,8 +98,8 @@ var versionWord = regexp.MustCompile(
// versionWords lists, sorted and lowercased, the version words in a copy's // versionWords lists, sorted and lowercased, the version words in a copy's
// title and file name together. Two copies holding one title tag can still be // title and file name together. Two copies holding one title tag can still be
// two versions, told apart only by the file name: "Suite-Pee" and // two versions, told apart only by the file name: "Suite-Tea" and
// "Suite-Pee (Clean Version)", "Luv (sic) Grand Finale" and its instrumental. // "Suite-Tea (Clean Version)", "Hush (sic) Grand Finale" and its instrumental.
func versionWords(title, path string) string { func versionWords(title, path string) string {
seen := map[string]bool{} seen := map[string]bool{}
name := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) name := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
@@ -123,7 +123,7 @@ func versionWords(title, path string) string {
// songKey is MatchTitleKey with every bracketed segment and a dashed version // songKey is MatchTitleKey with every bracketed segment and a dashed version
// suffix dropped: the song a title names, whatever version of it. // suffix dropped: the song a title names, whatever version of it.
// "Lovesick (Instrumental)", "Lovesick - Instrumental Version" and "Lovesick" // "Homesick (Instrumental)", "Homesick - Instrumental Version" and "Homesick"
// share one. // share one.
func songKey(title, artist string) string { func songKey(title, artist string) string {
t := versionSuffix.ReplaceAllString(bracketed.ReplaceAllString(title, " "), "") t := versionSuffix.ReplaceAllString(bracketed.ReplaceAllString(title, " "), "")
@@ -134,9 +134,9 @@ func songKey(title, artist string) string {
} }
var ( var (
// A bracketed credit: "(feat. Panda Bear)", "[ft. X]", "(featuring Y)". // A bracketed credit: "(feat. Koala Bear)", "[ft. X]", "(featuring Y)".
featBracket = regexp.MustCompile(`(?i)[(\[][^)\]]*\b(feat\.?|ft\.?|featuring)\s[^)\]]*[)\]]`) featBracket = regexp.MustCompile(`(?i)[(\[][^)\]]*\b(feat\.?|ft\.?|featuring)\s[^)\]]*[)\]]`)
// A credit trailing the title without brackets: "Doin' It Right ft. Panda // A credit trailing the title without brackets: "Doin' It Twice ft. Panda
// Bear". // Bear".
featTrailing = regexp.MustCompile(`(?i)\s(feat\.?|ft\.?|featuring)\s.*$`) featTrailing = regexp.MustCompile(`(?i)\s(feat\.?|ft\.?|featuring)\s.*$`)
// "(2011 Remaster)", "[Remastered]", "- Remastered 2009". // "(2011 Remaster)", "[Remastered]", "- Remastered 2009".
+37 -37
View File
@@ -10,7 +10,7 @@ import (
// The group shapes the classifier tells apart. // The group shapes the classifier tells apart.
func TestClassifyDuplicateGroup(t *testing.T) { func TestClassifyDuplicateGroup(t *testing.T) {
m := func(album, title string) ClassifyMember { m := func(album, title string) ClassifyMember {
return ClassifyMember{AlbumID: album, Title: title, ArtistName: "Gorillaz"} return ClassifyMember{AlbumID: album, Title: title, ArtistName: "Plastic Apes"}
} }
cases := []struct { cases := []struct {
name string name string
@@ -18,30 +18,30 @@ func TestClassifyDuplicateGroup(t *testing.T) {
members []ClassifyMember members []ClassifyMember
want DuplicateClass want DuplicateClass
}{ }{
{"Humanz: one album, one song twice", "exact", {"Mammalz: one album, one song twice", "exact",
[]ClassifyMember{m("humanz", "Saturnz Barz"), m("humanz", "Saturnz Barz (Official Video)")}, ClassSameRelease}, []ClassifyMember{m("mammalz", "Neptunez Barz"), m("mammalz", "Neptunez Barz (Official Video)")}, ClassSameRelease},
{"one album, video upload title with artist prefix", "acoustic", {"one album, video upload title with artist prefix", "acoustic",
[]ClassifyMember{m("humanz", "Andromeda"), m("humanz", "Gorillaz - Andromeda (Official Audio)")}, ClassSameRelease}, []ClassifyMember{m("mammalz", "Cassiopeia"), m("mammalz", "Plastic Apes - Cassiopeia (Official Audio)")}, ClassSameRelease},
{"one album, identical bytes under a version title: one file in two slots", "exact", {"one album, identical bytes under a version title: one file in two slots", "exact",
[]ClassifyMember{m("www", "WWW"), m("www", "WWW (instrumental)")}, ClassMismatch}, []ClassifyMember{m("www", "XYZ"), m("www", "XYZ (instrumental)")}, ClassMismatch},
{"one album, acoustic match, two versions named", "acoustic", {"one album, acoustic match, two versions named", "acoustic",
[]ClassifyMember{m("moe", "Lovesick"), m("moe", "Lovesick (Instrumental)")}, ClassDistinct}, []ClassifyMember{m("moe", "Homesick"), m("moe", "Homesick (Instrumental)")}, ClassDistinct},
{"Void: one album, one audio under three song titles", "acoustic", {"Void: one album, one audio under three song titles", "acoustic",
[]ClassifyMember{m("void", "Slimewar (into the void)"), m("void", "Void"), m("void", "Reach")}, ClassMismatch}, []ClassifyMember{m("void", "Slimeworld (into the void)"), m("void", "Void"), m("void", "Reach")}, ClassMismatch},
{"a version named after a dash", "acoustic", {"a version named after a dash", "acoustic",
[]ClassifyMember{m("andora", "Goodbye Yesterday"), m("andora", "Goodbye Yesterday - Instrumental Version")}, ClassDistinct}, []ClassifyMember{m("andora", "Goodbye Yesterday"), m("andora", "Goodbye Yesterday - Instrumental Version")}, ClassDistinct},
{"a dash that names no version", "acoustic", {"a dash that names no version", "acoustic",
[]ClassifyMember{m("a", "Monday Chill - Part One"), m("a", "Monday Chill - Part Two")}, ClassMismatch}, []ClassifyMember{m("a", "Monday Chill - Part One"), m("a", "Monday Chill - Part Two")}, ClassMismatch},
{"Slasher and Slasher II are not versions of one song", "acoustic", {"Slasher and Slasher II are not versions of one song", "acoustic",
[]ClassifyMember{m("slasher", "Slasher"), m("slasher", "Slasher II")}, ClassMismatch}, []ClassifyMember{m("slasher", "Slasher"), m("slasher", "Slasher II")}, ClassMismatch},
{"Big Me: the single and the album", "exact", {"Big You: the single and the album", "exact",
[]ClassifyMember{m("single", "Big Me"), m("album", "Big Me")}, ClassCrossRelease}, []ClassifyMember{m("single", "Big You"), m("album", "Big You")}, ClassCrossRelease},
{"remaster and featuring credits are one song", "acoustic", {"remaster and featuring credits are one song", "acoustic",
[]ClassifyMember{m("a", "Feel Good Inc. (2017 Remaster)"), m("b", "Feel Good Inc feat. De La Soul")}, ClassCrossRelease}, []ClassifyMember{m("a", "Feel Fine Ltd. (2017 Remaster)"), m("b", "Feel Fine Ltd feat. Del Mar Soul")}, ClassCrossRelease},
{"a later release retitles the recording", "acoustic", {"a later release retitles the recording", "acoustic",
[]ClassifyMember{m("coco", "Ragtime Cat"), m("single", "The Ragtime Cat")}, ClassCrossRelease}, []ClassifyMember{m("coco", "Ragtime Cat"), m("single", "The Ragtime Cat")}, ClassCrossRelease},
{"identical bytes on two albums under two titles", "exact", {"identical bytes on two albums under two titles", "exact",
[]ClassifyMember{m("dookie", "F.O.D."), m("live", "F.O.D. (live)")}, ClassCrossRelease}, []ClassifyMember{m("cookie", "F.O.E."), m("live", "F.O.E. (live)")}, ClassCrossRelease},
{"a lone copy", "exact", []ClassifyMember{m("a", "Song")}, ClassReview}, {"a lone copy", "exact", []ClassifyMember{m("a", "Song")}, ClassReview},
} }
for _, tc := range cases { for _, tc := range cases {
@@ -53,9 +53,9 @@ func TestClassifyDuplicateGroup(t *testing.T) {
func TestMatchTitleKey(t *testing.T) { func TestMatchTitleKey(t *testing.T) {
cases := []struct{ title, artist, want string }{ cases := []struct{ title, artist, want string }{
{"Saturnz Barz (Official Video)", "Gorillaz", "saturnzbarz"}, {"Neptunez Barz (Official Video)", "Plastic Apes", "neptunezbarz"},
{"Gorillaz - Saturnz Barz", "Gorillaz", "saturnzbarz"}, {"Plastic Apes - Neptunez Barz", "Plastic Apes", "neptunezbarz"},
{"Doin' It Right (Music Video) ft. Panda Bear", "Daft Punk", "doinitright"}, {"Doin' It Twice (Music Video) ft. Koala Bear", "Deft Monks", "doinittwice"},
{"Song [feat. X]", "", "song"}, {"Song [feat. X]", "", "song"},
{"Song - Remastered 2009", "", "song"}, {"Song - Remastered 2009", "", "song"},
{"Rock & Roll", "", "rockandroll"}, {"Rock & Roll", "", "rockandroll"},
@@ -79,12 +79,12 @@ func TestMatchTitleKey(t *testing.T) {
// named differently must agree. // named differently must agree.
func TestVersionWords(t *testing.T) { func TestVersionWords(t *testing.T) {
differ := [][2][2]string{ differ := [][2][2]string{
{{"Suite-Pee", "/m/SOAD/Sugar/System of a Down - Sugar - 02 - Suite-Pee.mp3"}, {{"Suite-Tea", "/m/SOAC/Sugar/System of a Clown - Sugar - 02 - Suite-Tea.mp3"},
{"Suite-Pee", "/m/SOAD/Sugar/System of a Down - Sugar - 02 - Suite-Pee (Clean Version).mp3"}}, {"Suite-Tea", "/m/SOAC/Sugar/System of a Clown - Sugar - 02 - Suite-Tea (Clean Version).mp3"}},
{{"Luv (sic) Grand Finale", "/m/Nujabes/Hexalogy/Nujabes - Luv(sic) Hexalogy - 06 - Luv (sic) Grand Finale Instrumentals.mp3"}, {{"Hush (sic) Grand Finale", "/m/Sebanuj/Heptalogy/Sebanuj - Hush(sic) Heptalogy - 06 - Hush (sic) Grand Finale Instrumentals.mp3"},
{"Luv (sic) Grand Finale", "/m/Nujabes/Hexalogy/0106 - Luvsic Grand Finale.m4a"}}, {"Hush (sic) Grand Finale", "/m/Sebanuj/Heptalogy/0106 - Hushsic Grand Finale.m4a"}},
{{"Charger", "/m/Gorillaz/Humanz/Gorillaz - Humanz - 08 - Charger - live in Cologne 2017.mp3"}, {{"Dynamo", "/m/Plastic Apes/Mammalz/Plastic Apes - Mammalz - 08 - Dynamo - live in Cologne 2017.mp3"},
{"Charger", "/m/Gorillaz/Humanz/CD 01/08 Charger.flac"}}, {"Dynamo", "/m/Plastic Apes/Mammalz/CD 01/08 Dynamo.flac"}},
} }
for _, p := range differ { for _, p := range differ {
a, b := versionWords(p[0][0], p[0][1]), versionWords(p[1][0], p[1][1]) a, b := versionWords(p[0][0], p[0][1]), versionWords(p[1][0], p[1][1])
@@ -93,12 +93,12 @@ func TestVersionWords(t *testing.T) {
} }
} }
agree := [][2][2]string{ agree := [][2][2]string{
{{"Heat Waves (Shakur Ahmad Remix)", "/m/GA/Glass Animals - Dreamland Deluxe - 02 - Heat Waves (Shakur Ahmad Remix).mp3"}, {{"Heat Lines (Tariq Amal Remix)", "/m/GA/Glass Insects - Dreamland Deluxe - 02 - Heat Lines (Tariq Amal Remix).mp3"},
{"Heat Waves (Shakur Ahmad Remix)", "/m/GA/02. Heat Waves (Shakur Ahmad Remix).flac"}}, {"Heat Lines (Tariq Amal Remix)", "/m/GA/02. Heat Lines (Tariq Amal Remix).flac"}},
{{"Luv (sic) Instrumentals", "/m/Nujabes/0201 - Luvsic instrumentals.m4a"}, {{"Hush (sic) Instrumentals", "/m/Sebanuj/0201 - Hushsic instrumentals.m4a"},
{"Luv (sic) Instrumentals", "/m/Nujabes/Nujabes - Luv(sic) Hexalogy - 01 - Luv (sic) Instrumentals.mp3"}}, {"Hush (sic) Instrumentals", "/m/Sebanuj/Sebanuj - Hush(sic) Heptalogy - 01 - Hush (sic) Instrumentals.mp3"}},
{{"Henrietta", "/m/The Fratellis - Costello Music - 01 - Henrietta.mp3"}, {{"Henrietta Mae", "/m/The Fratellinis - Castello Music - 01 - Henrietta Mae.mp3"},
{"Henrietta", "/m/The Fratellis - Costello Music - 01 - Henrietta.flac"}}, {"Henrietta Mae", "/m/The Fratellinis - Castello Music - 01 - Henrietta Mae.flac"}},
} }
for _, p := range agree { for _, p := range agree {
a, b := versionWords(p[0][0], p[0][1]), versionWords(p[1][0], p[1][1]) a, b := versionWords(p[0][0], p[0][1]), versionWords(p[1][0], p[1][1])
@@ -113,11 +113,11 @@ func TestWrongSlots(t *testing.T) {
copies := func(titles ...string) []slotCopy { copies := func(titles ...string) []slotCopy {
out := make([]slotCopy, len(titles)) out := make([]slotCopy, len(titles))
for i, title := range titles { for i, title := range titles {
out[i] = slotCopy{Title: title, Artist: "Savant", DurationMs: 220000} out[i] = slotCopy{Title: title, Artist: "Savanta", DurationMs: 220000}
} }
return out return out
} }
void := []dbq.MbReleaseTrack{track("Slimewar (Into the Void)", 300000), track("Reach", 281000), track("Void", 220500)} void := []dbq.MbReleaseTrack{track("Slimeworld (Into the Void)", 300000), track("Reach", 281000), track("Void", 220500)}
cases := []struct { cases := []struct {
name string name string
copies []slotCopy copies []slotCopy
@@ -126,17 +126,17 @@ func TestWrongSlots(t *testing.T) {
losers []int losers []int
ok bool ok bool
}{ }{
{"Void: the file is Void's; the other two slots are other songs", copies("Slimewar (into the void)", "Void", "Reach"), void, 1, []int{0, 2}, true}, {"Void: the file is Void's; the other two slots are other songs", copies("Slimeworld (into the void)", "Void", "Reach"), void, 1, []int{0, 2}, true},
{"no track list", copies("Void", "Reach"), nil, -1, nil, false}, {"no track list", copies("Void", "Reach"), nil, -1, nil, false},
{"a title the track list does not hold", copies("Void", "Bonus"), void, -1, nil, false}, {"a title the track list does not hold", copies("Void", "Bonus"), void, -1, nil, false},
{"Killjoy held twice beside Dreamland's slot", []slotCopy{ {"Killjoy held twice beside Dreamland's slot", []slotCopy{
{Title: "Dreamland", Artist: "Fox Stevenson", DurationMs: 167000}, {Title: "Dreamland", Artist: "Lynx Morrison", DurationMs: 167000},
{Title: "Killjoy", Artist: "Fox Stevenson", DurationMs: 167000}, {Title: "Killjoy", Artist: "Lynx Morrison", DurationMs: 167000},
{Title: "Killjoy", Artist: "Fox Stevenson", DurationMs: 166000}, {Title: "Killjoy", Artist: "Lynx Morrison", DurationMs: 166000},
}, []dbq.MbReleaseTrack{track("Killjoy", 166500), track("Dreamland", 214000)}, 1, []int{0}, true}, }, []dbq.MbReleaseTrack{track("Killjoy", 166500), track("Dreamland", 214000)}, 1, []int{0}, true},
{"two slots fit the file", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 220000), track("Reach", 221500)}, -1, nil, false}, {"two slots fit the file", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 220000), track("Reach", 221500)}, -1, nil, false},
{"a slot near but not within the fit", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 220000), track("Reach", 226000)}, -1, nil, false}, {"a slot near but not within the fit", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 220000), track("Reach", 226000)}, -1, nil, false},
{"no slot fits, and every slot is clearly another song's", copies("Reach", "Slimewar (into the void)"), void, -1, []int{0, 1}, true}, {"no slot fits, and every slot is clearly another song's", copies("Reach", "Slimeworld (into the void)"), void, -1, []int{0, 1}, true},
{"no slot fits, but one is near", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 226000), track("Reach", 281000)}, -1, nil, false}, {"no slot fits, but one is near", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 226000), track("Reach", 281000)}, -1, nil, false},
{"an unknown length counts for nothing", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 220000), track("Reach", 0)}, -1, nil, false}, {"an unknown length counts for nothing", copies("Void", "Reach"), []dbq.MbReleaseTrack{track("Void", 220000), track("Reach", 0)}, -1, nil, false},
} }
@@ -149,15 +149,15 @@ func TestWrongSlots(t *testing.T) {
} }
} }
// The lengths cannot place a recording filed as several songs (Savant's // The lengths cannot place a recording filed as several songs (Savanta's
// Mortals, cut to each slot's length); what AcoustID calls it can. // Immortals, cut to each slot's length); what AcoustID calls it can.
func TestNamedCopies(t *testing.T) { func TestNamedCopies(t *testing.T) {
track := func(title string, ms int32, rec string) dbq.MbReleaseTrack { track := func(title string, ms int32, rec string) dbq.MbReleaseTrack {
return dbq.MbReleaseTrack{Title: title, LengthMs: ms, RecordingMbid: rec} return dbq.MbReleaseTrack{Title: title, LengthMs: ms, RecordingMbid: rec}
} }
copies := []slotCopy{ copies := []slotCopy{
{Title: "Tormentor", Artist: "The Wombats", DurationMs: 220000}, {Title: "Tormentor", Artist: "The Wallabies", DurationMs: 220000},
{Title: "Record Shop", Artist: "The Wombats", DurationMs: 181000}, {Title: "Record Shop", Artist: "The Wallabies", DurationMs: 181000},
} }
album := []dbq.MbReleaseTrack{ album := []dbq.MbReleaseTrack{
track("Tormentor", 221000, "rec-tormentor"), track("Record Shop", 180000, "rec-record-shop"), track("Ice Cream", 200000, "rec-ice"), track("Tormentor", 221000, "rec-tormentor"), track("Record Shop", 180000, "rec-record-shop"), track("Ice Cream", 200000, "rec-ice"),
+1 -1
View File
@@ -115,7 +115,7 @@ func TestGroupDuplicates_ExactTier(t *testing.T) {
res := groupDuplicates([]fingerprintCandidate{ res := groupDuplicates([]fingerprintCandidate{
{ID: "www-01", DurationMs: 215000, StreamSHA256: hash}, {ID: "www-01", DurationMs: 215000, StreamSHA256: hash},
{ID: "www-02", DurationMs: 215000, StreamSHA256: hash}, {ID: "www-02", DurationMs: 215000, StreamSHA256: hash},
{ID: "lovesick", DurationMs: 198000, StreamSHA256: []byte("another")}, {ID: "homesick", DurationMs: 198000, StreamSHA256: []byte("another")},
}, defaultAcousticMaxBitErrorRate) }, defaultAcousticMaxBitErrorRate)
want := []duplicateGroup{{Tier: tierExact, Members: []string{"www-01", "www-02"}}} want := []duplicateGroup{{Tier: tierExact, Members: []string{"www-01", "www-02"}}}
if !reflect.DeepEqual(res.Groups, want) { if !reflect.DeepEqual(res.Groups, want) {
+1 -1
View File
@@ -59,7 +59,7 @@ func newMergeFixture(t *testing.T) mergeFixture {
} }
return tr return tr
} }
f.remove = upsert("WWW (copy)", f.removePath) f.remove = upsert("XYZ (copy)", f.removePath)
f.other = upsert("Neighbour", filepath.Join(dir, "other.mp3")) f.other = upsert("Neighbour", filepath.Join(dir, "other.mp3"))
mustExec := func(sql string, args ...any) { mustExec := func(sql string, args ...any) {
+19 -19
View File
@@ -15,7 +15,7 @@ import (
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
) )
// resolveFixture is the Humanz shape: one album, one song twice, both copies on // resolveFixture is the Mammalz shape: one album, one song twice, both copies on
// disk under an artist/album folder, in one pending exact-tier group. // disk under an artist/album folder, in one pending exact-tier group.
type resolveFixture struct { type resolveFixture struct {
pool *pgxpool.Pool pool *pgxpool.Pool
@@ -29,13 +29,13 @@ func newResolveFixture(t *testing.T) resolveFixture {
pool := newPool(t) pool := newPool(t)
ctx := context.Background() ctx := context.Background()
q := dbq.New(pool) q := dbq.New(pool)
dir := filepath.Join(t.TempDir(), "Gorillaz", "Humanz (2017)") dir := filepath.Join(t.TempDir(), "Plastic Apes", "Mammalz (2017)")
if err := os.MkdirAll(dir, 0o755); err != nil { if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err) t.Fatal(err)
} }
f := resolveFixture{pool: pool} f := resolveFixture{pool: pool}
f.cleanPath = filepath.Join(dir, "Gorillaz - Humanz - 03 - Saturnz Barz.mp3") f.cleanPath = filepath.Join(dir, "Plastic Apes - Mammalz - 03 - Neptunez Barz.mp3")
f.ripPath = filepath.Join(dir, "Gorillaz - Humanz - 03 - Saturnz Barz (Official Video).mp3") f.ripPath = filepath.Join(dir, "Plastic Apes - Mammalz - 03 - Neptunez Barz (Official Video).mp3")
for _, p := range []string{f.cleanPath, f.ripPath} { for _, p := range []string{f.cleanPath, f.ripPath} {
if err := os.WriteFile(p, []byte("audio"), 0o644); err != nil { if err := os.WriteFile(p, []byte("audio"), 0o644); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -45,7 +45,7 @@ func newResolveFixture(t *testing.T) resolveFixture {
var artist dbq.Artist var artist dbq.Artist
f.clean, album, artist = seedTrack(t, pool, f.cleanPath) f.clean, album, artist = seedTrack(t, pool, f.cleanPath)
rip, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ rip, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: "Saturnz Barz (Official Video)", AlbumID: album.ID, ArtistID: artist.ID, Title: "Neptunez Barz (Official Video)", AlbumID: album.ID, ArtistID: artist.ID,
DurationMs: 1000, FilePath: f.ripPath, FileSize: 100, FileFormat: "mp3", DurationMs: 1000, FilePath: f.ripPath, FileSize: 100, FileFormat: "mp3",
}) })
if err != nil { if err != nil {
@@ -58,7 +58,7 @@ func newResolveFixture(t *testing.T) resolveFixture {
t.Fatalf("exec %q: %v", sql, err) t.Fatalf("exec %q: %v", sql, err)
} }
} }
exec(`UPDATE tracks SET title = 'Saturnz Barz' WHERE id = $1`, f.clean.ID) exec(`UPDATE tracks SET title = 'Neptunez Barz' WHERE id = $1`, f.clean.ID)
if err := pool.QueryRow(ctx, if err := pool.QueryRow(ctx,
`INSERT INTO duplicate_groups (member_key, tier) VALUES ('resolve-fixture', 'exact') RETURNING id`, `INSERT INTO duplicate_groups (member_key, tier) VALUES ('resolve-fixture', 'exact') RETURNING id`,
).Scan(&f.groupID); err != nil { ).Scan(&f.groupID); err != nil {
@@ -150,9 +150,9 @@ func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture {
q := dbq.New(pool) q := dbq.New(pool)
root := t.TempDir() root := t.TempDir()
f := crossReleaseRipFixture{pool: pool} f := crossReleaseRipFixture{pool: pool}
f.cleanPath = filepath.Join(root, "Gorillaz", "Demon Days (2005)", "06 - Feel Good Inc.mp3") f.cleanPath = filepath.Join(root, "Plastic Apes", "Ghost Nights (2005)", "06 - Feel Fine Ltd.mp3")
f.ripPath = filepath.Join(root, "Gorillaz", "Feel Good Inc (2005)", "01 - Feel Good Inc. (Official Video).mp3") f.ripPath = filepath.Join(root, "Plastic Apes", "Feel Fine Ltd (2005)", "01 - Feel Fine Ltd. (Official Video).mp3")
artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Gorillaz", SortName: "Gorillaz"}) artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Plastic Apes", SortName: "Plastic Apes"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -177,8 +177,8 @@ func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture {
} }
return tr return tr
} }
f.clean = track("Demon Days", "Feel Good Inc.", f.cleanPath) f.clean = track("Ghost Nights", "Feel Fine Ltd.", f.cleanPath)
f.rip = track("Feel Good Inc.", "Feel Good Inc. (Official Video)", f.ripPath) f.rip = track("Feel Fine Ltd.", "Feel Fine Ltd. (Official Video)", f.ripPath)
if err := pool.QueryRow(ctx, if err := pool.QueryRow(ctx,
`INSERT INTO duplicate_groups (member_key, tier) VALUES ('cross-rip', 'acoustic') RETURNING id`, `INSERT INTO duplicate_groups (member_key, tier) VALUES ('cross-rip', 'acoustic') RETURNING id`,
).Scan(&f.groupID); err != nil { ).Scan(&f.groupID); err != nil {
@@ -217,8 +217,8 @@ func TestResolveDuplicates_MergesARipAcrossReleases_Integration(t *testing.T) {
func TestResolveDuplicates_KeepsCleanCopiesOnTwoReleases_Integration(t *testing.T) { func TestResolveDuplicates_KeepsCleanCopiesOnTwoReleases_Integration(t *testing.T) {
for name, prepare := range map[string]func(f crossReleaseRipFixture) (string, []any){ for name, prepare := range map[string]func(f crossReleaseRipFixture) (string, []any){
"renamed": func(f crossReleaseRipFixture) (string, []any) { "renamed": func(f crossReleaseRipFixture) (string, []any) {
return `UPDATE tracks SET title = 'Feel Good Inc.', file_path = $2 WHERE id = $1`, return `UPDATE tracks SET title = 'Feel Fine Ltd.', file_path = $2 WHERE id = $1`,
[]any{f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Good Inc.mp3")} []any{f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Fine Ltd.mp3")}
}, },
"kept as fine": func(f crossReleaseRipFixture) (string, []any) { "kept as fine": func(f crossReleaseRipFixture) (string, []any) {
return `UPDATE tracks SET source_verdict = 'fine' WHERE id = $1`, []any{f.rip.ID} return `UPDATE tracks SET source_verdict = 'fine' WHERE id = $1`, []any{f.rip.ID}
@@ -245,7 +245,7 @@ func TestResolveDuplicates_KeepsCleanCopiesOnTwoReleases_Integration(t *testing.
} }
// Identical audio under two titles on two albums, neither a rip: a later // Identical audio under two titles on two albums, neither a rip: a later
// release retitled the recording ("F.O.D." and "F.O.D. (live)"). Each copy // release retitled the recording ("F.O.E." and "F.O.E. (live)"). Each copy
// belongs to its release, so nothing is removed and they count as one song. // belongs to its release, so nothing is removed and they count as one song.
func TestResolveDuplicates_LinksOneRecordingUnderTwoTitles_Integration(t *testing.T) { func TestResolveDuplicates_LinksOneRecordingUnderTwoTitles_Integration(t *testing.T) {
f := newCrossReleaseRipFixture(t) f := newCrossReleaseRipFixture(t)
@@ -282,7 +282,7 @@ func newOneAlbumFixture(t *testing.T, tier, titleA, titleB string) oneAlbumFixtu
pool := newPool(t) pool := newPool(t)
ctx := context.Background() ctx := context.Background()
q := dbq.New(pool) q := dbq.New(pool)
dir := filepath.Join(t.TempDir(), "Savant", "Void") dir := filepath.Join(t.TempDir(), "Savanta", "Void")
if err := os.MkdirAll(dir, 0o755); err != nil { if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -331,7 +331,7 @@ func auditCount(t *testing.T, pool *pgxpool.Pool, action string, groupID pgtype.
// Two versions of a song on one album that sound alike are not duplicates: // Two versions of a song on one album that sound alike are not duplicates:
// the group is dismissed and both files stay. // the group is dismissed and both files stay.
func TestResolveDuplicates_DismissesTwoVersionsOfASong_Integration(t *testing.T) { func TestResolveDuplicates_DismissesTwoVersionsOfASong_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Lovesick", "Lovesick (Instrumental)") f := newOneAlbumFixture(t, "acoustic", "Homesick", "Homesick (Instrumental)")
res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -418,7 +418,7 @@ func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testi
} }
// A slot emptied of another song's file folds into a copy of its own song the // A slot emptied of another song's file folds into a copy of its own song the
// album already holds (Savant's VOID DLC "Weeper" beside Void's). A copy under // album already holds (Savanta's VOID DLC "Sleeper" beside Void's). A copy under
// the title that is not as long as the song is another song: the slot waits for // the title that is not as long as the song is another song: the slot waits for
// a good copy, and folds into that. // a good copy, and folds into that.
func TestResolveDuplicates_EmptiedSlotFoldsOnlyIntoItsOwnSong_Integration(t *testing.T) { func TestResolveDuplicates_EmptiedSlotFoldsOnlyIntoItsOwnSong_Integration(t *testing.T) {
@@ -465,7 +465,7 @@ func TestResolveDuplicates_EmptiedSlotFoldsOnlyIntoItsOwnSong_Integration(t *tes
} }
// One recording filling two slots whose songs are both clearly something else // One recording filling two slots whose songs are both clearly something else
// (Shnabubula's whole album in one file): both copies go, nothing is kept. // (Shnorkelbub's whole album in one file): both copies go, nothing is kept.
func TestResolveDuplicates_RemovesEveryCopyWhenNoSlotIsTheirs_Integration(t *testing.T) { func TestResolveDuplicates_RemovesEveryCopyWhenNoSlotIsTheirs_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 282000, "Reach": 421000}) seedTrackList(t, f.pool, f.album, map[string]int{"Void": 282000, "Reach": 421000})
@@ -735,7 +735,7 @@ func TestResolveDuplicates_HoldsBackRips_Integration(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if _, err := f.pool.Exec(ctx, `UPDATE tracks SET file_path = $2 WHERE id = $1`, if _, err := f.pool.Exec(ctx, `UPDATE tracks SET file_path = $2 WHERE id = $1`,
f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Good Inc.mp3")); err != nil { f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Fine Ltd.mp3")); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if res := resolve(); res.Released != 1 { if res := resolve(); res.Released != 1 {
+5 -5
View File
@@ -22,8 +22,8 @@ import (
// Retitles across releases are linked like any cross-release group. What is // Retitles across releases are linked like any cross-release group. What is
// left on one album is three shapes: // left on one album is three shapes:
// //
// - distinct: two versions of a song that sound alike ("Lovesick" and // - distinct: two versions of a song that sound alike ("Homesick" and
// "Lovesick (Instrumental)"). Not duplicates, so the group is dismissed. // "Homesick (Instrumental)"). Not duplicates, so the group is dismissed.
// - mismatch: one file filling several track slots (one recording as // - mismatch: one file filling several track slots (one recording as
// three of an album's tracks). The album's MusicBrainz track list // three of an album's tracks). The album's MusicBrainz track list
// says how long each slot's song is. When exactly one slot's song is as // says how long each slot's song is. When exactly one slot's song is as
@@ -70,7 +70,7 @@ type slotCopy struct {
// wrongSlots decides which copies of a one-album mismatch sit in a slot that // wrongSlots decides which copies of a one-album mismatch sit in a slot that
// is not theirs. keep is the copy whose slot fits the recording, or -1 when // is not theirs. keep is the copy whose slot fits the recording, or -1 when
// every copy is clearly another song's (Shnabubula's whole album, 45 minutes // every copy is clearly another song's (Shnorkelbub's whole album, 45 minutes
// in one file, filed as both "Fading Light" and "Looking for Answers"): then // in one file, filed as both "Fading Light" and "Looking for Answers"): then
// all of them go. ok is false when the track list cannot say, and nothing // all of them go. ok is false when the track list cannot say, and nothing
// should be removed. // should be removed.
@@ -426,8 +426,8 @@ func groupRecordings(
// emptiedSlots is the losers whose song the album holds no other copy of: // emptiedSlots is the losers whose song the album holds no other copy of:
// no present track on it under that title as long as the song's slot. Those // no present track on it under that title as long as the song's slot. Those
// wait for a good copy to arrive. The rest are the song held // wait for a good copy to arrive. The rest are the song held
// twice, and missing-pair folding folds them into the copy held: Savant's // twice, and missing-pair folding folds them into the copy held: Savanta's
// VOID DLC "Weeper" beside Void's. A failed read counts every loser as // VOID DLC "Sleeper" beside Void's. A failed read counts every loser as
// emptied, which only makes the album wait for a copy it may not need. // emptied, which only makes the album wait for a copy it may not need.
func emptiedSlots( func emptiedSlots(
ctx context.Context, q *dbq.Queries, logger *slog.Logger, g *resolveGroup, losers []int, tracks []dbq.MbReleaseTrack, ctx context.Context, q *dbq.Queries, logger *slog.Logger, g *resolveGroup, losers []int, tracks []dbq.MbReleaseTrack,
+1 -1
View File
@@ -121,7 +121,7 @@ func TestSettleWrongSlot_KeepsTheCopyTheOperatorNames_Integration(t *testing.T)
func TestSettleWrongSlot_RefusesWhatItCannotSettle_Integration(t *testing.T) { func TestSettleWrongSlot_RefusesWhatItCannotSettle_Integration(t *testing.T) {
ctx := context.Background() ctx := context.Background()
t.Run("two versions of a song", func(t *testing.T) { t.Run("two versions of a song", func(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Lovesick", "Lovesick (Instrumental)") f := newOneAlbumFixture(t, "acoustic", "Homesick", "Homesick (Instrumental)")
if _, err := SettleWrongSlot(ctx, f.pool, nil, f.groupID, pgtype.UUID{}, pgtype.UUID{}); !errors.Is(err, ErrNotWrongSlot) { if _, err := SettleWrongSlot(ctx, f.pool, nil, f.groupID, pgtype.UUID{}, pgtype.UUID{}); !errors.Is(err, ErrNotWrongSlot) {
t.Errorf("err = %v, want ErrNotWrongSlot", err) t.Errorf("err = %v, want ErrNotWrongSlot", err)
} }
+1 -1
View File
@@ -119,7 +119,7 @@ func TestProposeSurvivor_LosslessThenTagFit(t *testing.T) {
wantID: "fits", wantReason: "tags fit the album", wantID: "fits", wantReason: "tags fit the album",
}, },
{ {
// The Humanz shape: two rips a few bytes apart, one carrying a // The Mammalz shape: two rips a few bytes apart, one carrying a
// video marker and clashing with another track's position. // video marker and clashing with another track's position.
name: "tag fit beats a few bytes", name: "tag fit beats a few bytes",
cands: []SurvivorCandidate{ cands: []SurvivorCandidate{
+2 -2
View File
@@ -68,8 +68,8 @@ func hashRow(n byte, path string) dbq.FindMissingTrackByAudioHashRow {
func audioHash(b byte) []byte { return bytes.Repeat([]byte{b}, 32) } func audioHash(b byte) []byte { return bytes.Repeat([]byte{b}, 32) }
const ( const (
oldPath = "/music/Linkin Park/Minutes to Midnight/02 - Bleed It Out.mp3" oldPath = "/music/Lincoln Yard/Minutes to Noon/02 - Bleed It Out.mp3"
newPath = "/music/Linkin Park/Minutes to Midnight/04 - Bleed It Out.mp3" newPath = "/music/Lincoln Yard/Minutes to Noon/04 - Bleed It Out.mp3"
) )
func TestAdoptMovedTrack_MatchesByMbid(t *testing.T) { func TestAdoptMovedTrack_MatchesByMbid(t *testing.T) {
+4 -4
View File
@@ -59,12 +59,12 @@ func TestAnnounceNewAlbums_TellsEveryoneOfEachNewAlbumOnce(t *testing.T) {
} }
// A new album with its own new track. // A new album with its own new track.
arrived, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Geogaddi", SortTitle: "Geogaddi", ArtistID: artist.ID}) arrived, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Geomantic", SortTitle: "Geomantic", ArtistID: artist.ID})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: "Music Is Math", AlbumID: arrived.ID, ArtistID: artist.ID, Title: "Music Is Maps", AlbumID: arrived.ID, ArtistID: artist.ID,
DurationMs: 1000, FilePath: filepath.Join(dir, "b.mp3"), FileSize: 100, FileFormat: "mp3", DurationMs: 1000, FilePath: filepath.Join(dir, "b.mp3"), FileSize: 100, FileFormat: "mp3",
}); err != nil { }); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -82,9 +82,9 @@ func TestAnnounceNewAlbums_TellsEveryoneOfEachNewAlbumOnce(t *testing.T) {
for _, u := range []dbq.User{admin, listener} { for _, u := range []dbq.User{admin, listener} {
got := newMusicNotices(t, q, u) got := newMusicNotices(t, q, u)
if len(got) != 1 || got[0].Count != 1 || len(got[0].Albums) != 1 || if len(got) != 1 || got[0].Count != 1 || len(got[0].Albums) != 1 ||
got[0].Albums[0].Title != "Geogaddi" || got[0].Albums[0].AlbumID != arrived.ID.String() || got[0].Albums[0].Title != "Geomantic" || got[0].Albums[0].AlbumID != arrived.ID.String() ||
got[0].Albums[0].Artist != "Delete Test Artist" { got[0].Albums[0].Artist != "Delete Test Artist" {
t.Fatalf("%s's notices = %+v, want one naming Geogaddi alone", u.Username, got) t.Fatalf("%s's notices = %+v, want one naming Geomantic alone", u.Username, got)
} }
} }
+8 -8
View File
@@ -388,7 +388,7 @@ func TestScanner_ReleaseGroupMBID_Integration(t *testing.T) {
} }
// Two albums of one name by one artist, in different release groups, are two // Two albums of one name by one artist, in different release groups, are two
// albums, as Weezer's self-titled albums are. A // albums, as Glasshouse's self-titled albums are. A
// track of the same group joins its album, and a track filed under the other // track of the same group joins its album, and a track filed under the other
// album's row by the old lookup moves to its own on the tagReadVersion re-read. // album's row by the old lookup moves to its own on the tagReadVersion re-read.
func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing.T) { func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing.T) {
@@ -421,14 +421,14 @@ func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing.
tagged := func(rel, title, group string) string { tagged := func(rel, title, group string) string {
p := filepath.Join(root, rel) p := filepath.Join(root, rel)
writeTestMP3(t, p, map[string]string{ writeTestMP3(t, p, map[string]string{
"TIT2": title, "TPE1": "Weezer", "TALB": "Weezer", "TIT2": title, "TPE1": "Glasshouse", "TALB": "Glasshouse",
"TXXX": "MusicBrainz Release Group Id\x00" + group, "TXXX": "MusicBrainz Release Group Id\x00" + group,
}) })
return p return p
} }
tagged("Weezer (1994)/01.mp3", "My Name Is Jonas", blue) tagged("Glasshouse (1994)/01.mp3", "My Name Is Tobias", blue)
tagged("Weezer (1994)/02.mp3", "No One Else", blue) tagged("Glasshouse (1994)/02.mp3", "No One Near", blue)
greenPath := tagged("Weezer (2001)/01.mp3", "Don't Let Go", green) greenPath := tagged("Glasshouse (2001)/01.mp3", "Don't Look Down", green)
scanner := New(pool, logger, []string{root}, nil) scanner := New(pool, logger, []string{root}, nil)
if _, err := scanner.Scan(ctx, nil); err != nil { if _, err := scanner.Scan(ctx, nil); err != nil {
@@ -437,7 +437,7 @@ func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing.
albumsByGroup := func() map[string]int { albumsByGroup := func() map[string]int {
t.Helper() t.Helper()
rows, err := pool.Query(ctx, `SELECT a.release_group_mbid, count(t.id) FROM albums a rows, err := pool.Query(ctx, `SELECT a.release_group_mbid, count(t.id) FROM albums a
JOIN tracks t ON t.album_id = a.id WHERE a.title = 'Weezer' GROUP BY a.id, a.release_group_mbid`) JOIN tracks t ON t.album_id = a.id WHERE a.title = 'Glasshouse' GROUP BY a.id, a.release_group_mbid`)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -462,8 +462,8 @@ func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing.
// A bonus track tagged with no release group joins the album its folder // A bonus track tagged with no release group joins the album its folder
// holds, whichever row is older. // holds, whichever row is older.
writeTestMP3(t, filepath.Join(root, "Weezer (2001)/02.mp3"), map[string]string{ writeTestMP3(t, filepath.Join(root, "Glasshouse (2001)/02.mp3"), map[string]string{
"TIT2": "Photograph (live)", "TPE1": "Weezer", "TALB": "Weezer", "TIT2": "Polaroid (live)", "TPE1": "Glasshouse", "TALB": "Glasshouse",
}) })
if _, err := scanner.Scan(ctx, nil); err != nil { if _, err := scanner.Scan(ctx, nil); err != nil {
t.Fatalf("scan the bonus track: %v", err) t.Fatalf("scan the bonus track: %v", err)
+10 -10
View File
@@ -42,7 +42,7 @@ func newSongLinkFixture(t *testing.T, pool *pgxpool.Pool) songLinkFixture {
t.Fatal(err) t.Fatal(err)
} }
tr, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ tr, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: "Feel Good Inc.", AlbumID: a.ID, ArtistID: artist.ID, Title: "Feel Fine Ltd.", AlbumID: a.ID, ArtistID: artist.ID,
DurationMs: 1000, FilePath: path, FileSize: 100, FileFormat: "mp3", DurationMs: 1000, FilePath: path, FileSize: 100, FileFormat: "mp3",
}) })
if err != nil { if err != nil {
@@ -51,8 +51,8 @@ func newSongLinkFixture(t *testing.T, pool *pgxpool.Pool) songLinkFixture {
return tr return tr
} }
f := songLinkFixture{ f := songLinkFixture{
single: track("Feel Good Inc. (single)", "/music/Link Artist/Feel Good Inc/01 Feel Good Inc.mp3"), single: track("Feel Fine Ltd. (single)", "/music/Link Artist/Feel Fine Ltd/01 Feel Fine Ltd.mp3"),
albumCut: track("Demon Days", "/music/Link Artist/Demon Days/06 Feel Good Inc.mp3"), albumCut: track("Ghost Nights", "/music/Link Artist/Ghost Nights/06 Feel Fine Ltd.mp3"),
} }
f.user, err = q.CreateUser(ctx, dbq.CreateUserParams{ f.user, err = q.CreateUser(ctx, dbq.CreateUserParams{
Username: dbtest.TestUserPrefix + "song-link", PasswordHash: "x", ApiTokenHash: "song-link-token", Username: dbtest.TestUserPrefix + "song-link", PasswordHash: "x", ApiTokenHash: "song-link-token",
@@ -221,7 +221,7 @@ func songKeys(t *testing.T, q *dbq.Queries, ids ...pgtype.UUID) []pgtype.UUID {
return out return out
} }
// A cross-release group whose album holds the song twice (Humanz: Saturnz // A cross-release group whose album holds the song twice (Mammalz: Neptunez
// Barz as a FLAC and a YouTube mp3, beside the single): the album's // Barz as a FLAC and a YouTube mp3, beside the single): the album's
// extra copy is merged into its FLAC, the single stays, and the two copies // extra copy is merged into its FLAC, the single stays, and the two copies
// left are linked as one song. // left are linked as one song.
@@ -230,7 +230,7 @@ func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integratio
ctx := context.Background() ctx := context.Background()
q := dbq.New(pool) q := dbq.New(pool)
dir := t.TempDir() dir := t.TempDir()
artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Gorillaz", SortName: "Gorillaz"}) artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Plastic Apes", SortName: "Plastic Apes"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -254,7 +254,7 @@ func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integratio
t.Fatal(err) t.Fatal(err)
} }
tr, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{ tr, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: "Saturnz Barz", AlbumID: a.ID, ArtistID: artist.ID, Title: "Neptunez Barz", AlbumID: a.ID, ArtistID: artist.ID,
DurationMs: 181000, FilePath: path, FileSize: 100, FileFormat: format, DurationMs: 181000, FilePath: path, FileSize: 100, FileFormat: format,
}) })
if err != nil { if err != nil {
@@ -262,12 +262,12 @@ func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integratio
} }
return tr return tr
} }
flac := track("Humanz", "04 Saturnz Barz.flac", "flac") flac := track("Mammalz", "04 Neptunez Barz.flac", "flac")
mp3 := track("Humanz", "06 Saturnz Barz (feat. Popcaan).mp3", "mp3") mp3 := track("Mammalz", "06 Neptunez Barz (feat. Popcaan).mp3", "mp3")
single := track("Saturnz Barz", "01 Saturnz Barz.mp3", "mp3") single := track("Neptunez Barz", "01 Neptunez Barz.mp3", "mp3")
var groupID pgtype.UUID var groupID pgtype.UUID
if err := pool.QueryRow(ctx, if err := pool.QueryRow(ctx,
`INSERT INTO duplicate_groups (member_key, tier) VALUES ('humanz-saturnz', 'exact') RETURNING id`, `INSERT INTO duplicate_groups (member_key, tier) VALUES ('mammalz-neptunez', 'exact') RETURNING id`,
).Scan(&groupID); err != nil { ).Scan(&groupID); err != nil {
t.Fatal(err) t.Fatal(err)
} }
+9 -9
View File
@@ -13,24 +13,24 @@ func TestSourceMarkersFor(t *testing.T) {
base string base string
want []string want []string
}{ }{
{"Daft Punk - Random Access Memories - 06 - Daft Punk - Doin' It Right (Music Video) ft. Panda Bear.mp3", []string{"music video"}}, {"Deft Monks - Random Access Dreams - 06 - Deft Monks - Doin' It Twice (Music Video) ft. Koala Bear.mp3", []string{"music video"}},
{"Gorillaz - Humanz - 03 - Gorillaz - Saturnz Barz (Official Video).mp3", []string{"music video"}}, {"Plastic Apes - Mammalz - 03 - Plastic Apes - Neptunez Barz (Official Video).mp3", []string{"music video"}},
{"Gorillaz - Humanz - 05 - Gorillaz - Andromeda (Official Audio).mp3", []string{"official audio"}}, {"Plastic Apes - Mammalz - 05 - Plastic Apes - Cassiopeia (Official Audio).mp3", []string{"official audio"}},
{"Gorillaz - Gorillaz - 06 - Gorillaz - P45 (Visualizer).mp3", []string{"visualiser"}}, {"Plastic Apes - Plastic Apes - 06 - Plastic Apes - Q46 (Visualizer).mp3", []string{"visualiser"}},
{"Gorillaz - Demon Days - 16 - Gorillaz - Don Quixote's Christmas Bonanza (Visualiser).mp3", []string{"visualiser"}}, {"Plastic Apes - Ghost Nights - 16 - Plastic Apes - Sancho's Holiday Bonanza (Visualiser).mp3", []string{"visualiser"}},
{"Artist - Album - 01 - Artist - Song (Lyric Video).mp3", []string{"lyric video"}}, {"Artist - Album - 01 - Artist - Song (Lyric Video).mp3", []string{"lyric video"}},
{"Gorillaz - Humanz - 02 - FIRST TIME HEARING Gorillaz - Ascension REACTION.mp3", []string{"reaction"}}, {"Plastic Apes - Mammalz - 02 - FIRST TIME HEARING Plastic Apes - Elevation REACTION.mp3", []string{"reaction"}},
{"Watsky - INTENTION - 05 - MANIAC Reacts to Watsky - AWW SHiT.mp3", []string{"reaction"}}, {"Watsky - INTENTION - 05 - MANIAC Reacts to Watsky - AWW SHiT.mp3", []string{"reaction"}},
{"米津玄師 - diorama - 09 - 【MV】米津玄師 - 恋と病熱.mp3", []string{"MV"}}, {"米津玄師 - diorama - 09 - 【MV】米津玄師 - 恋と病熱.mp3", []string{"MV"}},
{"Andora - Ego - 01 - Andora - Ego (feat. Will Stetson) MV.mp3", []string{"MV"}}, {"Andora - Ego - 01 - Andora - Ego (feat. Will Stetson) MV.mp3", []string{"MV"}},
{"Jimmy Eat World - Something(s) Loud - 05 - Jimmy Eat World - Call to Love (Audio).mp3", []string{"[Audio]"}}, {"Jimmy Eat World - Something(s) Loud - 05 - Jimmy Eat World - Call to Love (Audio).mp3", []string{"[Audio]"}},
{"Record Heat - World War IV - 03 - Record Heat - Front Seat Feelin' [Audio].mp3", []string{"[Audio]"}}, {"Record Heat - World War IV - 03 - Record Heat - Front Seat Feelin' [Audio].mp3", []string{"[Audio]"}},
{"Aphex Twin - Come To Daddy - 03 - Aphex Twin - Bucephalus Bouncing Ball (HQ).mp3", []string{"[HD]"}}, {"Apex Sibling - Come To Mother - 03 - Apex Sibling - Pegasus Bouncing Ball (HQ).mp3", []string{"[HD]"}},
{"Artist - Album - 01 - Artist - Song (Official Lyric Video) [4K].mp3", []string{"lyric video", "[HD]"}}, {"Artist - Album - 01 - Artist - Song (Official Lyric Video) [4K].mp3", []string{"lyric video", "[HD]"}},
{"Beck - Guero - 15 - Beck - Chain Reaction.mp3", nil}, {"Beck - Guero - 15 - Beck - Chain Reaction.mp3", nil},
{"Nirvana - MTV Unplugged in New York - 01 - About a Girl (live in New York).flac", nil}, {"Kettle Saints - Unplugged in Old York - 01 - About a Ghost (live in New York).flac", nil},
{"Boards of Canada - Music Has the Right to Children - 05 - Roygbiv.flac", nil}, {"Fields of Ontario - Music Has the Right to Wander - 05 - Prismatic.flac", nil},
{"Artist - Album - 01 - Mvula.flac", nil}, {"Artist - Album - 01 - Mvula.flac", nil},
} }
for _, c := range cases { for _, c := range cases {
+1 -1
View File
@@ -175,7 +175,7 @@ func composeMessage(cfg dbq.SmtpConfig, to, subject, textBody, htmlBody string)
// encodeSubject makes subject safe as a header value. Line breaks are // encodeSubject makes subject safe as a header value. Line breaks are
// replaced, so a name carried into a subject cannot start a header of its // replaced, so a name carried into a subject cannot start a header of its
// own, and non-ASCII text ("Moe Shop – WWW") is RFC 2047 encoded, which // own, and non-ASCII text ("Mochi Shop – XYZ") is RFC 2047 encoded, which
// mime.QEncoding leaves alone when there is nothing to encode. // mime.QEncoding leaves alone when there is nothing to encode.
func encodeSubject(subject string) string { func encodeSubject(subject string) string {
subject = strings.NewReplacer("\r\n", " ", "\r", " ", "\n", " ").Replace(subject) subject = strings.NewReplacer("\r\n", " ", "\r", " ", "\n", " ").Replace(subject)
+2 -2
View File
@@ -11,11 +11,11 @@ func TestEncodeSubject(t *testing.T) {
t.Errorf("plain ASCII changed: %q", got) t.Errorf("plain ASCII changed: %q", got)
} }
enc := encodeSubject("Minstrel: Moe Shop – WWW") enc := encodeSubject("Minstrel: Mochi Shop – XYZ")
if !strings.HasPrefix(enc, "=?utf-8?q?") { if !strings.HasPrefix(enc, "=?utf-8?q?") {
t.Errorf("non-ASCII not RFC 2047 encoded: %q", enc) t.Errorf("non-ASCII not RFC 2047 encoded: %q", enc)
} }
if dec, err := new(mime.WordDecoder).DecodeHeader(enc); err != nil || dec != "Minstrel: Moe Shop – WWW" { if dec, err := new(mime.WordDecoder).DecodeHeader(enc); err != nil || dec != "Minstrel: Mochi Shop – XYZ" {
t.Errorf("round trip = %q, %v", dec, err) t.Errorf("round trip = %q, %v", dec, err)
} }
+1 -1
View File
@@ -178,7 +178,7 @@ func sleep(ctx context.Context, d time.Duration) error {
const luceneSpecial = `+-&|!(){}[]^"~*?:\/` const luceneSpecial = `+-&|!(){}[]^"~*?:\/`
// Escape makes text typed by a person safe to put in a search query, so // Escape makes text typed by a person safe to put in a search query, so
// "AC/DC" or "Sunn O)))" searches for what was typed rather than failing to // "AM/FM" or "Moon O)))" searches for what was typed rather than failing to
// parse. // parse.
func Escape(s string) string { func Escape(s string) string {
var b strings.Builder var b strings.Builder
+22 -22
View File
@@ -19,10 +19,10 @@ func testClient(srv *httptest.Server) *Client {
func TestEscape_KeepsWhatWasTyped(t *testing.T) { func TestEscape_KeepsWhatWasTyped(t *testing.T) {
for in, want := range map[string]string{ for in, want := range map[string]string{
"Radiohead": "Radiohead", "Signal Tower": "Signal Tower",
"AC/DC": `AC\/DC`, "AM/FM": `AM\/FM`,
"Sunn O)))": `Sunn O\)\)\)`, "Moon O)))": `Moon O\)\)\)`,
`"Weird" Al`: `\"Weird\" Al`, `"Odd" Al`: `\"Odd\" Al`,
} { } {
if got := Escape(in); got != want { if got := Escape(in); got != want {
t.Errorf("Escape(%q) = %q, want %q", in, got, want) t.Errorf("Escape(%q) = %q, want %q", in, got, want)
@@ -36,24 +36,24 @@ func TestSearchReleaseGroups_AsksTitleAndArtistAndReadsCredits(t *testing.T) {
query.Store(r.URL.Query().Get("query")) query.Store(r.URL.Query().Get("query"))
agent.Store(r.Header.Get("User-Agent")) agent.Store(r.Header.Get("User-Agent"))
_, _ = w.Write([]byte(`{"release-groups": [{ _, _ = w.Write([]byte(`{"release-groups": [{
"id": "rg1", "title": "OK Computer", "primary-type": "Album", "secondary-types": [], "id": "rg1", "title": "OK Calculator", "primary-type": "Album", "secondary-types": [],
"first-release-date": "1997-05-21", "first-release-date": "1997-05-21",
"artist-credit": [{"name": "Radiohead", "joinphrase": "", "artist": {"id": "a1", "name": "Radiohead"}}] "artist-credit": [{"name": "Signal Tower", "joinphrase": "", "artist": {"id": "a1", "name": "Signal Tower"}}]
}]}`)) }]}`))
})) }))
defer srv.Close() defer srv.Close()
got, err := testClient(srv).SearchReleaseGroups(context.Background(), "ok computer", 10) got, err := testClient(srv).SearchReleaseGroups(context.Background(), "ok calculator", 10)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if q := query.Load(); q != "releasegroup:(ok computer) OR artist:(ok computer)" { if q := query.Load(); q != "releasegroup:(ok calculator) OR artist:(ok calculator)" {
t.Errorf("query = %q", q) t.Errorf("query = %q", q)
} }
if agent.Load() != UserAgent { if agent.Load() != UserAgent {
t.Errorf("User-Agent = %q", agent.Load()) t.Errorf("User-Agent = %q", agent.Load())
} }
if len(got) != 1 || got[0].MBID != "rg1" || got[0].Year() != "1997" || got[0].ArtistCredit != "Radiohead" || got[0].ArtistMBIDs[0] != "a1" { if len(got) != 1 || got[0].MBID != "rg1" || got[0].Year() != "1997" || got[0].ArtistCredit != "Signal Tower" || got[0].ArtistMBIDs[0] != "a1" {
t.Errorf("got %+v", got) t.Errorf("got %+v", got)
} }
} }
@@ -62,16 +62,16 @@ func TestSearchReleaseGroupsBy_AsksForBothTitleAndArtist(t *testing.T) {
var query atomic.Value var query atomic.Value
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
query.Store(r.URL.Query().Get("query")) query.Store(r.URL.Query().Get("query"))
_, _ = w.Write([]byte(`{"release-groups": [{"id": "rg1", "title": "Highway to Hell", _, _ = w.Write([]byte(`{"release-groups": [{"id": "rg1", "title": "Highway to Nowhere",
"artist-credit": [{"name": "AC/DC", "artist": {"id": "a1"}}]}]}`)) "artist-credit": [{"name": "AM/FM", "artist": {"id": "a1"}}]}]}`))
})) }))
defer srv.Close() defer srv.Close()
got, err := testClient(srv).SearchReleaseGroupsBy(context.Background(), " AC/DC ", "Highway to Hell", 10) got, err := testClient(srv).SearchReleaseGroupsBy(context.Background(), " AM/FM ", "Highway to Nowhere", 10)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if q := query.Load(); q != `releasegroup:(Highway to Hell) AND artist:(AC\/DC)` { if q := query.Load(); q != `releasegroup:(Highway to Nowhere) AND artist:(AM\/FM)` {
t.Errorf("query = %q", q) t.Errorf("query = %q", q)
} }
if len(got) != 1 || got[0].MBID != "rg1" || got[0].ArtistMBIDs[0] != "a1" { if len(got) != 1 || got[0].MBID != "rg1" || got[0].ArtistMBIDs[0] != "a1" {
@@ -82,17 +82,17 @@ func TestSearchReleaseGroupsBy_AsksForBothTitleAndArtist(t *testing.T) {
func TestSearchRecordings_FilesASongUnderItsAlbum(t *testing.T) { func TestSearchRecordings_FilesASongUnderItsAlbum(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"recordings": [{ _, _ = w.Write([]byte(`{"recordings": [{
"id": "rec1", "title": "Karma Police", "length": 264000, "id": "rec1", "title": "Karma Patrol", "length": 264000,
"artist-credit": [{"name": "Radiohead", "artist": {"id": "a1"}}], "artist-credit": [{"name": "Signal Tower", "artist": {"id": "a1"}}],
"releases": [ "releases": [
{"id": "r1", "status": "Official", "release-group": {"id": "rg-live", "title": "Live", "primary-type": "Album", "secondary-types": ["Live"]}}, {"id": "r1", "status": "Official", "release-group": {"id": "rg-live", "title": "Live", "primary-type": "Album", "secondary-types": ["Live"]}},
{"id": "r2", "status": "Official", "release-group": {"id": "rg1", "title": "OK Computer", "primary-type": "Album"}} {"id": "r2", "status": "Official", "release-group": {"id": "rg1", "title": "OK Calculator", "primary-type": "Album"}}
] ]
}]}`)) }]}`))
})) }))
defer srv.Close() defer srv.Close()
got, err := testClient(srv).SearchRecordings(context.Background(), "karma police", 5) got, err := testClient(srv).SearchRecordings(context.Background(), "karma patrol", 5)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -136,11 +136,11 @@ func TestReleaseGroupReleases_ReadsMediaAndTracks(t *testing.T) {
t.Errorf("inc = %q", r.URL.Query().Get("inc")) t.Errorf("inc = %q", r.URL.Query().Get("inc"))
} }
_, _ = w.Write([]byte(`{"release-count": 1, "releases": [{ _, _ = w.Write([]byte(`{"release-count": 1, "releases": [{
"id": "r1", "title": "OK Computer", "status": "Official", "date": "1997-06-16", "country": "GB", "id": "r1", "title": "OK Calculator", "status": "Official", "date": "1997-06-16", "country": "GB",
"media": [ "media": [
{"position": 1, "format": "CD", "tracks": [ {"position": 1, "format": "CD", "tracks": [
{"position": 1, "number": "1", "title": "Airbag", "length": 284000, "recording": {"id": "rec-a"}}, {"position": 1, "number": "1", "title": "Lifebelt", "length": 284000, "recording": {"id": "rec-a"}},
{"position": 2, "number": "2", "title": "Paranoid Android", "length": null, "recording": {"id": "rec-b", "length": 383000}} {"position": 2, "number": "2", "title": "Anxious Robot", "length": null, "recording": {"id": "rec-b", "length": 383000}}
]}, ]},
{"position": 2, "format": "CD", "tracks": []} {"position": 2, "format": "CD", "tracks": []}
] ]
@@ -171,11 +171,11 @@ func TestGet_ThrottleIsRetriedThenUnreachable(t *testing.T) {
w.WriteHeader(http.StatusServiceUnavailable) w.WriteHeader(http.StatusServiceUnavailable)
return return
} }
_, _ = w.Write([]byte(`{"artists": [{"id": "a1", "name": "Radiohead"}]}`)) _, _ = w.Write([]byte(`{"artists": [{"id": "a1", "name": "Signal Tower"}]}`))
})) }))
defer srv.Close() defer srv.Close()
got, err := testClient(srv).SearchArtists(context.Background(), "radiohead", 5) got, err := testClient(srv).SearchArtists(context.Background(), "signal tower", 5)
if err != nil || len(got) != 1 || calls.Load() != 2 { if err != nil || len(got) != 1 || calls.Load() != 2 {
t.Fatalf("a throttled first answer should be retried: %v, %+v, %d calls", err, got, calls.Load()) t.Fatalf("a throttled first answer should be retried: %v, %+v, %d calls", err, got, calls.Load())
} }
+2 -2
View File
@@ -235,8 +235,8 @@ func (c *Client) SearchArtists(ctx context.Context, text string, limit int) ([]A
return out, nil return out, nil
} }
// SearchReleaseGroups finds albums by title or by artist, so "radiohead ok // SearchReleaseGroups finds albums by title or by artist, so "signal tower ok
// computer" and "ok computer" both find OK Computer. // computer" and "ok calculator" both find OK Calculator.
func (c *Client) SearchReleaseGroups(ctx context.Context, text string, limit int) ([]ReleaseGroup, error) { func (c *Client) SearchReleaseGroups(ctx context.Context, text string, limit int) ([]ReleaseGroup, error) {
var resp struct { var resp struct {
ReleaseGroups []wireReleaseGroup `json:"release-groups"` ReleaseGroups []wireReleaseGroup `json:"release-groups"`
+7 -7
View File
@@ -38,9 +38,9 @@ func TestDigest_BatchGoesOutOnceAWindowAfterTheFirstItem(t *testing.T) {
start := time.Now() start := time.Now()
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice),
notifications.Payload{Name: "Moe Shop – WWW"}.Map())) notifications.Payload{Name: "Mochi Shop – XYZ"}.Map()))
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice),
notifications.Payload{Name: "Tycho – Awake", Reason: "already have it"}.Map())) notifications.Payload{Name: "Tacho – Asleep", Reason: "already have it"}.Map()))
d.Tick(ctx, start.Add(30*time.Minute)) d.Tick(ctx, start.Add(30*time.Minute))
require.Empty(t, fake.Sent, "inside the window nothing goes") require.Empty(t, fake.Sent, "inside the window nothing goes")
@@ -49,8 +49,8 @@ func TestDigest_BatchGoesOutOnceAWindowAfterTheFirstItem(t *testing.T) {
require.Len(t, fake.Sent, 1, "both items, one email") require.Len(t, fake.Sent, 1, "both items, one email")
require.Equal(t, "alice@example.com", fake.Sent[0].To) require.Equal(t, "alice@example.com", fake.Sent[0].To)
require.Equal(t, "Minstrel: 2 updates", fake.Sent[0].Subject) require.Equal(t, "Minstrel: 2 updates", fake.Sent[0].Subject)
require.Contains(t, fake.Sent[0].TextBody, "Someone flagged Moe Shop – WWW.") require.Contains(t, fake.Sent[0].TextBody, "Someone flagged Mochi Shop – XYZ.")
require.Contains(t, fake.Sent[0].TextBody, "Someone flagged Tycho – Awake: already have it") require.Contains(t, fake.Sent[0].TextBody, "Someone flagged Tacho – Asleep: already have it")
d.Tick(ctx, start.Add(3*time.Hour)) d.Tick(ctx, start.Add(3*time.Hour))
require.Len(t, fake.Sent, 1, "never sent twice") require.Len(t, fake.Sent, 1, "never sent twice")
@@ -171,8 +171,8 @@ func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) {
} }
for _, a := range []notifications.Arrival{ for _, a := range []notifications.Arrival{
{Artist: "Moe Shop", Title: "WWW"}, {Artist: "Mochi Shop", Title: "XYZ"},
{Artist: "Moe Shop", Title: "Pure"}, {Artist: "Mochi Shop", Title: "Pure"},
} { } {
p := notifications.Payload{Count: 1, Albums: []notifications.Arrival{a}} p := notifications.Payload{Count: 1, Albums: []notifications.Arrival{a}}
require.NoError(t, n.Notify(ctx, notifications.KindNewMusic, notifications.ToUser(alice), p.Map())) require.NoError(t, n.Notify(ctx, notifications.KindNewMusic, notifications.ToUser(alice), p.Map()))
@@ -184,7 +184,7 @@ func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) {
d.Tick(ctx, slot) d.Tick(ctx, slot)
require.Len(t, fake.Sent, 1) require.Len(t, fake.Sent, 1)
require.Equal(t, "Minstrel: new music in your library", fake.Sent[0].Subject) require.Equal(t, "Minstrel: new music in your library", fake.Sent[0].Subject)
require.Contains(t, fake.Sent[0].TextBody, "Moe Shop\n - WWW") require.Contains(t, fake.Sent[0].TextBody, "Mochi Shop\n - XYZ")
require.Contains(t, fake.Sent[0].TextBody, " - Pure") require.Contains(t, fake.Sent[0].TextBody, " - Pure")
d.Tick(ctx, slot.Add(5*time.Hour)) d.Tick(ctx, slot.Add(5*time.Hour))
+11 -11
View File
@@ -137,22 +137,22 @@ func TestRenderDigest_SummaryGroupsByArtist(t *testing.T) {
return pendingItem{Kind: KindNewMusic, Payload: b} return pendingItem{Kind: KindNewMusic, Payload: b}
} }
items := []pendingItem{ items := []pendingItem{
scan(Arrival{Artist: "Moe Shop", Title: "WWW", ArtistID: "ar-1", AlbumID: "al-1"}, scan(Arrival{Artist: "Mochi Shop", Title: "XYZ", ArtistID: "ar-1", AlbumID: "al-1"},
Arrival{Artist: "Boards of Canada", Title: "Geogaddi", AlbumID: "al-2"}), Arrival{Artist: "Fields of Ontario", Title: "Geomantic", AlbumID: "al-2"}),
scan(Arrival{Artist: "Moe Shop", Title: "Pure", ArtistID: "ar-1", AlbumID: "al-3"}), scan(Arrival{Artist: "Mochi Shop", Title: "Pure", ArtistID: "ar-1", AlbumID: "al-3"}),
} }
e, err := renderDigest(EmailSummary, "alice", items, "https://music.example/") e, err := renderDigest(EmailSummary, "alice", items, "https://music.example/")
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "Minstrel: new music in your library", e.Subject) require.Equal(t, "Minstrel: new music in your library", e.Subject)
moe := strings.Index(e.Text, "Moe Shop") moe := strings.Index(e.Text, "Mochi Shop")
require.GreaterOrEqual(t, moe, 0) require.GreaterOrEqual(t, moe, 0)
require.Equal(t, moe, strings.LastIndex(e.Text, "Moe Shop\n"), "one heading per artist, across scans") require.Equal(t, moe, strings.LastIndex(e.Text, "Mochi Shop\n"), "one heading per artist, across scans")
require.Less(t, moe, strings.Index(e.Text, "Boards of Canada"), "artists in the order they arrived") require.Less(t, moe, strings.Index(e.Text, "Fields of Ontario"), "artists in the order they arrived")
require.Contains(t, e.Text, "Moe Shop\n https://music.example/artists/ar-1") require.Contains(t, e.Text, "Mochi Shop\n https://music.example/artists/ar-1")
require.Contains(t, e.Text, " - WWW\n https://music.example/albums/al-1") require.Contains(t, e.Text, " - XYZ\n https://music.example/albums/al-1")
require.Contains(t, e.Text, " - Pure\n https://music.example/albums/al-3") require.Contains(t, e.Text, " - Pure\n https://music.example/albums/al-3")
require.Contains(t, e.Text, " - Geogaddi\n https://music.example/albums/al-2") require.Contains(t, e.Text, " - Geomantic\n https://music.example/albums/al-2")
require.Contains(t, e.Text, "https://music.example/settings/notifications") require.Contains(t, e.Text, "https://music.example/settings/notifications")
require.Contains(t, e.HTML, `<a href="https://music.example/albums/al-1"`) require.Contains(t, e.HTML, `<a href="https://music.example/albums/al-1"`)
} }
@@ -160,13 +160,13 @@ func TestRenderDigest_SummaryGroupsByArtist(t *testing.T) {
func TestRenderDigest_BatchListsEachItemAndEscapesHTML(t *testing.T) { func TestRenderDigest_BatchListsEachItemAndEscapesHTML(t *testing.T) {
b, _ := json.Marshal(Payload{Name: "<script>x</script>", Reason: "dup"}.Map()) b, _ := json.Marshal(Payload{Name: "<script>x</script>", Reason: "dup"}.Map())
items := []pendingItem{ items := []pendingItem{
{Kind: KindQuarantineFlagged, Payload: []byte(`{"name":"WWW","actor":"Ann"}`)}, {Kind: KindQuarantineFlagged, Payload: []byte(`{"name":"XYZ","actor":"Ann"}`)},
{Kind: KindQuarantineFlagged, Payload: b}, {Kind: KindQuarantineFlagged, Payload: b},
} }
e, err := renderDigest(EmailBatch, "alice", items, "") e, err := renderDigest(EmailBatch, "alice", items, "")
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "Minstrel: 2 updates", e.Subject) require.Equal(t, "Minstrel: 2 updates", e.Subject)
require.Contains(t, e.Text, "- Track flagged\n Ann flagged WWW.") require.Contains(t, e.Text, "- Track flagged\n Ann flagged XYZ.")
require.NotContains(t, e.Text, "http", "no public address: no links") require.NotContains(t, e.Text, "http", "no public address: no links")
require.Contains(t, e.Text, "Settings → Notifications") require.Contains(t, e.Text, "Settings → Notifications")
require.NotContains(t, e.HTML, "<script>") require.NotContains(t, e.HTML, "<script>")
+2 -2
View File
@@ -83,13 +83,13 @@ func TestNotify_WritesARowAndNudgesOnlyThatUser(t *testing.T) {
n := notifications.New(pool, bus, nil) n := notifications.New(pool, bus, nil)
require.NoError(t, n.Notify(ctx, notifications.KindNewMusic, require.NoError(t, n.Notify(ctx, notifications.KindNewMusic,
notifications.ToUser(alice), map[string]any{"count": 1, "name": "WWW"})) notifications.ToUser(alice), map[string]any{"count": 1, "name": "XYZ"}))
rows := rowsFor(t, q, alice) rows := rowsFor(t, q, alice)
require.Len(t, rows, 1) require.Len(t, rows, 1)
require.Equal(t, "new_music", rows[0].Kind) require.Equal(t, "new_music", rows[0].Kind)
require.False(t, rows[0].ReadAt.Valid) require.False(t, rows[0].ReadAt.Valid)
require.JSONEq(t, `{"count":1,"name":"WWW"}`, string(rows[0].Payload)) require.JSONEq(t, `{"count":1,"name":"XYZ"}`, string(rows[0].Payload))
require.Empty(t, rowsFor(t, q, bob)) require.Empty(t, rowsFor(t, q, bob))
select { select {
+2 -2
View File
@@ -23,7 +23,7 @@ type Rendered struct {
// Payload is what producers put in a notification. Every field is optional; // Payload is what producers put in a notification. Every field is optional;
// each kind documents the ones it uses in Render. // each kind documents the ones it uses in Render.
type Payload struct { type Payload struct {
// Name is what was flagged, as the user would say it: "Moe Shop – WWW". // Name is what was flagged, as the user would say it: "Mochi Shop – XYZ".
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"`
// Albums are new_music's arrivals, the first AlbumsKept of Count. // Albums are new_music's arrivals, the first AlbumsKept of Count.
Albums []Arrival `json:"albums,omitempty"` Albums []Arrival `json:"albums,omitempty"`
@@ -33,7 +33,7 @@ type Payload struct {
// Count is the coalesced kinds' running total since the notice was last // Count is the coalesced kinds' running total since the notice was last
// read. // read.
Count int64 `json:"count,omitempty"` Count int64 `json:"count,omitempty"`
// Items name what Count counts, one each, newest first: "Weezer – Buddy // Items name what Count counts, one each, newest first: "Glasshouse – Buddy
// Holly". A coalesced update puts its own in front and keeps ten, // Holly". A coalesced update puts its own in front and keeps ten,
// so the body can say which, not only how many. // so the body can say which, not only how many.
Items []string `json:"items,omitempty"` Items []string `json:"items,omitempty"`
+9 -9
View File
@@ -26,9 +26,9 @@ func TestRender_EveryKindHasATitleAndALink(t *testing.T) {
} }
func TestRender_NewMusicOpensWhatArrived(t *testing.T) { func TestRender_NewMusicOpensWhatArrived(t *testing.T) {
one := render(KindNewMusic, Payload{Count: 1, Albums: []Arrival{{Artist: "Moe Shop", Title: "WWW", AlbumID: "al-1"}}}) one := render(KindNewMusic, Payload{Count: 1, Albums: []Arrival{{Artist: "Mochi Shop", Title: "XYZ", AlbumID: "al-1"}}})
require.Equal(t, "New album", one.Title) require.Equal(t, "New album", one.Title)
require.Equal(t, "Moe Shop – WWW is in the library.", one.Body) require.Equal(t, "Mochi Shop – XYZ is in the library.", one.Body)
require.Equal(t, "/albums/al-1", one.Link) require.Equal(t, "/albums/al-1", one.Link)
// Several open Home, whose Recently added row starts with them; the // Several open Home, whose Recently added row starts with them; the
@@ -42,8 +42,8 @@ func TestRender_NewMusicOpensWhatArrived(t *testing.T) {
} }
func TestRender_FlagCarriesTheReasonWhenThereIsOne(t *testing.T) { func TestRender_FlagCarriesTheReasonWhenThereIsOne(t *testing.T) {
require.Equal(t, "Ann flagged WWW.", render(KindQuarantineFlagged, Payload{Name: "WWW", Actor: "Ann"}).Body) require.Equal(t, "Ann flagged XYZ.", render(KindQuarantineFlagged, Payload{Name: "XYZ", Actor: "Ann"}).Body)
require.Equal(t, "Ann flagged WWW: bad rip", render(KindQuarantineFlagged, Payload{Name: "WWW", Actor: "Ann", Reason: "bad rip"}).Body) require.Equal(t, "Ann flagged XYZ: bad rip", render(KindQuarantineFlagged, Payload{Name: "XYZ", Actor: "Ann", Reason: "bad rip"}).Body)
} }
func TestRender_CoalescedCountsReadNaturally(t *testing.T) { func TestRender_CoalescedCountsReadNaturally(t *testing.T) {
@@ -56,8 +56,8 @@ func TestRender_CoalescedCountsReadNaturally(t *testing.T) {
// A notice says which, not only how many. // A notice says which, not only how many.
func TestRender_NamesWhatChanged(t *testing.T) { func TestRender_NamesWhatChanged(t *testing.T) {
require.Equal(t, "No longer on disk: Weezer – Buddy Holly.", require.Equal(t, "No longer on disk: Glasshouse – Lucky Penny.",
render(KindTracksMissing, Payload{Count: 1, Items: []string{"Weezer – Buddy Holly"}}).Body) render(KindTracksMissing, Payload{Count: 1, Items: []string{"Glasshouse – Lucky Penny"}}).Body)
require.Equal(t, "No longer on disk: A – 1 and B – 2.", require.Equal(t, "No longer on disk: A – 1 and B – 2.",
render(KindTracksMissing, Payload{Count: 2, Items: []string{"A – 1", "B – 2"}}).Body) render(KindTracksMissing, Payload{Count: 2, Items: []string{"A – 1", "B – 2"}}).Body)
// Three are named; the rest of the count, not only the rest of the // Three are named; the rest of the count, not only the rest of the
@@ -67,8 +67,8 @@ func TestRender_NamesWhatChanged(t *testing.T) {
require.Equal(t, "12 new duplicates to review", render(KindDuplicatesFound, Payload{Count: 12}).Title) require.Equal(t, "12 new duplicates to review", render(KindDuplicatesFound, Payload{Count: 12}).Title)
require.Equal(t, "Extra copies removed, the right one kept: A and B.", require.Equal(t, "Extra copies removed, the right one kept: A and B.",
render(KindDuplicatesResolved, Payload{Count: 2, Items: []string{"A", "B"}}).Body) render(KindDuplicatesResolved, Payload{Count: 2, Items: []string{"A", "B"}}).Body)
require.Equal(t, "Failed to play: Weezer – Buddy Holly (alice).", require.Equal(t, "Failed to play: Glasshouse – Lucky Penny (alice).",
render(KindPlaybackErrors, Payload{Count: 1, Items: []string{"Weezer – Buddy Holly (alice)"}}).Body) render(KindPlaybackErrors, Payload{Count: 1, Items: []string{"Glasshouse – Lucky Penny (alice)"}}).Body)
} }
func TestRender_RowsFromBeforeItemsReadAsTheyDid(t *testing.T) { func TestRender_RowsFromBeforeItemsReadAsTheyDid(t *testing.T) {
@@ -91,5 +91,5 @@ func TestRender_AnUnreadablePayloadStillRenders(t *testing.T) {
} }
func TestPayloadMap_DropsEmptyFields(t *testing.T) { func TestPayloadMap_DropsEmptyFields(t *testing.T) {
require.Equal(t, map[string]any{"name": "WWW", "count": float64(2)}, Payload{Name: "WWW", Count: 2}.Map()) require.Equal(t, map[string]any{"name": "XYZ", "count": float64(2)}, Payload{Name: "XYZ", Count: 2}.Map())
} }
+1 -1
View File
@@ -36,7 +36,7 @@ func TestGenerateCollage_EmptyPlaylist(t *testing.T) {
func TestGenerateCollage_OneTrack(t *testing.T) { func TestGenerateCollage_OneTrack(t *testing.T) {
pool := newPool(t) pool := newPool(t)
user := seedUser(t, pool, "alice") user := seedUser(t, pool, "alice")
tk := seedTrack(t, pool, "Roygbiv", "BoC") tk := seedTrack(t, pool, "Prismatic", "FoO")
dir := t.TempDir() dir := t.TempDir()
svc := playlists.NewService(pool, nil, dir) svc := playlists.NewService(pool, nil, dir)
+5 -5
View File
@@ -324,7 +324,7 @@ func TestDelete_MissingCoverFileTolerated(t *testing.T) {
func TestAppendTracks_Snapshot(t *testing.T) { func TestAppendTracks_Snapshot(t *testing.T) {
pool := newPool(t) pool := newPool(t)
user := seedUser(t, pool, "alice") user := seedUser(t, pool, "alice")
track := seedTrack(t, pool, "Roygbiv", "Boards of Canada") track := seedTrack(t, pool, "Prismatic", "Fields of Ontario")
svc := playlists.NewService(pool, nil, t.TempDir()) svc := playlists.NewService(pool, nil, t.TempDir())
pl, _ := svc.Create(context.Background(), user.ID, "Test", "", false) pl, _ := svc.Create(context.Background(), user.ID, "Test", "", false)
@@ -336,11 +336,11 @@ func TestAppendTracks_Snapshot(t *testing.T) {
if len(got.Tracks) != 1 { if len(got.Tracks) != 1 {
t.Fatalf("Tracks length = %d, want 1", len(got.Tracks)) t.Fatalf("Tracks length = %d, want 1", len(got.Tracks))
} }
if got.Tracks[0].Title != "Roygbiv" { if got.Tracks[0].Title != "Prismatic" {
t.Errorf("Title snapshot = %q, want Roygbiv", got.Tracks[0].Title) t.Errorf("Title snapshot = %q, want Prismatic", got.Tracks[0].Title)
} }
if got.Tracks[0].ArtistName != "Boards of Canada" { if got.Tracks[0].ArtistName != "Fields of Ontario" {
t.Errorf("ArtistName snapshot = %q, want Boards of Canada", got.Tracks[0].ArtistName) t.Errorf("ArtistName snapshot = %q, want Fields of Ontario", got.Tracks[0].ArtistName)
} }
if got.TrackCount != 1 { if got.TrackCount != 1 {
t.Errorf("rollup TrackCount = %d, want 1", got.TrackCount) t.Errorf("rollup TrackCount = %d, want 1", got.TrackCount)
@@ -31,9 +31,9 @@ func TestClient_SubmitListens_Success(t *testing.T) {
listens := []Listen{{ listens := []Listen{{
ListenedAt: 1700000000, ListenedAt: 1700000000,
Track: Track{ Track: Track{
ArtistName: "Miles Davis", ArtistName: "Marlo Davies",
TrackName: "So What", TrackName: "So Then",
ReleaseName: "Kind of Blue", ReleaseName: "Kind of Grey",
DurationMs: 545000, DurationMs: 545000,
}, },
}} }}
@@ -46,10 +46,10 @@ func TestClient_SubmitListens_Success(t *testing.T) {
if seenAuth != "Token tk" { if seenAuth != "Token tk" {
t.Errorf("auth = %q, want %q", seenAuth, "Token tk") t.Errorf("auth = %q, want %q", seenAuth, "Token tk")
} }
if !strings.Contains(seenBody, `"track_name":"So What"`) { if !strings.Contains(seenBody, `"track_name":"So Then"`) {
t.Errorf("body missing track_name: %s", seenBody) t.Errorf("body missing track_name: %s", seenBody)
} }
if !strings.Contains(seenBody, `"artist_name":"Miles Davis"`) { if !strings.Contains(seenBody, `"artist_name":"Marlo Davies"`) {
t.Errorf("body missing artist_name: %s", seenBody) t.Errorf("body missing artist_name: %s", seenBody)
} }
} }
+5 -5
View File
@@ -40,12 +40,12 @@ func TestParseUUIDInvalid(t *testing.T) {
func TestIndexLetter(t *testing.T) { func TestIndexLetter(t *testing.T) {
cases := map[string]string{ cases := map[string]string{
"Radiohead": "R", "Signal Tower": "S",
"the beatles": "T", "the lanterns": "T",
" massive": "M", " marble": "M",
"4 Non Blondes": "#", "4 Cent Wonders": "#",
"": "?", "": "?",
"*NSYNC": "?", "*SYNCH": "?",
"Éowyn": "?", "Éowyn": "?",
} }
for in, want := range cases { for in, want := range cases {
+1 -1
View File
@@ -61,7 +61,7 @@ func TestLastfmFetch_ParsesTags(t *testing.T) {
defer func() { lastfmBaseURL = old }() defer func() { lastfmBaseURL = old }()
tags, err := newLastfmProvider(true, "k").FetchTrackTags(context.Background(), tags, err := newLastfmProvider(true, "k").FetchTrackTags(context.Background(),
TrackRef{ArtistName: "Slowdive", Title: "Alison"}) TrackRef{ArtistName: "Slowglide", Title: "Annabel"})
if err != nil { if err != nil {
t.Fatalf("fetch: %v", err) t.Fatalf("fetch: %v", err)
} }
+6 -6
View File
@@ -29,9 +29,9 @@ beforeEach(() => {
const baseQuarantineRow: AdminQuarantineRow = { const baseQuarantineRow: AdminQuarantineRow = {
track_id: 't1', track_id: 't1',
track_title: 'Avril 14th', track_title: 'Juin 21st',
artist_name: 'Aphex Twin', artist_name: 'Apex Sibling',
album_title: 'Drukqs', album_title: 'Drumkits',
album_id: 'alb1', album_id: 'alb1',
report_count: 1, report_count: 1,
latest_at: '2026-01-01T00:00:00Z', latest_at: '2026-01-01T00:00:00Z',
@@ -47,9 +47,9 @@ const baseAction: ActionResult = {
const baseActionRow: QuarantineActionRow = { const baseActionRow: QuarantineActionRow = {
id: 'a1', id: 'a1',
track_id: 't1', track_id: 't1',
track_title: 'Avril 14th', track_title: 'Juin 21st',
artist_name: 'Aphex Twin', artist_name: 'Apex Sibling',
album_title: 'Drukqs', album_title: 'Drumkits',
action: 'resolved', action: 'resolved',
admin_id: 'admin1', admin_id: 'admin1',
affected_users: 1, affected_users: 1,
+3 -3
View File
@@ -31,13 +31,13 @@ const mockMineRow: QuarantineMineRow = {
reason: 'bad_rip', reason: 'bad_rip',
notes: null, notes: null,
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
track_title: 'Avril 14th', track_title: 'Juin 21st',
track_duration_ms: 120000, track_duration_ms: 120000,
album_id: 'alb1', album_id: 'alb1',
album_title: 'Drukqs', album_title: 'Drumkits',
album_cover_art_path: null, album_cover_art_path: null,
artist_id: 'art1', artist_id: 'art1',
artist_name: 'Aphex Twin' artist_name: 'Apex Sibling'
}; };
beforeEach(() => { beforeEach(() => {
+4 -4
View File
@@ -150,9 +150,9 @@ describe("AcoustIDCard", () => {
vi.mocked(listUnsettledAcoustID).mockResolvedValue([ vi.mocked(listUnsettledAcoustID).mockResolvedValue([
{ {
track_id: "t1", track_id: "t1",
title: "WWW", title: "XYZ",
artist: "Moe Shop", artist: "Mochi Shop",
album: "WWW", album: "XYZ",
file_path: "/music/a.mp3", file_path: "/music/a.mp3",
state: "ambiguous", state: "ambiguous",
best_score: 0.97, best_score: 0.97,
@@ -168,7 +168,7 @@ describe("AcoustIDCard", () => {
details.open = true; details.open = true;
await fireEvent(details, new Event("toggle")); await fireEvent(details, new Event("toggle"));
const list = await screen.findByTestId("acoustid-unsettled"); const list = await screen.findByTestId("acoustid-unsettled");
expect(list.textContent).toMatch(/WWW/); expect(list.textContent).toMatch(/XYZ/);
expect(list.textContent).toMatch(/2 recordings/); expect(list.textContent).toMatch(/2 recordings/);
}); });
+14 -14
View File
@@ -39,10 +39,10 @@ import { enqueueTracks, playQueue } from '#lib/player/store.svelte.js';
const album: AlbumRef = { const album: AlbumRef = {
id: 'xyz', id: 'xyz',
title: 'Kind of Blue', title: 'Kind of Grey',
sort_title: 'Kind of Blue', sort_title: 'Kind of Grey',
artist_id: 'm-davis', artist_id: 'm-davies',
artist_name: 'Miles Davis', artist_name: 'Marlo Davies',
year: 1959, year: 1959,
track_count: 5, track_count: 5,
duration_sec: 2630, duration_sec: 2630,
@@ -57,8 +57,8 @@ describe('AlbumCard', () => {
const { container } = render(AlbumCard, { props: { album } }); const { container } = render(AlbumCard, { props: { album } });
const link = screen.getByRole('link'); const link = screen.getByRole('link');
expect(link).toHaveAttribute('href', '/albums/xyz'); expect(link).toHaveAttribute('href', '/albums/xyz');
expect(link).toHaveTextContent('Kind of Blue'); expect(link).toHaveTextContent('Kind of Grey');
expect(link).toHaveTextContent('Miles Davis'); expect(link).toHaveTextContent('Marlo Davies');
// The year is intentionally omitted from the Home tile — // The year is intentionally omitted from the Home tile —
// dropped in the visual polish pass; the album detail page // dropped in the visual polish pass; the album detail page
// still shows it. // still shows it.
@@ -85,9 +85,9 @@ describe('AlbumCard', () => {
test('+ queue button fetches album detail and calls enqueueTracks', async () => { test('+ queue button fetches album detail and calls enqueueTracks', async () => {
const tracks: TrackRef[] = [ const tracks: TrackRef[] = [
makeTrack({ makeTrack({
title: 'So What', title: 'So Then',
album_id: 'xyz', album_title: 'Kind of Blue', album_id: 'xyz', album_title: 'Kind of Grey',
artist_id: 'm-davis', artist_name: 'Miles Davis', artist_id: 'm-davies', artist_name: 'Marlo Davies',
duration_sec: 545 duration_sec: 545
}) })
]; ];
@@ -106,9 +106,9 @@ describe('AlbumCard', () => {
test('play overlay click fetches album detail and calls playQueue at index 0', async () => { test('play overlay click fetches album detail and calls playQueue at index 0', async () => {
const tracks: TrackRef[] = [ const tracks: TrackRef[] = [
makeTrack({ makeTrack({
title: 'So What', title: 'So Then',
album_id: 'xyz', album_title: 'Kind of Blue', album_id: 'xyz', album_title: 'Kind of Grey',
artist_id: 'm-davis', artist_name: 'Miles Davis', artist_id: 'm-davies', artist_name: 'Marlo Davies',
duration_sec: 545 duration_sec: 545
}) })
]; ];
@@ -116,7 +116,7 @@ describe('AlbumCard', () => {
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce(detail); (api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce(detail);
render(AlbumCard, { props: { album } }); render(AlbumCard, { props: { album } });
await fireEvent.click(screen.getByRole('button', { name: /play kind of blue/i })); await fireEvent.click(screen.getByRole('button', { name: /play kind of grey/i }));
expect(api.get).toHaveBeenCalledWith('/api/albums/xyz'); expect(api.get).toHaveBeenCalledWith('/api/albums/xyz');
await Promise.resolve(); await Promise.resolve();
await Promise.resolve(); await Promise.resolve();
@@ -125,6 +125,6 @@ describe('AlbumCard', () => {
test('renders the bottom-right kebab menu trigger', () => { test('renders the bottom-right kebab menu trigger', () => {
render(AlbumCard, { props: { album } }); render(AlbumCard, { props: { album } });
expect(screen.getByRole('button', { name: /Album actions for Kind of Blue/i })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /Album actions for Kind of Grey/i })).toBeInTheDocument();
}); });
}); });
+8 -8
View File
@@ -20,8 +20,8 @@ import { playQueue } from '#lib/player/store.svelte.js';
const artist: ArtistRef = { const artist: ArtistRef = {
id: 'art-1', id: 'art-1',
name: 'Boards of Canada', name: 'Fields of Ontario',
sort_name: 'Boards of Canada', sort_name: 'Fields of Ontario',
album_count: 5, album_count: 5,
cover_url: '/api/albums/cov-1/cover' cover_url: '/api/albums/cov-1/cover'
}; };
@@ -48,13 +48,13 @@ describe('ArtistCard', () => {
test('play overlay fetches tracks, shuffles, calls playQueue', async () => { test('play overlay fetches tracks, shuffles, calls playQueue', async () => {
const tracks: TrackRef[] = makeTracks(2, { const tracks: TrackRef[] = makeTracks(2, {
album_id: 'al-1', album_title: 'X', album_id: 'al-1', album_title: 'X',
artist_id: 'art-1', artist_name: 'BoC', artist_id: 'art-1', artist_name: 'FoO',
duration_sec: 1 duration_sec: 1
}); });
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce(tracks); (api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce(tracks);
render(ArtistCard, { props: { artist } }); render(ArtistCard, { props: { artist } });
await fireEvent.click(screen.getByRole('button', { name: /play boards of canada/i })); await fireEvent.click(screen.getByRole('button', { name: /play fields of ontario/i }));
expect(api.get).toHaveBeenCalledWith('/api/artists/art-1/tracks'); expect(api.get).toHaveBeenCalledWith('/api/artists/art-1/tracks');
await Promise.resolve(); await Promise.resolve();
await Promise.resolve(); await Promise.resolve();
@@ -70,22 +70,22 @@ describe('ArtistCard', () => {
// Like button (LikeButton's aria-label is dynamic Like|Unlike). // Like button (LikeButton's aria-label is dynamic Like|Unlike).
expect(screen.getByRole('button', { name: /^(Like|Unlike)$/ })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /^(Like|Unlike)$/ })).toBeInTheDocument();
// Add-to-queue button. // Add-to-queue button.
expect(screen.getByRole('button', { name: /Add Boards of Canada to queue/i })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /Add Fields of Ontario to queue/i })).toBeInTheDocument();
}); });
test('renders the bottom-right kebab', () => { test('renders the bottom-right kebab', () => {
render(ArtistCard, { props: { artist } }); render(ArtistCard, { props: { artist } });
expect(screen.getByRole('button', { name: /Artist actions for Boards of Canada/i })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /Artist actions for Fields of Ontario/i })).toBeInTheDocument();
}); });
test('+queue button calls listArtistTracks then enqueueTracks', async () => { test('+queue button calls listArtistTracks then enqueueTracks', async () => {
const fakeTracks = [ const fakeTracks = [
makeTrack({ artist_id: 'art-1', artist_name: 'BoC' }) makeTrack({ artist_id: 'art-1', artist_name: 'FoO' })
]; ];
const { listArtistTracks } = await import('#lib/api/artists.js'); const { listArtistTracks } = await import('#lib/api/artists.js');
(listArtistTracks as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce(fakeTracks); (listArtistTracks as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce(fakeTracks);
render(ArtistCard, { props: { artist } }); render(ArtistCard, { props: { artist } });
const btn = screen.getByRole('button', { name: /Add Boards of Canada to queue/i }); const btn = screen.getByRole('button', { name: /Add Fields of Ontario to queue/i });
await fireEvent.click(btn); await fireEvent.click(btn);
// Allow promise microtask to flush. // Allow promise microtask to flush.
await new Promise((r) => setTimeout(r, 0)); await new Promise((r) => setTimeout(r, 0));
@@ -39,7 +39,7 @@ function item(over: Partial<NotificationItem> = {}): NotificationItem {
id: 'n1', id: 'n1',
kind: 'new_music', kind: 'new_music',
title: 'New album', title: 'New album',
body: 'Boards of Canada – Geogaddi is in the library.', body: 'Fields of Ontario – Geomantic is in the library.',
link: '/albums/al-1', link: '/albums/al-1',
created_at: new Date().toISOString(), created_at: new Date().toISOString(),
read_at: null, read_at: null,
@@ -95,7 +95,7 @@ describe('NotificationBell', () => {
test('lists each kind with the server-rendered title and body, unread marked', async () => { test('lists each kind with the server-rendered title and body, unread marked', async () => {
setInbox([ setInbox([
item({ id: 'a', kind: 'new_music', title: 'New album', body: 'Geogaddi is in the library.' }), item({ id: 'a', kind: 'new_music', title: 'New album', body: 'Geomantic is in the library.' }),
item({ item({
id: 'b', id: 'b',
kind: 'tracks_missing', kind: 'tracks_missing',
@@ -111,7 +111,7 @@ describe('NotificationBell', () => {
const rows = screen.getAllByTestId('notification-item'); const rows = screen.getAllByTestId('notification-item');
expect(rows).toHaveLength(2); expect(rows).toHaveLength(2);
expect(rows[0]).toHaveTextContent('New album'); expect(rows[0]).toHaveTextContent('New album');
expect(rows[0]).toHaveTextContent('Geogaddi is in the library.'); expect(rows[0]).toHaveTextContent('Geomantic is in the library.');
expect(rows[0]).toHaveAttribute('data-unread', 'true'); expect(rows[0]).toHaveAttribute('data-unread', 'true');
expect(rows[1]).toHaveTextContent('4 tracks went missing'); expect(rows[1]).toHaveTextContent('4 tracks went missing');
expect(rows[1]).not.toHaveAttribute('data-unread'); expect(rows[1]).not.toHaveAttribute('data-unread');
+5 -5
View File
@@ -59,9 +59,9 @@ import {
function track(): TrackRef { function track(): TrackRef {
return makeTrack({ return makeTrack({
title: 'So What', title: 'So Then',
album_id: 'xyz', album_title: 'Kind of Blue', album_id: 'xyz', album_title: 'Kind of Grey',
artist_id: 'md', artist_name: 'Miles Davis', artist_id: 'md', artist_name: 'Marlo Davies',
duration_sec: 545 duration_sec: 545
}); });
} }
@@ -94,10 +94,10 @@ afterEach(() => vi.clearAllMocks());
describe('PlayerBar', () => { describe('PlayerBar', () => {
test('renders title, artist, and cover linked to /now-playing', () => { test('renders title, artist, and cover linked to /now-playing', () => {
render(PlayerBar); render(PlayerBar);
expect(compact().getByText('So What')).toBeInTheDocument(); expect(compact().getByText('So Then')).toBeInTheDocument();
// The artist label sits under the title in compact (no link wrapper); // The artist label sits under the title in compact (no link wrapper);
// look for it as plain text. // look for it as plain text.
expect(compact().getByText('Miles Davis')).toBeInTheDocument(); expect(compact().getByText('Marlo Davies')).toBeInTheDocument();
// Cover + title area links to /now-playing (Spotify/YouTube Music // Cover + title area links to /now-playing (Spotify/YouTube Music
// pattern). Album reachable via the album-name link inside NowPlaying. // pattern). Album reachable via the album-name link inside NowPlaying.
const cover = compact().getByRole('link', { name: /open now playing/i }); const cover = compact().getByRole('link', { name: /open now playing/i });
+11 -11
View File
@@ -36,9 +36,9 @@ const live: PlaylistTrack = {
track_id: 't-1', track_id: 't-1',
album_id: 'a-1', album_id: 'a-1',
artist_id: 'ar-1', artist_id: 'ar-1',
title: 'Roygbiv', title: 'Prismatic',
artist_name: 'Boards of Canada', artist_name: 'Fields of Ontario',
album_title: 'MHTRTC', album_title: 'MHTRTW',
duration_sec: 137, duration_sec: 137,
stream_url: '/api/tracks/t-1/stream', stream_url: '/api/tracks/t-1/stream',
added_at: '', added_at: '',
@@ -69,7 +69,7 @@ describe('PlaylistTrackRow', () => {
render(PlaylistTrackRow, { render(PlaylistTrackRow, {
props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() } props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() }
}); });
expect(screen.getByText('Roygbiv')).toBeInTheDocument(); expect(screen.getByText('Prismatic')).toBeInTheDocument();
expect(screen.getByText('2:17')).toBeInTheDocument(); expect(screen.getByText('2:17')).toBeInTheDocument();
}); });
@@ -79,7 +79,7 @@ describe('PlaylistTrackRow', () => {
}); });
expect(screen.getByLabelText(/reorder track/i)).toBeInTheDocument(); expect(screen.getByLabelText(/reorder track/i)).toBeInTheDocument();
expect( expect(
screen.getByLabelText(/Remove Roygbiv from playlist/i) screen.getByLabelText(/Remove Prismatic from playlist/i)
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
@@ -89,7 +89,7 @@ describe('PlaylistTrackRow', () => {
}); });
expect(screen.queryByLabelText(/reorder track/i)).not.toBeInTheDocument(); expect(screen.queryByLabelText(/reorder track/i)).not.toBeInTheDocument();
expect( expect(
screen.queryByLabelText(/Remove Roygbiv from playlist/i) screen.queryByLabelText(/Remove Prismatic from playlist/i)
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
}); });
@@ -117,7 +117,7 @@ describe('PlaylistTrackRow', () => {
render(PlaylistTrackRow, { render(PlaylistTrackRow, {
props: { row: removed, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() } props: { row: removed, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() }
}); });
const titleEl = screen.getByText('Roygbiv'); const titleEl = screen.getByText('Prismatic');
expect(titleEl.className).toContain('line-through'); expect(titleEl.className).toContain('line-through');
}); });
@@ -126,7 +126,7 @@ describe('PlaylistTrackRow', () => {
render(PlaylistTrackRow, { render(PlaylistTrackRow, {
props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay } props: { row: live, isOwner: true, onRemove: vi.fn(), onPlay }
}); });
await fireEvent.click(screen.getByText('Roygbiv')); await fireEvent.click(screen.getByText('Prismatic'));
expect(onPlay).toHaveBeenCalledWith(2); expect(onPlay).toHaveBeenCalledWith(2);
}); });
@@ -137,7 +137,7 @@ describe('PlaylistTrackRow', () => {
props: { row: missingFile, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() } props: { row: missingFile, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() }
}); });
expect(screen.getByText(/file missing/i)).toBeTruthy(); expect(screen.getByText(/file missing/i)).toBeTruthy();
expect(screen.getByText('Roygbiv').className).not.toContain('line-through'); expect(screen.getByText('Prismatic').className).not.toContain('line-through');
}); });
test('clicking a missing-file row does not play it', async () => { test('clicking a missing-file row does not play it', async () => {
@@ -145,7 +145,7 @@ describe('PlaylistTrackRow', () => {
render(PlaylistTrackRow, { render(PlaylistTrackRow, {
props: { row: missingFile, isOwner: true, onRemove: vi.fn(), onPlay } props: { row: missingFile, isOwner: true, onRemove: vi.fn(), onPlay }
}); });
await fireEvent.click(screen.getByText('Roygbiv')); await fireEvent.click(screen.getByText('Prismatic'));
expect(onPlay).not.toHaveBeenCalled(); expect(onPlay).not.toHaveBeenCalled();
}); });
@@ -154,6 +154,6 @@ describe('PlaylistTrackRow', () => {
render(PlaylistTrackRow, { render(PlaylistTrackRow, {
props: { row: missingFile, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() } props: { row: missingFile, isOwner: true, onRemove: vi.fn(), onPlay: vi.fn() }
}); });
expect(screen.getByLabelText(/remove roygbiv from playlist/i)).toBeTruthy(); expect(screen.getByLabelText(/remove prismatic from playlist/i)).toBeTruthy();
}); });
}); });
+12 -12
View File
@@ -21,15 +21,15 @@ vi.mock('#lib/api/quarantine.js', () => emptyQuarantineMock());
import TrackListRow from './TrackListRow.svelte'; import TrackListRow from './TrackListRow.svelte';
import { enqueueTrack, playRadio } from '#lib/player/store.svelte.js'; import { enqueueTrack, playRadio } from '#lib/player/store.svelte.js';
const track = makeTrack({ id: 't1', title: 'Roygbiv', duration_sec: 137 }); const track = makeTrack({ id: 't1', title: 'Prismatic', duration_sec: 137 });
function base(overrides: Record<string, unknown> = {}) { function base(overrides: Record<string, unknown> = {}) {
return { return {
title: 'Roygbiv', title: 'Prismatic',
subtitle: 'Boards of Canada · MHTRTC', subtitle: 'Fields of Ontario · MHTRTW',
durationSec: 137, durationSec: 137,
track, track,
ariaLabel: 'Roygbiv', ariaLabel: 'Prismatic',
onActivate: vi.fn(), onActivate: vi.fn(),
...overrides ...overrides
}; };
@@ -43,19 +43,19 @@ afterEach(() => {
describe('TrackListRow', () => { describe('TrackListRow', () => {
test('draws title, subtitle and duration', () => { test('draws title, subtitle and duration', () => {
render(TrackListRow, { props: base() }); render(TrackListRow, { props: base() });
expect(screen.getByText('Roygbiv')).toBeInTheDocument(); expect(screen.getByText('Prismatic')).toBeInTheDocument();
expect(screen.getByText('Boards of Canada · MHTRTC')).toBeInTheDocument(); expect(screen.getByText('Fields of Ontario · MHTRTW')).toBeInTheDocument();
expect(screen.getByText('2:17')).toBeInTheDocument(); expect(screen.getByText('2:17')).toBeInTheDocument();
}); });
test('a plain row is striped; the now-playing row is banded instead', () => { test('a plain row is striped; the now-playing row is banded instead', () => {
const { unmount } = render(TrackListRow, { props: base() }); const { unmount } = render(TrackListRow, { props: base() });
expect(screen.getByRole('button', { name: 'Roygbiv' }).className).toContain('odd:bg-surface/50'); expect(screen.getByRole('button', { name: 'Prismatic' }).className).toContain('odd:bg-surface/50');
unmount(); unmount();
player.current = { id: 't1' }; player.current = { id: 't1' };
render(TrackListRow, { props: base() }); render(TrackListRow, { props: base() });
const row = screen.getByRole('button', { name: 'Roygbiv' }); const row = screen.getByRole('button', { name: 'Prismatic' });
expect(row.className).toContain('border-l-accent'); expect(row.className).toContain('border-l-accent');
expect(row.className).not.toContain('odd:bg-surface/50'); expect(row.className).not.toContain('odd:bg-surface/50');
}); });
@@ -63,7 +63,7 @@ describe('TrackListRow', () => {
test('click and Enter activate the row', async () => { test('click and Enter activate the row', async () => {
const props = base(); const props = base();
render(TrackListRow, { props }); render(TrackListRow, { props });
const row = screen.getByRole('button', { name: 'Roygbiv' }); const row = screen.getByRole('button', { name: 'Prismatic' });
await fireEvent.click(row); await fireEvent.click(row);
await fireEvent.keyDown(row, { key: 'Enter' }); await fireEvent.keyDown(row, { key: 'Enter' });
expect(props.onActivate).toHaveBeenCalledTimes(2); expect(props.onActivate).toHaveBeenCalledTimes(2);
@@ -74,7 +74,7 @@ describe('TrackListRow', () => {
test('Enter on an inner control does not activate the row', async () => { test('Enter on an inner control does not activate the row', async () => {
const props = base(); const props = base();
render(TrackListRow, { props }); render(TrackListRow, { props });
await fireEvent.keyDown(screen.getByRole('button', { name: /add roygbiv to queue/i }), { key: 'Enter' }); await fireEvent.keyDown(screen.getByRole('button', { name: /add prismatic to queue/i }), { key: 'Enter' });
expect(props.onActivate).not.toHaveBeenCalled(); expect(props.onActivate).not.toHaveBeenCalled();
}); });
@@ -82,7 +82,7 @@ describe('TrackListRow', () => {
const props = base(); const props = base();
render(TrackListRow, { props }); render(TrackListRow, { props });
await fireEvent.click(screen.getByRole('button', { name: /play radio/i })); await fireEvent.click(screen.getByRole('button', { name: /play radio/i }));
await fireEvent.click(screen.getByRole('button', { name: /add roygbiv to queue/i })); await fireEvent.click(screen.getByRole('button', { name: /add prismatic to queue/i }));
expect(playRadio).toHaveBeenCalledWith('t1'); expect(playRadio).toHaveBeenCalledWith('t1');
expect(enqueueTrack).toHaveBeenCalledWith(track); expect(enqueueTrack).toHaveBeenCalledWith(track);
expect(props.onActivate).not.toHaveBeenCalled(); expect(props.onActivate).not.toHaveBeenCalled();
@@ -98,7 +98,7 @@ describe('TrackListRow', () => {
test('a disabled row does not activate', async () => { test('a disabled row does not activate', async () => {
const props = base({ disabled: true }); const props = base({ disabled: true });
render(TrackListRow, { props }); render(TrackListRow, { props });
await fireEvent.click(screen.getByRole('button', { name: 'Roygbiv' })); await fireEvent.click(screen.getByRole('button', { name: 'Prismatic' }));
expect(props.onActivate).not.toHaveBeenCalled(); expect(props.onActivate).not.toHaveBeenCalled();
}); });
}); });
+2 -2
View File
@@ -36,7 +36,7 @@ vi.mock('#lib/player/store.svelte.js', () => ({
import TrackMenu from './TrackMenu.svelte'; import TrackMenu from './TrackMenu.svelte';
import { playNext, enqueueTrack, playRadio } from '#lib/player/store.svelte.js'; import { playNext, enqueueTrack, playRadio } from '#lib/player/store.svelte.js';
const track = makeTrack({ title: 'Roygbiv' }); const track = makeTrack({ title: 'Prismatic' });
afterEach(() => { afterEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
@@ -46,7 +46,7 @@ afterEach(() => {
describe('TrackMenu', () => { describe('TrackMenu', () => {
test('kebab toggles aria-expanded', async () => { test('kebab toggles aria-expanded', async () => {
render(TrackMenu, { props: { track } }); render(TrackMenu, { props: { track } });
const kebab = screen.getByRole('button', { name: /track actions for roygbiv/i }); const kebab = screen.getByRole('button', { name: /track actions for prismatic/i });
expect(kebab.getAttribute('aria-expanded')).toBe('false'); expect(kebab.getAttribute('aria-expanded')).toBe('false');
await fireEvent.click(kebab); await fireEvent.click(kebab);
expect(kebab.getAttribute('aria-expanded')).toBe('true'); expect(kebab.getAttribute('aria-expanded')).toBe('true');
+13 -13
View File
@@ -21,8 +21,8 @@ import { playQueue, enqueueTrack, playRadio } from '#lib/player/store.svelte.js'
import { selection, clearSelection } from '#lib/selection/store.svelte.js'; import { selection, clearSelection } from '#lib/selection/store.svelte.js';
const tracks: TrackRef[] = [ const tracks: TrackRef[] = [
makeTrack({ title: 'So What', duration_sec: 545 }), makeTrack({ title: 'So Then', duration_sec: 545 }),
makeTrack({ id: 't2', title: 'Freddie Freeloader', track_number: 2, duration_sec: 565, stream_url: '/api/tracks/t2/stream' }) makeTrack({ id: 't2', title: 'Freddie Freewheeler', track_number: 2, duration_sec: 565, stream_url: '/api/tracks/t2/stream' })
]; ];
beforeEach(() => clearSelection()); beforeEach(() => clearSelection());
@@ -32,7 +32,7 @@ describe('TrackRow', () => {
test('renders track number, title, formatted duration', () => { test('renders track number, title, formatted duration', () => {
render(TrackRow, { props: { tracks, index: 0 } }); render(TrackRow, { props: { tracks, index: 0 } });
expect(screen.getByText('1')).toBeInTheDocument(); expect(screen.getByText('1')).toBeInTheDocument();
expect(screen.getByText('So What')).toBeInTheDocument(); expect(screen.getByText('So Then')).toBeInTheDocument();
expect(screen.getByText('9:05')).toBeInTheDocument(); expect(screen.getByText('9:05')).toBeInTheDocument();
}); });
@@ -44,26 +44,26 @@ describe('TrackRow', () => {
test('clicking the row calls playQueue(tracks, index)', async () => { test('clicking the row calls playQueue(tracks, index)', async () => {
render(TrackRow, { props: { tracks, index: 1 } }); render(TrackRow, { props: { tracks, index: 1 } });
await fireEvent.click(screen.getByRole('button', { name: 'Freddie Freeloader' })); await fireEvent.click(screen.getByRole('button', { name: 'Freddie Freewheeler' }));
expect(playQueue).toHaveBeenCalledWith(tracks, 1); expect(playQueue).toHaveBeenCalledWith(tracks, 1);
}); });
test('Enter on the row activates play', async () => { test('Enter on the row activates play', async () => {
render(TrackRow, { props: { tracks, index: 0 } }); render(TrackRow, { props: { tracks, index: 0 } });
await fireEvent.keyDown(screen.getByRole('button', { name: 'So What' }), { key: 'Enter' }); await fireEvent.keyDown(screen.getByRole('button', { name: 'So Then' }), { key: 'Enter' });
expect(playQueue).toHaveBeenCalledWith(tracks, 0); expect(playQueue).toHaveBeenCalledWith(tracks, 0);
}); });
test('Space on the row activates play', async () => { test('Space on the row activates play', async () => {
render(TrackRow, { props: { tracks, index: 0 } }); render(TrackRow, { props: { tracks, index: 0 } });
await fireEvent.keyDown(screen.getByRole('button', { name: 'So What' }), { key: ' ' }); await fireEvent.keyDown(screen.getByRole('button', { name: 'So Then' }), { key: ' ' });
expect(playQueue).toHaveBeenCalledWith(tracks, 0); expect(playQueue).toHaveBeenCalledWith(tracks, 0);
}); });
test('onPlay prop overrides default playQueue', async () => { test('onPlay prop overrides default playQueue', async () => {
const onPlay = vi.fn(); const onPlay = vi.fn();
render(TrackRow, { props: { tracks, index: 1, onPlay } }); render(TrackRow, { props: { tracks, index: 1, onPlay } });
await fireEvent.click(screen.getByRole('button', { name: 'Freddie Freeloader' })); await fireEvent.click(screen.getByRole('button', { name: 'Freddie Freewheeler' }));
expect(onPlay).toHaveBeenCalledWith(tracks, 1); expect(onPlay).toHaveBeenCalledWith(tracks, 1);
expect(playQueue).not.toHaveBeenCalled(); expect(playQueue).not.toHaveBeenCalled();
}); });
@@ -93,7 +93,7 @@ describe('TrackRow', () => {
test('a missing file is marked, does not play, and offers no actions', async () => { test('a missing file is marked, does not play, and offers no actions', async () => {
const withMissing = [{ ...tracks[0], unavailable: true }, tracks[1]]; const withMissing = [{ ...tracks[0], unavailable: true }, tracks[1]];
render(TrackRow, { props: { tracks: withMissing, index: 0 } }); render(TrackRow, { props: { tracks: withMissing, index: 0 } });
const row = screen.getByRole('button', { name: 'So What' }); const row = screen.getByRole('button', { name: 'So Then' });
expect(row).toHaveAttribute('aria-disabled', 'true'); expect(row).toHaveAttribute('aria-disabled', 'true');
expect(screen.getByText(/file missing/i)).toBeInTheDocument(); expect(screen.getByText(/file missing/i)).toBeInTheDocument();
await fireEvent.click(row); await fireEvent.click(row);
@@ -106,7 +106,7 @@ describe('TrackRow', () => {
describe('selection mode', () => { describe('selection mode', () => {
test('clicking the checkbox toggles selection without playing', async () => { test('clicking the checkbox toggles selection without playing', async () => {
render(TrackRow, { props: { tracks, index: 0 } }); render(TrackRow, { props: { tracks, index: 0 } });
const box = screen.getByRole('checkbox', { name: /select so what/i }); const box = screen.getByRole('checkbox', { name: /select so then/i });
await fireEvent.click(box); await fireEvent.click(box);
expect(selection.isSelected('t1')).toBe(true); expect(selection.isSelected('t1')).toBe(true);
expect(playQueue).not.toHaveBeenCalled(); expect(playQueue).not.toHaveBeenCalled();
@@ -114,12 +114,12 @@ describe('TrackRow', () => {
test('row click toggles selection (not play) once any row is selected', async () => { test('row click toggles selection (not play) once any row is selected', async () => {
render(TrackRow, { props: { tracks, index: 0 } }); render(TrackRow, { props: { tracks, index: 0 } });
const box = screen.getByRole('checkbox', { name: /select so what/i }); const box = screen.getByRole('checkbox', { name: /select so then/i });
await fireEvent.click(box); await fireEvent.click(box);
// Re-render at index 1 — selection mode is now active globally. // Re-render at index 1 — selection mode is now active globally.
const { container } = render(TrackRow, { props: { tracks, index: 1 } }); const { container } = render(TrackRow, { props: { tracks, index: 1 } });
const row = container.querySelector('[role="button"][aria-label="Freddie Freeloader"]')!; const row = container.querySelector('[role="button"][aria-label="Freddie Freewheeler"]')!;
await fireEvent.click(row); await fireEvent.click(row);
expect(selection.isSelected('t2')).toBe(true); expect(selection.isSelected('t2')).toBe(true);
expect(playQueue).not.toHaveBeenCalled(); expect(playQueue).not.toHaveBeenCalled();
@@ -127,11 +127,11 @@ describe('TrackRow', () => {
test('shift+click on the row extends the range from the anchor', async () => { test('shift+click on the row extends the range from the anchor', async () => {
render(TrackRow, { props: { tracks, index: 0 } }); render(TrackRow, { props: { tracks, index: 0 } });
const box = screen.getByRole('checkbox', { name: /select so what/i }); const box = screen.getByRole('checkbox', { name: /select so then/i });
await fireEvent.click(box); await fireEvent.click(box);
const { container } = render(TrackRow, { props: { tracks, index: 1 } }); const { container } = render(TrackRow, { props: { tracks, index: 1 } });
const row = container.querySelector('[role="button"][aria-label="Freddie Freeloader"]')!; const row = container.querySelector('[role="button"][aria-label="Freddie Freewheeler"]')!;
await fireEvent.click(row, { shiftKey: true }); await fireEvent.click(row, { shiftKey: true });
expect(selection.isSelected('t1')).toBe(true); expect(selection.isSelected('t1')).toBe(true);
expect(selection.isSelected('t2')).toBe(true); expect(selection.isSelected('t2')).toBe(true);
@@ -7,9 +7,9 @@ const row: PlaylistTrack = {
track_id: 't-1', track_id: 't-1',
album_id: 'a-1', album_id: 'a-1',
artist_id: 'ar-1', artist_id: 'ar-1',
title: 'Roygbiv', title: 'Prismatic',
artist_name: 'Boards of Canada', artist_name: 'Fields of Ontario',
album_title: 'MHTRTC', album_title: 'MHTRTW',
duration_sec: 137, duration_sec: 137,
stream_url: '/api/tracks/t-1/stream', stream_url: '/api/tracks/t-1/stream',
added_at: '', added_at: '',
@@ -20,11 +20,11 @@ describe('playlistTrackToRef', () => {
test('maps a playable row onto a TrackRef', () => { test('maps a playable row onto a TrackRef', () => {
expect(playlistTrackToRef(row)).toEqual({ expect(playlistTrackToRef(row)).toEqual({
id: 't-1', id: 't-1',
title: 'Roygbiv', title: 'Prismatic',
album_id: 'a-1', album_id: 'a-1',
album_title: 'MHTRTC', album_title: 'MHTRTW',
artist_id: 'ar-1', artist_id: 'ar-1',
artist_name: 'Boards of Canada', artist_name: 'Fields of Ontario',
duration_sec: 137, duration_sec: 137,
stream_url: '/api/tracks/t-1/stream' stream_url: '/api/tracks/t-1/stream'
}); });
+3 -3
View File
@@ -192,8 +192,8 @@ describe('admin Overview status', () => {
setupOverview(summary(), vi.fn(), status({ setupOverview(summary(), vi.fn(), status({
listening: { listening: {
now: [{ now: [{
username: 'bryan', track_id: 't1', title: 'Avril 14th', artist_name: 'Aphex Twin', album_id: 'al1', username: 'alex', track_id: 't1', title: 'Juin 21st', artist_name: 'Apex Sibling', album_id: 'al1',
album_title: 'Drukqs', duration_ms: 125_000, started_at: minutesAgo(1), client: 'android', device_class: 'phone' album_title: 'Drumkits', duration_ms: 125_000, started_at: minutesAgo(1), client: 'android', device_class: 'phone'
}], }],
plays_day: 37, listeners_day: 2, last_play_at: minutesAgo(1) plays_day: 37, listeners_day: 2, last_play_at: minutesAgo(1)
} }
@@ -201,7 +201,7 @@ describe('admin Overview status', () => {
render(OverviewPage); render(OverviewPage);
const rows = screen.getAllByTestId('listening-row'); const rows = screen.getAllByTestId('listening-row');
expect(rows).toHaveLength(1); expect(rows).toHaveLength(1);
expect(rows[0].textContent?.replace(/\s+/g, ' ')).toMatch(/bryan Avril 14th · Aphex Twin android · started 1m ago/); expect(rows[0].textContent?.replace(/\s+/g, ' ')).toMatch(/alex Juin 21st · Apex Sibling android · started 1m ago/);
expect(textOf('listening-day')).toBe('37 plays by 2 people in the last day, the latest 1m ago.'); expect(textOf('listening-day')).toBe('37 plays by 2 people in the last day, the latest 1m ago.');
}); });
+14 -14
View File
@@ -28,8 +28,8 @@ import { createAlbumQuery } from '#lib/api/queries.js';
function track(id: string, title: string, number: number, dur: number): TrackRef { function track(id: string, title: string, number: number, dur: number): TrackRef {
return makeTrack({ return makeTrack({
id, title, id, title,
album_id: 'xyz', album_title: 'Kind of Blue', album_id: 'xyz', album_title: 'Kind of Grey',
artist_id: 'md', artist_name: 'Miles Davis', artist_id: 'md', artist_name: 'Marlo Davies',
track_number: number, track_number: number,
duration_sec: dur, duration_sec: dur,
stream_url: `/api/tracks/${id}/stream` stream_url: `/api/tracks/${id}/stream`
@@ -44,28 +44,28 @@ afterEach(() => {
describe('album detail page', () => { describe('album detail page', () => {
test('renders hero metadata + one TrackRow per track', () => { test('renders hero metadata + one TrackRow per track', () => {
const detail: AlbumDetail = { const detail: AlbumDetail = {
id: 'xyz', title: 'Kind of Blue', sort_title: 'Kind of Blue', id: 'xyz', title: 'Kind of Grey', sort_title: 'Kind of Grey',
artist_id: 'md', artist_name: 'Miles Davis', artist_id: 'md', artist_name: 'Marlo Davies',
year: 1959, track_count: 2, duration_sec: 544 + 565, year: 1959, track_count: 2, duration_sec: 544 + 565,
cover_url: '/api/albums/xyz/cover', cover_url: '/api/albums/xyz/cover',
cover_art_source: null, cover_art_source: null,
tracks: [track('t1', 'So What', 1, 544), track('t2', 'Freddie Freeloader', 2, 565)], tracks: [track('t1', 'So Then', 1, 544), track('t2', 'Freddie Freewheeler', 2, 565)],
genres: ['Jazz'] genres: ['Jazz']
}; };
(createAlbumQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: detail })); (createAlbumQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: detail }));
render(AlbumPage); render(AlbumPage);
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Kind of Blue'); expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Kind of Grey');
// Two links point at /artists/md: the back chevron and the inline hero // Two links point at /artists/md: the back chevron and the inline hero
// link. getAllByRole returns both; both should target the artist page. // link. getAllByRole returns both; both should target the artist page.
const artistLinks = screen.getAllByRole('link', { name: /Miles Davis/ }); const artistLinks = screen.getAllByRole('link', { name: /Marlo Davies/ });
expect(artistLinks.length).toBeGreaterThanOrEqual(1); expect(artistLinks.length).toBeGreaterThanOrEqual(1);
artistLinks.forEach((l) => expect(l).toHaveAttribute('href', '/artists/md')); artistLinks.forEach((l) => expect(l).toHaveAttribute('href', '/artists/md'));
expect(screen.getByText(/1959/)).toBeInTheDocument(); expect(screen.getByText(/1959/)).toBeInTheDocument();
expect(screen.getByText(/2 tracks/i)).toBeInTheDocument(); expect(screen.getByText(/2 tracks/i)).toBeInTheDocument();
expect(screen.getByText('So What')).toBeInTheDocument(); expect(screen.getByText('So Then')).toBeInTheDocument();
expect(screen.getByText('Freddie Freeloader')).toBeInTheDocument(); expect(screen.getByText('Freddie Freewheeler')).toBeInTheDocument();
const img = screen.getByRole('img') as HTMLImageElement; const img = screen.getByRole('img') as HTMLImageElement;
expect(img.src).toContain('/api/albums/xyz/cover'); expect(img.src).toContain('/api/albums/xyz/cover');
@@ -74,7 +74,7 @@ describe('album detail page', () => {
test('back link points to /artists/:artistId with the artist name', () => { test('back link points to /artists/:artistId with the artist name', () => {
const detail: AlbumDetail = { const detail: AlbumDetail = {
id: 'xyz', title: 'T', sort_title: 'T', id: 'xyz', title: 'T', sort_title: 'T',
artist_id: 'md', artist_name: 'Miles Davis', artist_id: 'md', artist_name: 'Marlo Davies',
track_count: 0, duration_sec: 0, track_count: 0, duration_sec: 0,
cover_url: '/api/albums/xyz/cover', cover_url: '/api/albums/xyz/cover',
cover_art_source: null, cover_art_source: null,
@@ -85,7 +85,7 @@ describe('album detail page', () => {
render(AlbumPage); render(AlbumPage);
// Back chevron specifically (disambiguated from the inline artist link by // Back chevron specifically (disambiguated from the inline artist link by
// the leading arrow character). // the leading arrow character).
const back = screen.getByRole('link', { name: /^← Miles Davis/ }); const back = screen.getByRole('link', { name: /^← Marlo Davies/ });
expect(back).toHaveAttribute('href', '/artists/md'); expect(back).toHaveAttribute('href', '/artists/md');
}); });
@@ -126,8 +126,8 @@ describe('album detail page', () => {
// a slash-bearing tag is why browse selection lives in the query string. // a slash-bearing tag is why browse selection lives in the query string.
test('year and genre are quick-jump links into the browse axes', () => { test('year and genre are quick-jump links into the browse axes', () => {
const detail: AlbumDetail = { const detail: AlbumDetail = {
id: 'xyz', title: 'Kind of Blue', sort_title: 'Kind of Blue', id: 'xyz', title: 'Kind of Grey', sort_title: 'Kind of Grey',
artist_id: 'md', artist_name: 'Miles Davis', artist_id: 'md', artist_name: 'Marlo Davies',
year: 1959, track_count: 0, duration_sec: 0, year: 1959, track_count: 0, duration_sec: 0,
cover_url: '/api/albums/xyz/cover', cover_url: '/api/albums/xyz/cover',
cover_art_source: null, cover_art_source: null,
@@ -154,7 +154,7 @@ describe('album detail page', () => {
test('no genre chips when the album carries no genre tags', () => { test('no genre chips when the album carries no genre tags', () => {
const detail: AlbumDetail = { const detail: AlbumDetail = {
id: 'xyz', title: 'Untagged', sort_title: 'Untagged', id: 'xyz', title: 'Untagged', sort_title: 'Untagged',
artist_id: 'md', artist_name: 'Miles Davis', artist_id: 'md', artist_name: 'Marlo Davies',
track_count: 0, duration_sec: 0, track_count: 0, duration_sec: 0,
cover_url: '/api/albums/xyz/cover', cover_url: '/api/albums/xyz/cover',
cover_art_source: null, cover_art_source: null,
@@ -14,11 +14,11 @@ vi.mock('#lib/api/admin.js', () => ({
dismissDuplicateGroup: vi.fn().mockResolvedValue(undefined), dismissDuplicateGroup: vi.fn().mockResolvedValue(undefined),
mergeDuplicateGroup: vi.fn().mockResolvedValue({ mergeDuplicateGroup: vi.fn().mockResolvedValue({
survivor_track_id: 'www-01', survivor_track_id: 'www-01',
removed_paths: ['/music/Moe Shop/WWW (2020)/www-02.mp3'] removed_paths: ['/music/Mochi Shop/XYZ (2020)/www-02.mp3']
}), }),
removeWrongSlotFiles: vi.fn().mockResolvedValue({ removeWrongSlotFiles: vi.fn().mockResolvedValue({
kept_track_id: null, kept_track_id: null,
removed_paths: ['/music/Moe Shop/WWW (2020)/www-01.mp3', '/music/Moe Shop/WWW (2020)/www-02.mp3'] removed_paths: ['/music/Mochi Shop/XYZ (2020)/www-01.mp3', '/music/Mochi Shop/XYZ (2020)/www-02.mp3']
}) })
})); }));
vi.mock('#lib/player/store.svelte.js', () => ({ playQueue: vi.fn() })); vi.mock('#lib/player/store.svelte.js', () => ({ playQueue: vi.fn() }));
@@ -51,12 +51,12 @@ const allFingerprinted = { total: 1200, fingerprinted: 1200, rejected: 0, pendin
function member(id: string, extra: Partial<AdminDuplicatesResponse['groups'][number]['members'][number]> = {}) { function member(id: string, extra: Partial<AdminDuplicatesResponse['groups'][number]['members'][number]> = {}) {
return { return {
track_id: id, track_id: id,
title: 'WWW', title: 'XYZ',
artist_id: 'ar-1', artist_id: 'ar-1',
artist_name: 'Moe Shop', artist_name: 'Mochi Shop',
album_id: 'al-1', album_id: 'al-1',
album_title: 'WWW', album_title: 'XYZ',
file_path: `/music/Moe Shop/WWW (2020)/${id}.mp3`, file_path: `/music/Mochi Shop/XYZ (2020)/${id}.mp3`,
file_format: 'mp3', file_format: 'mp3',
file_size: 6_900_000, file_size: 6_900_000,
duration_sec: 215, duration_sec: 215,
@@ -199,14 +199,14 @@ describe('admin duplicates', () => {
); );
}); });
// Identical audio titled "WWW" and "WWW (instrumental)". One file // Identical audio titled "XYZ" and "XYZ (instrumental)". One file
// claimed to be the vocal and wasn't, and nothing said the vocal was missing. // claimed to be the vocal and wasn't, and nothing said the vocal was missing.
describe('identical audio under different titles', () => { describe('identical audio under different titles', () => {
function www() { function www() {
const r = response(); const r = response();
r.groups[0] = { r.groups[0] = {
...r.groups[0], ...r.groups[0],
members: [member('www-01'), member('www-02', { title: 'WWW (instrumental)' })] members: [member('www-01'), member('www-02', { title: 'XYZ (instrumental)' })]
}; };
return r; return r;
} }
@@ -214,16 +214,16 @@ describe('admin duplicates', () => {
test('says the copies are titled differently and names both titles', () => { test('says the copies are titled differently and names both titles', () => {
renderWith(www()); renderWith(www());
const notice = text(screen.getByTestId('title-mismatch')); const notice = text(screen.getByTestId('title-mismatch'));
expect(notice).toContain('titled “WWW” and “WWW (instrumental)”'); expect(notice).toContain('titled “XYZ” and “XYZ (instrumental)”');
expect(notice).toContain("isn't in your library"); expect(notice).toContain("isn't in your library");
}); });
test('three different titles are all named', () => { test('three different titles are all named', () => {
const r = www(); const r = www();
r.groups[0].members.push(member('www-03', { title: 'WWW (Radio Edit)' })); r.groups[0].members.push(member('www-03', { title: 'XYZ (Radio Edit)' }));
renderWith(r); renderWith(r);
expect(text(screen.getByTestId('title-mismatch'))).toContain( expect(text(screen.getByTestId('title-mismatch'))).toContain(
'“WWW”, “WWW (instrumental)” and “WWW (Radio Edit)”' '“XYZ”, “XYZ (instrumental)” and “XYZ (Radio Edit)”'
); );
}); });
@@ -232,7 +232,7 @@ describe('admin duplicates', () => {
r.groups[0] = { r.groups[0] = {
...r.groups[0], ...r.groups[0],
members: [ members: [
member('www-01', { title: 'WWW (Instrumental)' }), member('www-01', { title: 'XYZ (Instrumental)' }),
member('www-02', { title: ' www (instrumental) ' }) member('www-02', { title: ' www (instrumental) ' })
] ]
}; };
@@ -253,14 +253,14 @@ describe('admin duplicates', () => {
expect(screen.queryByTestId('title-mismatch')).toBeNull(); expect(screen.queryByTestId('title-mismatch')).toBeNull();
}); });
// Unless the resolver found different songs on one album: Savant's Mortals // Unless the resolver found different songs on one album: Savanta's Immortals
// held one recording as 16 tracks, each cut to its own song's length. // held one recording as 16 tracks, each cut to its own song's length.
test('an acoustic group the resolver found to be different songs says so', () => { test('an acoustic group the resolver found to be different songs says so', () => {
const r = www(); const r = www();
r.groups[0] = { ...r.groups[0], tier: 'acoustic', worst_bit_error_rate: 0, class: 'mismatch' }; r.groups[0] = { ...r.groups[0], tier: 'acoustic', worst_bit_error_rate: 0, class: 'mismatch' };
renderWith(r); renderWith(r);
const notice = text(screen.getByTestId('title-mismatch')); const notice = text(screen.getByTestId('title-mismatch'));
expect(notice).toContain('The music is the same, but the copies are titled “WWW” and “WWW (instrumental)”'); expect(notice).toContain('The music is the same, but the copies are titled “XYZ” and “XYZ (instrumental)”');
expect(notice).toContain("If you can't tell, get the album again"); expect(notice).toContain("If you can't tell, get the album again");
}); });
}); });
@@ -276,7 +276,7 @@ describe('admin duplicates', () => {
tier: 'acoustic', tier: 'acoustic',
worst_bit_error_rate: 0.04, worst_bit_error_rate: 0.04,
class: 'mismatch', class: 'mismatch',
members: [member('www-01'), member('www-02', { title: 'WWW (instrumental)' })] members: [member('www-01'), member('www-02', { title: 'XYZ (instrumental)' })]
}; };
return r; return r;
} }
@@ -303,11 +303,11 @@ describe('admin duplicates', () => {
test('naming the song keeps that copy and removes the others', async () => { test('naming the song keeps that copy and removes the others', async () => {
renderWith(slots()); renderWith(slots());
await fireEvent.click(screen.getByRole('radio', { name: /This is WWW \(instrumental\)/ })); await fireEvent.click(screen.getByRole('radio', { name: /This is XYZ \(instrumental\)/ }));
expect(screen.getByTestId('song-badge')).toBeTruthy(); expect(screen.getByTestId('song-badge')).toBeTruthy();
await fireEvent.click(screen.getByRole('button', { name: 'Keep “WWW (instrumental)”…' })); await fireEvent.click(screen.getByRole('button', { name: 'Keep “XYZ (instrumental)”…' }));
expect(text(screen.getByTestId('refetch-confirm'))).toContain( expect(text(screen.getByTestId('refetch-confirm'))).toContain(
'The copy titled “WWW (instrumental)” stays, and 1 copy under other titles will be deleted from disk' 'The copy titled “XYZ (instrumental)” stays, and 1 copy under other titles will be deleted from disk'
); );
await fireEvent.click(screen.getByRole('button', { name: 'Remove 1 file' })); await fireEvent.click(screen.getByRole('button', { name: 'Remove 1 file' }));
expect(removeWrongSlotFiles).toHaveBeenCalledWith('g-1', { keep_track_id: 'www-02' }); expect(removeWrongSlotFiles).toHaveBeenCalledWith('g-1', { keep_track_id: 'www-02' });
@@ -443,15 +443,15 @@ describe('admin duplicates', () => {
action: 'duplicate_merge', action: 'duplicate_merge',
created_at: ago(HOUR), created_at: ago(HOUR),
details: { details: {
survivor_path: '/music/Gorillaz/Humanz (2017)/03 - Saturnz Barz.mp3', survivor_path: '/music/Plastic Apes/Mammalz (2017)/03 - Neptunez Barz.mp3',
survivor_reason: 'the copy that is not a video rip', survivor_reason: 'the copy that is not a video rip',
removed: [{ track_id: 't-2', file_path: '/music/Gorillaz/Humanz (2017)/03 - Saturnz Barz (Official Video).mp3' }] removed: [{ track_id: 't-2', file_path: '/music/Plastic Apes/Mammalz (2017)/03 - Neptunez Barz (Official Video).mp3' }]
} }
} }
]); ]);
await fireEvent.click(screen.getByRole('tab', { name: /resolved automatically/i })); await fireEvent.click(screen.getByRole('tab', { name: /resolved automatically/i }));
const items = screen.getAllByTestId('resolved-item').map(text); const items = screen.getAllByTestId('resolved-item').map(text);
expect(items[0]).toContain('Kept 03 - Saturnz Barz.mp3 (the copy that is not a video rip) and removed 1 file.'); expect(items[0]).toContain('Kept 03 - Neptunez Barz.mp3 (the copy that is not a video rip) and removed 1 file.');
expect(screen.queryByTestId('duplicate-group')).toBeNull(); expect(screen.queryByTestId('duplicate-group')).toBeNull();
}); });
@@ -461,16 +461,16 @@ describe('admin duplicates', () => {
id: 'a-2', id: 'a-2',
action: 'duplicate_dismiss', action: 'duplicate_dismiss',
created_at: ago(HOUR), created_at: ago(HOUR),
details: { artist: 'Moe Shop', titles: ['Lovesick', 'Lovesick (Instrumental)'] } details: { artist: 'Mochi Shop', titles: ['Homesick', 'Homesick (Instrumental)'] }
}, },
{ {
id: 'a-3', id: 'a-3',
action: 'duplicate_wrong_file', action: 'duplicate_wrong_file',
created_at: ago(HOUR), created_at: ago(HOUR),
details: { details: {
artist: 'Savant', artist: 'Savanta',
kept_title: 'Void', kept_title: 'Void',
removed: [{ track_id: 't-9', file_path: '/data/Music/Savant/Void/17 - Reach.m4a', title: 'Reach' }] removed: [{ track_id: 't-9', file_path: '/data/Music/Savanta/Void/17 - Reach.m4a', title: 'Reach' }]
} }
}, },
{ {
@@ -478,23 +478,23 @@ describe('admin duplicates', () => {
action: 'duplicate_wrong_file', action: 'duplicate_wrong_file',
created_at: ago(HOUR), created_at: ago(HOUR),
details: { details: {
artist: 'Shnabubula', artist: 'Shnorkelbub',
removed: [ removed: [
{ track_id: 't-5', file_path: '/data/Music/Shnabubula/05 - Fading Light.mp3', title: 'Fading Light' }, { track_id: 't-5', file_path: '/data/Music/Shnorkelbub/05 - Fading Light.mp3', title: 'Fading Light' },
{ track_id: 't-10', file_path: '/data/Music/Shnabubula/10 - Looking for Answers.mp3', title: 'Looking for Answers' } { track_id: 't-10', file_path: '/data/Music/Shnorkelbub/10 - Looking for Answers.mp3', title: 'Looking for Answers' }
] ]
} }
} }
]); ]);
await fireEvent.click(screen.getByRole('tab', { name: /resolved automatically/i })); await fireEvent.click(screen.getByRole('tab', { name: /resolved automatically/i }));
const items = screen.getAllByTestId('resolved-item').map(text); const items = screen.getAllByTestId('resolved-item').map(text);
expect(items[0]).toContain('Moe Shop: Lovesick and Lovesick (Instrumental) are different versions, not duplicates. Both kept.'); expect(items[0]).toContain('Mochi Shop: Homesick and Homesick (Instrumental) are different versions, not duplicates. Both kept.');
expect(items[1]).toContain( expect(items[1]).toContain(
'Savant: the recording of Void was also filed as Reach. Removed from there; those tracks wait in Needs a file.' 'Savanta: the recording of Void was also filed as Reach. Removed from there; those tracks wait in Needs a file.'
); );
expect(items[1]).toContain('/data/Music/Savant/Void/17 - Reach.m4a'); expect(items[1]).toContain('/data/Music/Savanta/Void/17 - Reach.m4a');
expect(items[2]).toContain( expect(items[2]).toContain(
'Shnabubula: one recording was filed as Fading Light and Looking for Answers, and it is none of them. Removed; those tracks wait in Needs a file.' 'Shnorkelbub: one recording was filed as Fading Light and Looking for Answers, and it is none of them. Removed; those tracks wait in Needs a file.'
); );
}); });
}); });
@@ -22,10 +22,10 @@ function track(
track_id: `t-${title}`, track_id: `t-${title}`,
title, title,
artist_id: 'ar-1', artist_id: 'ar-1',
artist_name: 'Linkin Park', artist_name: 'Lincoln Yard',
album_id: 'al-1', album_id: 'al-1',
album_title: 'Minutes to Midnight', album_title: 'Minutes to Noon',
file_path: `/music/Linkin Park/Minutes to Midnight/${title}.flac`, file_path: `/music/Lincoln Yard/Minutes to Noon/${title}.flac`,
duration_sec: 185, duration_sec: 185,
disc_number: 1, disc_number: 1,
track_number: 1, track_number: 1,
@@ -44,7 +44,7 @@ const response: AdminMissingResponse = {
offset: 0, offset: 0,
groups: [ groups: [
{ {
directory: '/music/Linkin Park/Minutes to Midnight', directory: '/music/Lincoln Yard/Minutes to Noon',
missing_since: new Date(Date.now() - 3 * DAY).toISOString(), missing_since: new Date(Date.now() - 3 * DAY).toISOString(),
tracks: [ tracks: [
track('Given Up', { lastPlayed: new Date(Date.now() - 2 * DAY).toISOString() }), track('Given Up', { lastPlayed: new Date(Date.now() - 2 * DAY).toISOString() }),
@@ -52,7 +52,7 @@ const response: AdminMissingResponse = {
] ]
}, },
{ {
directory: '/music/Boards of Canada/Geogaddi', directory: '/music/Fields of Ontario/Geomantic',
missing_since: new Date(Date.now() - 9 * DAY).toISOString(), missing_since: new Date(Date.now() - 9 * DAY).toISOString(),
tracks: [track('1969')] tracks: [track('1969')]
} }
@@ -71,8 +71,8 @@ function renderWith(data: AdminMissingResponse | undefined, extra = {}) {
describe('/collection/missing', () => { describe('/collection/missing', () => {
test('groups rows under their directory', () => { test('groups rows under their directory', () => {
renderWith(response); renderWith(response);
expect(screen.getByText('/music/Linkin Park/Minutes to Midnight')).toBeTruthy(); expect(screen.getByText('/music/Lincoln Yard/Minutes to Noon')).toBeTruthy();
expect(screen.getByText('/music/Boards of Canada/Geogaddi')).toBeTruthy(); expect(screen.getByText('/music/Fields of Ontario/Geomantic')).toBeTruthy();
expect(screen.getAllByTestId('missing-track-row')).toHaveLength(3); expect(screen.getAllByTestId('missing-track-row')).toHaveLength(3);
}); });
@@ -160,7 +160,7 @@ describe('/collection/missing', () => {
test('Forget all takes the whole folder', async () => { test('Forget all takes the whole folder', async () => {
renderWith(response); renderWith(response);
await fireEvent.click( await fireEvent.click(
screen.getByRole('button', { name: 'Forget the 2 tracks in /music/Linkin Park/Minutes to Midnight' }) screen.getByRole('button', { name: 'Forget the 2 tracks in /music/Lincoln Yard/Minutes to Noon' })
); );
await fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: /confirm forget/i })); await fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: /confirm forget/i }));
await waitFor(() => expect(forgetMissingTracks).toHaveBeenCalledWith(['t-Given Up', 't-Bleed It Out'])); await waitFor(() => expect(forgetMissingTracks).toHaveBeenCalledWith(['t-Given Up', 't-Bleed It Out']));
@@ -29,9 +29,9 @@ const hoursAgo = (h: number) => new Date(Date.now() - h * 3_600_000).toISOString
const flagged: AdminQuarantineRow = { const flagged: AdminQuarantineRow = {
track_id: 't1', track_id: 't1',
track_title: 'Roygbiv', track_title: 'Prismatic',
artist_name: 'Boards of Canada', artist_name: 'Fields of Ontario',
album_title: 'Geogaddi', album_title: 'Geomantic',
album_id: 'al1', album_id: 'al1',
report_count: 1, report_count: 1,
latest_at: hoursAgo(5), latest_at: hoursAgo(5),
@@ -49,7 +49,7 @@ const failure = (id: string, track: string, title: string, h: number): AdminPlay
occurred_at: hoursAgo(h), occurred_at: hoursAgo(h),
track_title: title, track_title: title,
track_file_path: `/music/${title}.flac`, track_file_path: `/music/${title}.flac`,
artist_name: 'Annadale', artist_name: 'Ashdale',
album_title: 'Dial Tone', album_title: 'Dial Tone',
album_id: 'al2' album_id: 'al2'
}); });
@@ -67,7 +67,7 @@ function setup(q: AdminQuarantineRow[], e: AdminPlaybackError[], opts: { error?:
describe('/collection/reports', () => { describe('/collection/reports', () => {
test('a flagged track and a track that failed to play are one list, one row per track, newest first', () => { test('a flagged track and a track that failed to play are one list, one row per track, newest first', () => {
setup([flagged], [failure('e1', 't1', 'Roygbiv', 1), failure('e2', 't2', 'Intro', 9)]); setup([flagged], [failure('e1', 't1', 'Prismatic', 1), failure('e2', 't2', 'Intro', 9)]);
const rows = screen.getAllByTestId('report-row'); const rows = screen.getAllByTestId('report-row');
expect(rows).toHaveLength(2); expect(rows).toHaveLength(2);
expect(screen.getByTestId('reports-verdict').textContent).toMatch(/2 tracks need a look/); expect(screen.getByTestId('reports-verdict').textContent).toMatch(/2 tracks need a look/);
@@ -78,8 +78,8 @@ describe('/collection/reports', () => {
}); });
test('Resolve clears the listeners\' reports and marks the playback errors fixed', async () => { test('Resolve clears the listeners\' reports and marks the playback errors fixed', async () => {
setup([flagged], [failure('e1', 't1', 'Roygbiv', 1)]); setup([flagged], [failure('e1', 't1', 'Prismatic', 1)]);
await fireEvent.click(screen.getByRole('button', { name: /resolve roygbiv/i })); await fireEvent.click(screen.getByRole('button', { name: /resolve prismatic/i }));
await waitFor(() => expect(resolveQuarantine).toHaveBeenCalledWith('t1')); await waitFor(() => expect(resolveQuarantine).toHaveBeenCalledWith('t1'));
await waitFor(() => expect(resolvePlaybackError).toHaveBeenCalledWith('e1', 'fixed')); await waitFor(() => expect(resolvePlaybackError).toHaveBeenCalledWith('e1', 'fixed'));
}); });
@@ -110,20 +110,20 @@ describe('/collection/reports', () => {
test("on a phone the row's other actions are in its menu", async () => { test("on a phone the row's other actions are in its menu", async () => {
setup([flagged], [failure('e2', 't2', 'Intro', 2)]); setup([flagged], [failure('e2', 't2', 'Intro', 2)]);
const roygbiv = screen.getAllByTestId('report-row').find((r) => r.textContent?.includes('Roygbiv'))!; const prismatic = screen.getAllByTestId('report-row').find((r) => r.textContent?.includes('Prismatic'))!;
await fireEvent.click(within(roygbiv).getByRole('button', { name: /more actions/i })); await fireEvent.click(within(prismatic).getByRole('button', { name: /more actions/i }));
const menu = within(screen.getByRole('menu')); const menu = within(screen.getByRole('menu'));
expect(menu.getByText('Remove the file')).toBeInTheDocument(); expect(menu.getByText('Remove the file')).toBeInTheDocument();
expect(menu.getByText('Remove from library')).toBeInTheDocument(); expect(menu.getByText('Remove from library')).toBeInTheDocument();
}); });
test('details show who flagged it, who it failed for, and the file', async () => { test('details show who flagged it, who it failed for, and the file', async () => {
setup([flagged], [failure('e1', 't1', 'Roygbiv', 1)]); setup([flagged], [failure('e1', 't1', 'Prismatic', 1)]);
await fireEvent.click(screen.getByRole('button', { name: /^details$/i })); await fireEvent.click(screen.getByRole('button', { name: /^details$/i }));
const details = screen.getByTestId('report-details').textContent?.replace(/\s+/g, ' '); const details = screen.getByTestId('report-details').textContent?.replace(/\s+/g, ' ');
expect(details).toMatch(/alice flagged it · Bad rip · crackles/); expect(details).toMatch(/alice flagged it · Bad rip · crackles/);
expect(details).toMatch(/Failed to play for bob · Wouldn't load/); expect(details).toMatch(/Failed to play for bob · Wouldn't load/);
expect(details).toMatch(/\/music\/Roygbiv\.flac/); expect(details).toMatch(/\/music\/Prismatic\.flac/);
}); });
test('a load failure says so with Try again, and an empty queue says nothing waits', () => { test('a load failure says so with Try again, and an empty queue says nothing waits', () => {
@@ -91,7 +91,7 @@
} }
// Disc and track are shown because junk numbering is the other half of // Disc and track are shown because junk numbering is the other half of
// the symptom: Humanz's rips were spread over discs 1 to 15. // the symptom: Mammalz's rips were spread over discs 1 to 15.
function position(t: AdminSuspectTrack): string { function position(t: AdminSuspectTrack): string {
const parts: string[] = []; const parts: string[] = [];
if (t.disc_number != null) parts.push(`disc ${t.disc_number}`); if (t.disc_number != null) parts.push(`disc ${t.disc_number}`);
@@ -14,17 +14,17 @@ import { createSuspectSourcesQuery, removeSuspectFile, setSuspectVerdict } from
const mocked = createSuspectSourcesQuery as ReturnType<typeof vi.fn>; const mocked = createSuspectSourcesQuery as ReturnType<typeof vi.fn>;
const HUMANZ = '/music/Gorillaz/Humanz (2017)'; const MAMMALZ = '/music/Plastic Apes/Mammalz (2017)';
function track(title: string, file: string, markers: string[], disc: number | null = 15): AdminSuspectTrack { function track(title: string, file: string, markers: string[], disc: number | null = 15): AdminSuspectTrack {
return { return {
track_id: `t-${title}`, track_id: `t-${title}`,
title, title,
artist_id: 'ar-1', artist_id: 'ar-1',
artist_name: 'Gorillaz', artist_name: 'Plastic Apes',
album_id: 'al-1', album_id: 'al-1',
album_title: 'Humanz', album_title: 'Mammalz',
file_path: `${HUMANZ}/${file}`, file_path: `${MAMMALZ}/${file}`,
duration_sec: 180, duration_sec: 180,
disc_number: disc, disc_number: disc,
track_number: 4, track_number: 4,
@@ -59,10 +59,10 @@ describe('Suspect sources page', () => {
infinite([ infinite([
page(0, 2, [ page(0, 2, [
{ {
directory: HUMANZ, directory: MAMMALZ,
tracks: [ tracks: [
track('Strobelite', 'Gorillaz - Strobelite (Official Video).mp3', ['music video']), track('Strobeline', 'Plastic Apes - Strobeline (Official Video).mp3', ['music video']),
track('Andromeda', 'Gorillaz - Andromeda [Audio] [HQ].mp3', ['[Audio]', '[HD]']) track('Cassiopeia', 'Plastic Apes - Cassiopeia [Audio] [HQ].mp3', ['[Audio]', '[HD]'])
] ]
} }
]) ])
@@ -71,8 +71,8 @@ describe('Suspect sources page', () => {
render(SuspectSourcesPage); render(SuspectSourcesPage);
expect(screen.getByTestId('suspect-count-pill')).toHaveTextContent('2'); expect(screen.getByTestId('suspect-count-pill')).toHaveTextContent('2');
expect(screen.getByText(HUMANZ)).toBeInTheDocument(); expect(screen.getByText(MAMMALZ)).toBeInTheDocument();
expect(screen.getByText('Gorillaz - Strobelite (Official Video).mp3')).toBeInTheDocument(); expect(screen.getByText('Plastic Apes - Strobeline (Official Video).mp3')).toBeInTheDocument();
expect(screen.getAllByTestId('suspect-marker').map((m) => m.textContent)).toEqual([ expect(screen.getAllByTestId('suspect-marker').map((m) => m.textContent)).toEqual([
'music video', 'music video',
'[Audio]', '[Audio]',
@@ -85,16 +85,16 @@ describe('Suspect sources page', () => {
test('joins a folder that straddles a page boundary', () => { test('joins a folder that straddles a page boundary', () => {
mocked.mockReturnValue( mocked.mockReturnValue(
infinite([ infinite([
page(0, 3, [{ directory: HUMANZ, tracks: [track('Strobelite', 'a (Official Video).mp3', ['music video'])] }]), page(0, 3, [{ directory: MAMMALZ, tracks: [track('Strobeline', 'a (Official Video).mp3', ['music video'])] }]),
page(1, 3, [ page(1, 3, [
{ directory: HUMANZ, tracks: [track('Momentz', 'b (Visualizer).mp3', ['visualiser'])] }, { directory: MAMMALZ, tracks: [track('Minutez', 'b (Visualizer).mp3', ['visualiser'])] },
{ directory: '/music/Daft Punk/RAM', tracks: [track('Doin It Right', 'c (Music Video).mp3', ['music video'])] } { directory: '/music/Deft Monks/RAD', tracks: [track('Doin It Twice', 'c (Music Video).mp3', ['music video'])] }
]) ])
]) ])
); );
render(SuspectSourcesPage); render(SuspectSourcesPage);
expect(screen.getAllByText(HUMANZ)).toHaveLength(1); expect(screen.getAllByText(MAMMALZ)).toHaveLength(1);
expect(screen.getAllByText('2 tracks')).toHaveLength(1); expect(screen.getAllByText('2 tracks')).toHaveLength(1);
expect(screen.getAllByTestId('suspect-track-row')).toHaveLength(3); expect(screen.getAllByTestId('suspect-track-row')).toHaveLength(3);
}); });
@@ -107,7 +107,7 @@ describe('Suspect sources page', () => {
test('loads more as you scroll, with no button', () => { test('loads more as you scroll, with no button', () => {
mocked.mockReturnValue( mocked.mockReturnValue(
infinite([page(0, 80, [{ directory: HUMANZ, tracks: [track('Strobelite', 'a (Official Video).mp3', ['music video'])] }])], { infinite([page(0, 80, [{ directory: MAMMALZ, tracks: [track('Strobeline', 'a (Official Video).mp3', ['music video'])] }])], {
hasNextPage: true hasNextPage: true
}) })
); );
@@ -123,8 +123,8 @@ describe('Suspect sources page', () => {
infinite([ infinite([
page(0, 1, [ page(0, 1, [
{ {
directory: HUMANZ, directory: MAMMALZ,
tracks: [track('Strobelite', 'Gorillaz - Strobelite (Official Video).mp3', ['music video'])] tracks: [track('Strobeline', 'Plastic Apes - Strobeline (Official Video).mp3', ['music video'])]
} }
]) ])
]) ])
@@ -133,7 +133,7 @@ describe('Suspect sources page', () => {
expect(screen.getByTestId('suspect-verdict')).toHaveTextContent(/Held back/); expect(screen.getByTestId('suspect-verdict')).toHaveTextContent(/Held back/);
await fireEvent.click(screen.getByRole('button', { name: 'This one is fine' })); await fireEvent.click(screen.getByRole('button', { name: 'This one is fine' }));
expect(setSuspectVerdict).toHaveBeenCalledWith('t-Strobelite', 'fine'); expect(setSuspectVerdict).toHaveBeenCalledWith('t-Strobeline', 'fine');
expect(await screen.findByText('Marked fine')).toBeInTheDocument(); expect(await screen.findByText('Marked fine')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Hold back again' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Hold back again' })).toBeInTheDocument();
}); });
@@ -145,17 +145,17 @@ describe('Suspect sources page', () => {
infinite([ infinite([
page(0, 1, [ page(0, 1, [
{ {
directory: HUMANZ, directory: MAMMALZ,
tracks: [track('Strobelite', 'Gorillaz - Strobelite (Official Video).mp3', ['music video'])] tracks: [track('Strobeline', 'Plastic Apes - Strobeline (Official Video).mp3', ['music video'])]
} }
]) ])
]) ])
); );
render(SuspectSourcesPage); render(SuspectSourcesPage);
await fireEvent.click(screen.getByRole('button', { name: 'Remove the file of Strobelite' })); await fireEvent.click(screen.getByRole('button', { name: 'Remove the file of Strobeline' }));
expect(removeSuspectFile).not.toHaveBeenCalled(); expect(removeSuspectFile).not.toHaveBeenCalled();
await fireEvent.click(screen.getByRole('button', { name: 'Confirm remove the file of Strobelite' })); await fireEvent.click(screen.getByRole('button', { name: 'Confirm remove the file of Strobeline' }));
expect(removeSuspectFile).toHaveBeenCalledWith('t-Strobelite'); expect(removeSuspectFile).toHaveBeenCalledWith('t-Strobeline');
}); });
}); });
+6 -6
View File
@@ -16,13 +16,13 @@ const baseRow: QuarantineMineRow = {
reason: 'bad_rip', reason: 'bad_rip',
notes: 'crackles', notes: 'crackles',
created_at: new Date(Date.now() - 2 * 24 * 3_600_000).toISOString(), // 2 days ago created_at: new Date(Date.now() - 2 * 24 * 3_600_000).toISOString(), // 2 days ago
track_title: 'Roygbiv', track_title: 'Prismatic',
track_duration_ms: 200000, track_duration_ms: 200000,
album_id: 'a1', album_id: 'a1',
album_title: 'Geogaddi', album_title: 'Geomantic',
album_cover_art_path: null, album_cover_art_path: null,
artist_id: 'ar1', artist_id: 'ar1',
artist_name: 'Boards of Canada' artist_name: 'Fields of Ontario'
}; };
afterEach(() => vi.clearAllMocks()); afterEach(() => vi.clearAllMocks());
@@ -31,8 +31,8 @@ describe('/library/hidden', () => {
test('renders one row per quarantine with title + meta + reason pill + notes', () => { test('renders one row per quarantine with title + meta + reason pill + notes', () => {
(createMyQuarantineQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: [baseRow] })); (createMyQuarantineQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: [baseRow] }));
render(HiddenPage); render(HiddenPage);
expect(screen.getByText('Roygbiv')).toBeInTheDocument(); expect(screen.getByText('Prismatic')).toBeInTheDocument();
expect(screen.getByText(/by boards of canada · geogaddi/i)).toBeInTheDocument(); expect(screen.getByText(/by fields of ontario · geomantic/i)).toBeInTheDocument();
expect(screen.getByText('Bad rip')).toBeInTheDocument(); expect(screen.getByText('Bad rip')).toBeInTheDocument();
expect(screen.getByText('crackles')).toBeInTheDocument(); expect(screen.getByText('crackles')).toBeInTheDocument();
}); });
@@ -40,7 +40,7 @@ describe('/library/hidden', () => {
test('un-hide button calls unflagTrack', async () => { test('un-hide button calls unflagTrack', async () => {
(createMyQuarantineQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: [baseRow] })); (createMyQuarantineQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: [baseRow] }));
render(HiddenPage); render(HiddenPage);
await fireEvent.click(screen.getByRole('button', { name: /un-hide roygbiv/i })); await fireEvent.click(screen.getByRole('button', { name: /un-hide prismatic/i }));
expect(unflagTrack).toHaveBeenCalledWith('t1'); expect(unflagTrack).toHaveBeenCalledWith('t1');
}); });
+9 -9
View File
@@ -38,14 +38,14 @@ function page<T>(items: T[], total: number, offset = 0, limit = 50): Page<T> {
afterEach(() => vi.clearAllMocks()); afterEach(() => vi.clearAllMocks());
const ar: ArtistRef = { id: 'a1', name: 'Miles', sort_name: 'Miles', album_count: 1, cover_url: '' }; const ar: ArtistRef = { id: 'a1', name: 'Marlo', sort_name: 'Marlo', album_count: 1, cover_url: '' };
const al: AlbumRef = { const al: AlbumRef = {
id: 'al1', title: 'Kind of Blue', sort_title: 'Kind of Blue', artist_id: 'a1', artist_name: 'Miles', id: 'al1', title: 'Kind of Grey', sort_title: 'Kind of Grey', artist_id: 'a1', artist_name: 'Marlo',
year: 1959, track_count: 1, duration_sec: 100, cover_url: '/x', cover_art_source: null year: 1959, track_count: 1, duration_sec: 100, cover_url: '/x', cover_art_source: null
}; };
const tr: TrackRef = makeTrack({ const tr: TrackRef = makeTrack({
title: 'So What', album_id: 'al1', album_title: 'Kind of Blue', title: 'So Then', album_id: 'al1', album_title: 'Kind of Grey',
artist_id: 'a1', artist_name: 'Miles', duration_sec: 100 artist_id: 'a1', artist_name: 'Marlo', duration_sec: 100
}); });
function setup(opts: { function setup(opts: {
@@ -78,14 +78,14 @@ describe('liked library page', () => {
'Albums 1', 'Albums 1',
'Tracks 1' 'Tracks 1'
]); ]);
expect(screen.getByText('Miles')).toBeInTheDocument(); expect(screen.getByText('Marlo')).toBeInTheDocument();
expect(screen.queryByText('So What')).not.toBeInTheDocument(); expect(screen.queryByText('So Then')).not.toBeInTheDocument();
await fireEvent.click(screen.getByRole('tab', { name: /albums/i })); await fireEvent.click(screen.getByRole('tab', { name: /albums/i }));
expect(screen.getByText('Kind of Blue')).toBeInTheDocument(); expect(screen.getByText('Kind of Grey')).toBeInTheDocument();
await fireEvent.click(screen.getByRole('tab', { name: /tracks/i })); await fireEvent.click(screen.getByRole('tab', { name: /tracks/i }));
expect(screen.getByText('So What')).toBeInTheDocument(); expect(screen.getByText('So Then')).toBeInTheDocument();
expect(screen.getByRole('tab', { name: /tracks/i })).toHaveAttribute('aria-selected', 'true'); expect(screen.getByRole('tab', { name: /tracks/i })).toHaveAttribute('aria-selected', 'true');
}); });
@@ -93,7 +93,7 @@ describe('liked library page', () => {
setup({ tracks: page([tr], 1) }); setup({ tracks: page([tr], 1) });
render(LikedPage); render(LikedPage);
expect(screen.getByRole('tab', { name: /tracks/i })).toHaveAttribute('aria-selected', 'true'); expect(screen.getByRole('tab', { name: /tracks/i })).toHaveAttribute('aria-selected', 'true');
expect(screen.getByText('So What')).toBeInTheDocument(); expect(screen.getByText('So Then')).toBeInTheDocument();
}); });
test('all three empty renders the whole-page onboarding card and no tabs', () => { test('all three empty renders the whole-page onboarding card and no tabs', () => {
+4 -4
View File
@@ -7,7 +7,7 @@ import { apiClientMock } from '../../../test-utils/mocks/client';
import { pageUrlModule } from '#test-utils/mocks/appState.js'; import { pageUrlModule } from '#test-utils/mocks/appState.js';
import type { AlbumRef, Page } from '#lib/api/types.js'; import type { AlbumRef, Page } from '#lib/api/types.js';
const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/albums?q=miles') })); const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/albums?q=marlo') }));
vi.mock('$app/state', () => pageUrlModule(state)); vi.mock('$app/state', () => pageUrlModule(state));
@@ -30,13 +30,13 @@ function page<T>(items: T[], total: number, offset = 0, limit = 50): Page<T> {
} }
const album: AlbumRef = { const album: AlbumRef = {
id: 'al1', title: 'Kind of Blue', sort_title: 'Kind of Blue', artist_id: 'a1', artist_name: 'Miles Davis', id: 'al1', title: 'Kind of Grey', sort_title: 'Kind of Grey', artist_id: 'a1', artist_name: 'Marlo Davies',
year: 1959, track_count: 5, duration_sec: 2630, cover_url: '/api/albums/al1/cover', cover_art_source: null year: 1959, track_count: 5, duration_sec: 2630, cover_url: '/api/albums/al1/cover', cover_art_source: null
}; };
afterEach(() => { afterEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
state.pageUrl = new URL('http://localhost/search/albums?q=miles'); state.pageUrl = new URL('http://localhost/search/albums?q=marlo');
}); });
describe('search albums overflow', () => { describe('search albums overflow', () => {
@@ -45,7 +45,7 @@ describe('search albums overflow', () => {
mockInfiniteQuery({ pages: [page([album], 1)] }) mockInfiniteQuery({ pages: [page([album], 1)] })
); );
render(AlbumsOverflow); render(AlbumsOverflow);
expect(screen.getByRole('link', { name: /Kind of Blue/ })).toHaveAttribute('href', '/albums/al1'); expect(screen.getByRole('link', { name: /Kind of Grey/ })).toHaveAttribute('href', '/albums/al1');
}); });
// No button; reaching the end of the list loads the next page. // No button; reaching the end of the list loads the next page.
@@ -6,7 +6,7 @@ import { emptyLikesMock } from '../../../test-utils/mocks/likes';
import { pageUrlModule } from '#test-utils/mocks/appState.js'; import { pageUrlModule } from '#test-utils/mocks/appState.js';
import type { ArtistRef, Page } from '#lib/api/types.js'; import type { ArtistRef, Page } from '#lib/api/types.js';
const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/artists?q=miles') })); const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/artists?q=marlo') }));
vi.mock('$app/state', () => pageUrlModule(state)); vi.mock('$app/state', () => pageUrlModule(state));
@@ -25,19 +25,19 @@ function page<T>(items: T[], total: number, offset = 0, limit = 50): Page<T> {
afterEach(() => { afterEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
state.pageUrl = new URL('http://localhost/search/artists?q=miles'); state.pageUrl = new URL('http://localhost/search/artists?q=marlo');
}); });
describe('search artists overflow', () => { describe('search artists overflow', () => {
test('renders a row per artist', () => { test('renders a row per artist', () => {
const a1: ArtistRef = { id: 'a1', name: 'Miles Davis', sort_name: 'Miles Davis', album_count: 12, cover_url: '' }; const a1: ArtistRef = { id: 'a1', name: 'Marlo Davies', sort_name: 'Marlo Davies', album_count: 12, cover_url: '' };
const a2: ArtistRef = { id: 'a2', name: 'Miles Mosley', sort_name: 'Miles Mosley', album_count: 1, cover_url: '' }; const a2: ArtistRef = { id: 'a2', name: 'Marlo Mosby', sort_name: 'Marlo Mosby', album_count: 1, cover_url: '' };
(createSearchArtistsInfiniteQuery as ReturnType<typeof vi.fn>).mockReturnValue( (createSearchArtistsInfiniteQuery as ReturnType<typeof vi.fn>).mockReturnValue(
mockInfiniteQuery({ pages: [page([a1, a2], 2)] }) mockInfiniteQuery({ pages: [page([a1, a2], 2)] })
); );
render(ArtistsOverflow); render(ArtistsOverflow);
expect(screen.getByRole('link', { name: /Miles Davis/ })).toBeInTheDocument(); expect(screen.getByRole('link', { name: /Marlo Davies/ })).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Miles Mosley/ })).toBeInTheDocument(); expect(screen.getByRole('link', { name: /Marlo Mosby/ })).toBeInTheDocument();
}); });
// No button; reaching the end of the list loads the next page. // No button; reaching the end of the list loads the next page.
+11 -11
View File
@@ -40,15 +40,15 @@ function emptyResp(): SearchResponse {
}; };
} }
const artist: ArtistRef = { id: 'a1', name: 'Miles Davis', sort_name: 'Miles Davis', album_count: 12, cover_url: '' }; const artist: ArtistRef = { id: 'a1', name: 'Marlo Davies', sort_name: 'Marlo Davies', album_count: 12, cover_url: '' };
const album: AlbumRef = { const album: AlbumRef = {
id: 'al1', title: 'Kind of Blue', sort_title: 'Kind of Blue', artist_id: 'a1', artist_name: 'Miles Davis', id: 'al1', title: 'Kind of Grey', sort_title: 'Kind of Grey', artist_id: 'a1', artist_name: 'Marlo Davies',
year: 1959, track_count: 5, duration_sec: 2630, cover_url: '/api/albums/al1/cover', cover_art_source: null year: 1959, track_count: 5, duration_sec: 2630, cover_url: '/api/albums/al1/cover', cover_art_source: null
}; };
const track = makeTrack({ const track = makeTrack({
title: 'So What', title: 'So Then',
album_id: 'al1', album_title: 'Kind of Blue', album_id: 'al1', album_title: 'Kind of Grey',
artist_id: 'a1', artist_name: 'Miles Davis', artist_id: 'a1', artist_name: 'Marlo Davies',
duration_sec: 545 duration_sec: 545
}); });
@@ -66,7 +66,7 @@ describe('search page', () => {
}); });
test('all three sections render when all three facets have items', () => { test('all three sections render when all three facets have items', () => {
state.pageUrl = new URL('http://localhost/search?q=miles'); state.pageUrl = new URL('http://localhost/search?q=marlo');
const resp: SearchResponse = { const resp: SearchResponse = {
...emptyResp(), ...emptyResp(),
artists: { items: [artist], total: 1, limit: 10, offset: 0 }, artists: { items: [artist], total: 1, limit: 10, offset: 0 },
@@ -81,7 +81,7 @@ describe('search page', () => {
}); });
test('empty facets are hidden', () => { test('empty facets are hidden', () => {
state.pageUrl = new URL('http://localhost/search?q=miles'); state.pageUrl = new URL('http://localhost/search?q=marlo');
const resp: SearchResponse = { const resp: SearchResponse = {
...emptyResp(), ...emptyResp(),
tracks: { items: [track], total: 1, limit: 10, offset: 0 } tracks: { items: [track], total: 1, limit: 10, offset: 0 }
@@ -94,7 +94,7 @@ describe('search page', () => {
}); });
test('"See all N →" link renders when total > items.length', () => { test('"See all N →" link renders when total > items.length', () => {
state.pageUrl = new URL('http://localhost/search?q=miles'); state.pageUrl = new URL('http://localhost/search?q=marlo');
const resp: SearchResponse = { const resp: SearchResponse = {
...emptyResp(), ...emptyResp(),
artists: { items: [artist], total: 47, limit: 10, offset: 0 } artists: { items: [artist], total: 47, limit: 10, offset: 0 }
@@ -102,11 +102,11 @@ describe('search page', () => {
(createSearchQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: resp })); (createSearchQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: resp }));
render(SearchPage); render(SearchPage);
const link = screen.getByRole('link', { name: /see all 47/i }); const link = screen.getByRole('link', { name: /see all 47/i });
expect(link).toHaveAttribute('href', '/search/artists?q=miles'); expect(link).toHaveAttribute('href', '/search/artists?q=marlo');
}); });
test('"See all" link omitted when total === items.length', () => { test('"See all" link omitted when total === items.length', () => {
state.pageUrl = new URL('http://localhost/search?q=miles'); state.pageUrl = new URL('http://localhost/search?q=marlo');
const resp: SearchResponse = { const resp: SearchResponse = {
...emptyResp(), ...emptyResp(),
tracks: { items: [track], total: 1, limit: 10, offset: 0 } tracks: { items: [track], total: 1, limit: 10, offset: 0 }
@@ -127,7 +127,7 @@ describe('search page', () => {
}); });
test('error state renders ApiErrorBanner', () => { test('error state renders ApiErrorBanner', () => {
state.pageUrl = new URL('http://localhost/search?q=miles'); state.pageUrl = new URL('http://localhost/search?q=marlo');
(createSearchQuery as ReturnType<typeof vi.fn>).mockReturnValue( (createSearchQuery as ReturnType<typeof vi.fn>).mockReturnValue(
mockQuery({ isError: true, error: { code: 'server_error', message: 'boom' } }) mockQuery({ isError: true, error: { code: 'server_error', message: 'boom' } })
); );
+5 -5
View File
@@ -8,7 +8,7 @@ import { pageUrlModule } from '#test-utils/mocks/appState.js';
import type { TrackRef, Page } from '#lib/api/types.js'; import type { TrackRef, Page } from '#lib/api/types.js';
import { makeTrack } from '#test-utils/fixtures/track.js'; import { makeTrack } from '#test-utils/fixtures/track.js';
const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/tracks?q=miles') })); const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/search/tracks?q=marlo') }));
vi.mock('$app/state', () => pageUrlModule(state)); vi.mock('$app/state', () => pageUrlModule(state));
@@ -35,11 +35,11 @@ function page<T>(items: T[], total: number, offset = 0, limit = 50): Page<T> {
return { items, total, offset, limit }; return { items, total, offset, limit };
} }
const track = makeTrack({ title: 'So What' }); const track = makeTrack({ title: 'So Then' });
afterEach(() => { afterEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
state.pageUrl = new URL('http://localhost/search/tracks?q=miles'); state.pageUrl = new URL('http://localhost/search/tracks?q=marlo');
}); });
describe('search tracks overflow', () => { describe('search tracks overflow', () => {
@@ -48,7 +48,7 @@ describe('search tracks overflow', () => {
mockInfiniteQuery({ pages: [page([track], 1)] }) mockInfiniteQuery({ pages: [page([track], 1)] })
); );
render(TracksOverflow); render(TracksOverflow);
expect(screen.getByRole('button', { name: 'So What' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'So Then' })).toBeInTheDocument();
}); });
test('clicking a track row triggers playRadio with the track id', async () => { test('clicking a track row triggers playRadio with the track id', async () => {
@@ -56,7 +56,7 @@ describe('search tracks overflow', () => {
mockInfiniteQuery({ pages: [page([track], 1)] }) mockInfiniteQuery({ pages: [page([track], 1)] })
); );
render(TracksOverflow); render(TracksOverflow);
await fireEvent.click(screen.getByRole('button', { name: 'So What' })); await fireEvent.click(screen.getByRole('button', { name: 'So Then' }));
expect(playRadio).toHaveBeenCalledWith('t1'); expect(playRadio).toHaveBeenCalledWith('t1');
}); });