The first public release of Fabled Minstrel #158

Merged
bvandeusen merged 256 commits from dev into main 2026-12-03 21:41:58 -05:00
9 changed files with 456 additions and 1238 deletions
Showing only changes of commit ac8792323c - Show all commits
+43 -63
View File
@@ -120,7 +120,7 @@ func TestResolveDuplicates_LinksASameReleaseCopyAndRemovesNothing_Integration(t
}
}
// With auto-resolve off, the pass classifies and removes nothing.
// With auto-resolve off, the pass classifies, and links and removes nothing.
func TestResolveDuplicates_ClassifiesOnlyWithoutPermission_Integration(t *testing.T) {
f := newResolveFixture(t)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, false)
@@ -134,6 +134,9 @@ func TestResolveDuplicates_ClassifiesOnlyWithoutPermission_Integration(t *testin
if status != "pending" || class == nil || *class != string(ClassSameRelease) {
t.Errorf("group = (%s, %v), want pending and classified", status, class)
}
if keys := songKeys(t, dbq.New(f.pool), f.clean.ID, f.rip.ID); keys[0] == keys[1] {
t.Error("linked as one song with auto-resolve off")
}
}
// crossReleaseRipFixture is a video rip on one release with the clean copy on
@@ -194,84 +197,61 @@ func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture {
return f
}
// A video rip on one release with the clean copy on another: both files stay,
// the copies count as one song, and the group waits for an admin to remove
// the rip.
func TestResolveDuplicates_LinksARipAcrossReleasesAndRemovesNothing_Integration(t *testing.T) {
f := newCrossReleaseRipFixture(t)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Classes[ClassCrossRelease] != 1 || res.SongsLinked != 1 {
t.Fatalf("result %+v; want the cross-release group linked as one song", res)
}
if !exists(f.ripPath) || !exists(f.cleanPath) {
t.Errorf("rip exists %v, clean exists %v; want both files left in place", exists(f.ripPath), exists(f.cleanPath))
}
if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" {
t.Errorf("group = %s, want pending for an admin", status)
}
if n, _ := autoMergeAudit(t, f.pool, f.groupID); n != 0 {
t.Errorf("automatic merge audit rows = %d, want none", n)
}
}
// Copies on two releases that are both clean each belong to their release:
// nothing is removed, and they are linked as one song. A rip an admin
// marked fine counts as clean.
func TestResolveDuplicates_KeepsCleanCopiesOnTwoReleases_Integration(t *testing.T) {
for name, prepare := range map[string]func(f crossReleaseRipFixture) (string, []any){
"renamed": func(f crossReleaseRipFixture) (string, []any) {
// Copies on separate releases (an album cut and the same song's single) are
// linked as one song and every file stays. When all but one copy is named
// like a video rip, the group's note asks an admin to merge; when every copy
// is clean (named cleanly, kept as fine by an admin, or one recording under
// two titles), each belongs to its release and the note says none is removed.
func TestResolveDuplicates_LinksCopiesAcrossReleasesAndRemovesNothing_Integration(t *testing.T) {
const ripNote, cleanNote = "named like a video rip", "none is removed"
for _, tc := range []struct {
name string
prepare func(f crossReleaseRipFixture) (string, []any) // nil: the fixture as built
wantNote string
}{
{"a rip beside the clean copy", nil, ripNote},
{"the rip renamed", func(f crossReleaseRipFixture) (string, []any) {
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 Fine Ltd.mp3")}
},
"kept as fine": func(f crossReleaseRipFixture) (string, []any) {
}, cleanNote},
{"the rip kept as fine", func(f crossReleaseRipFixture) (string, []any) {
return `UPDATE tracks SET source_verdict = 'fine' WHERE id = $1`, []any{f.rip.ID}
},
}, cleanNote},
// A later release retitled the recording; identical audio.
{"one recording under two titles", func(f crossReleaseRipFixture) (string, []any) {
return `WITH g AS (UPDATE duplicate_groups SET tier = 'exact' WHERE id = $3)
UPDATE tracks SET title = 'DARE', file_path = $2 WHERE id = $1`,
[]any{f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - DARE.mp3"), f.groupID}
}, cleanNote},
} {
t.Run(name, func(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
f := newCrossReleaseRipFixture(t)
sql, args := prepare(f)
if _, err := f.pool.Exec(context.Background(), sql, args...); err != nil {
t.Fatal(err)
if tc.prepare != nil {
sql, args := tc.prepare(f)
if _, err := f.pool.Exec(context.Background(), sql, args...); err != nil {
t.Fatal(err)
}
}
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if !exists(f.ripPath) || !exists(f.cleanPath) {
t.Errorf("result %+v; want both copies kept", res)
if res.Classes[ClassCrossRelease] != 1 || res.SongsLinked != 1 {
t.Fatalf("result %+v; want the cross-release group linked as one song", res)
}
if res.SongsLinked != 1 {
t.Errorf("linked %d, want the pair linked as one song", res.SongsLinked)
if !exists(f.ripPath) || !exists(f.cleanPath) {
t.Errorf("rip exists %v, clean exists %v; want both files left in place", exists(f.ripPath), exists(f.cleanPath))
}
if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, tc.wantNote) {
t.Errorf("note %q, want it to say %q", note, tc.wantNote)
}
if n, _ := autoMergeAudit(t, f.pool, f.groupID); n != 0 {
t.Errorf("automatic merge audit rows = %d, want none", n)
}
})
}
}
// Identical audio under two titles on two albums, neither a rip: a later
// 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.
func TestResolveDuplicates_LinksOneRecordingUnderTwoTitles_Integration(t *testing.T) {
f := newCrossReleaseRipFixture(t)
ctx := context.Background()
if _, err := f.pool.Exec(ctx, `UPDATE duplicate_groups SET tier = 'exact' WHERE id = $1`, f.groupID); err != nil {
t.Fatal(err)
}
if _, err := f.pool.Exec(ctx, `UPDATE tracks SET title = 'DARE', file_path = $2 WHERE id = $1`,
f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - DARE.mp3")); err != nil {
t.Fatal(err)
}
res, err := ResolveDuplicates(ctx, f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Classes[ClassCrossRelease] != 1 || res.SongsLinked != 1 || !exists(f.ripPath) || !exists(f.cleanPath) {
t.Fatalf("result %+v; want the pair linked and kept", res)
}
}
// oneAlbumFixture is one album holding two tracks in one pending group, each
// with a file on disk.
type oneAlbumFixture struct {
+141 -287
View File
@@ -67,151 +67,10 @@ func utf8Frame(values ...string) []byte {
return append([]byte{0x03}, []byte(strings.Join(values, "\x00"))...)
}
// TestReadID3v2GenreValues_MultiValue: dhowden/tag
// rejoins these values with the empty string, producing "Alternative RockRock";
// the whole point of our own reader is that they stay separate.
func TestReadID3v2GenreValues_MultiValue(t *testing.T) {
for _, major := range []byte{2, 3, 4} {
id := "TCON"
if major == 2 {
id = "TCO"
}
data := buildID3v2(t, major, rawFrame{id, utf8Frame("Alternative Rock", "Rock")})
got, err := readID3v2GenreValues(bytes.NewReader(data))
if err != nil {
t.Fatalf("v2.%d: %v", major, err)
}
want := []string{"Alternative Rock", "Rock"}
if !equalStrings(got, want) {
t.Errorf("v2.%d genres = %q, want %q", major, got, want)
}
}
}
// Eight values that a joining reader would weld into one 70-character token.
func TestReadID3v2GenreValues_ManyValues(t *testing.T) {
values := []string{
"Boom Bap", "Downtempo", "Hip Hop", "Instrumental",
"Lo-Fi", "Lo-Fi Hip Hop", "Chillwave", "Instrumental Hip Hop",
}
data := buildID3v2(t, 4, rawFrame{"TCON", utf8Frame(values...)})
got, err := readID3v2GenreValues(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
if !equalStrings(got, values) {
t.Errorf("genres = %q, want %q", got, values)
}
}
// A trailing null terminator is legal and must not produce an empty value.
func TestReadID3v2GenreValues_TrailingTerminator(t *testing.T) {
data := buildID3v2(t, 4, rawFrame{"TCON", append(utf8Frame("Jazz"), 0x00)})
got, err := readID3v2GenreValues(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
if !equalStrings(got, []string{"Jazz"}) {
t.Errorf("genres = %q, want [Jazz]", got)
}
}
// UTF-16 uses a TWO-byte separator. Splitting it on single nulls would cut
// every ASCII character in half, so this guards the width handling.
func TestReadID3v2GenreValues_UTF16(t *testing.T) {
tests := []struct {
name string
payload []byte
}{
{
// Spec-correct: encoding 1 with a BOM on every value.
name: "utf16le, BOM on each value",
payload: concat([]byte{0x01},
[]byte{0xFF, 0xFE}, utf16LE("Rock"),
[]byte{0x00, 0x00},
[]byte{0xFF, 0xFE}, utf16LE("Pop")),
},
{
// Sloppy but common: BOM only on the first value. Without carrying
// the byte order forward, "Pop" decodes byte-swapped to CJK.
name: "utf16le, BOM only on the first value",
payload: concat([]byte{0x01},
[]byte{0xFF, 0xFE}, utf16LE("Rock"),
[]byte{0x00, 0x00}, utf16LE("Pop")),
},
{
// Encoding 2: big-endian, no BOM anywhere.
name: "utf16be no BOM",
payload: concat([]byte{0x02},
utf16BE("Rock"), []byte{0x00, 0x00}, utf16BE("Pop")),
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
data := buildID3v2(t, 4, rawFrame{"TCON", tc.payload})
got, err := readID3v2GenreValues(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
if !equalStrings(got, []string{"Rock", "Pop"}) {
t.Errorf("genres = %q, want [Rock Pop]", got)
}
})
}
}
// ISO-8859-1 must be widened, not reinterpreted as UTF-8 — "Bj\xf6rk" would
// otherwise come back as invalid bytes.
func TestReadID3v2GenreValues_Latin1(t *testing.T) {
payload := append([]byte{0x00}, []byte("Chanson Fran\xe7aise")...)
data := buildID3v2(t, 3, rawFrame{"TCON", payload})
got, err := readID3v2GenreValues(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
if !equalStrings(got, []string{"Chanson Française"}) {
t.Errorf("genres = %q, want [Chanson Française]", got)
}
}
// Frames before TCON must be walked over correctly. If the size field were
// decoded with the wrong scheme the walk lands mid-frame and TCON is missed.
func TestReadID3v2GenreValues_SkipsPrecedingFrames(t *testing.T) {
for _, major := range []byte{3, 4} {
data := buildID3v2(t, major,
rawFrame{"TIT2", utf8Frame("Some Title")},
rawFrame{"TPE1", utf8Frame("Some Artist")},
rawFrame{"TCON", utf8Frame("Shoegaze", "Dream Pop")},
)
got, err := readID3v2GenreValues(bytes.NewReader(data))
if err != nil {
t.Fatalf("v2.%d: %v", major, err)
}
if !equalStrings(got, []string{"Shoegaze", "Dream Pop"}) {
t.Errorf("v2.%d genres = %q, want [Shoegaze Dream Pop]", major, got)
}
}
}
func TestReadID3v2GenreValues_NoGenreFrame(t *testing.T) {
data := buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("Only A Title")})
if _, err := readID3v2GenreValues(bytes.NewReader(data)); err == nil {
t.Fatal("expected an error when no genre frame is present")
}
}
func TestReadID3v2GenreValues_NotAnID3File(t *testing.T) {
if _, err := readID3v2GenreValues(bytes.NewReader([]byte("not a tag at all"))); err == nil {
t.Fatal("expected an error for a file with no ID3v2 tag")
}
}
// Padding after the last frame is zero bytes; the walk must stop rather than
// read a frame id of "\x00\x00\x00\x00".
func TestReadID3v2GenreValues_StopsAtPadding(t *testing.T) {
// paddedTag is a v2.4 tag holding one TCON frame followed by 32 bytes of
// padding, the way taggers leave room to grow.
func paddedTag(t *testing.T) []byte {
tagged := buildID3v2(t, 4, rawFrame{"TCON", utf8Frame("Rock")})
// Splice 32 padding bytes in before the MPEG sync trailer, growing the
// declared tag size to match.
body := tagged[10 : len(tagged)-4]
padded := append(append([]byte{}, body...), make([]byte, 32)...)
var out bytes.Buffer
@@ -219,41 +78,90 @@ func TestReadID3v2GenreValues_StopsAtPadding(t *testing.T) {
out.Write([]byte{4, 0x00, 0x00})
out.Write(synchsafeBytes(len(padded)))
out.Write(padded)
got, err := readID3v2GenreValues(bytes.NewReader(out.Bytes()))
if err != nil {
t.Fatal(err)
}
if !equalStrings(got, []string{"Rock"}) {
t.Errorf("genres = %q, want [Rock]", got)
}
return out.Bytes()
}
// Unsynchronisation inserts 0xFF 0x00 pairs that must be collapsed before the
// frame list is walked, or every offset past the first pair is wrong.
func TestReadID3v2GenreValues_TagUnsynchronisation(t *testing.T) {
// Latin-1 so a genre can legitimately contain the byte 0xFF ("ÿ"). Once
// unsynchronised that becomes 0xFF 0x00 — which is indistinguishable from a
// value separator until the collapse runs, so this fails loudly if
// undoUnsynchronisation is skipped.
// unsynchronisedTag is a v2.3 tag with the unsynchronisation flag set, whose
// Latin-1 genre holds the byte 0xFF. Once unsynchronised that becomes
// 0xFF 0x00, indistinguishable from a value separator until the collapse runs.
func unsynchronisedTag(t *testing.T) []byte {
payload := concat([]byte{0x00}, []byte("Ro\xffck"), []byte{0x00}, []byte("Pop"))
inner := buildID3v2(t, 3, rawFrame{"TCON", payload})
body := inner[10 : len(inner)-4]
encoded := bytes.ReplaceAll(body, []byte{0xFF}, []byte{0xFF, 0x00})
if bytes.Equal(encoded, body) {
t.Fatal("test is vacuous: nothing was unsynchronised")
t.Fatal("fixture is vacuous: nothing was unsynchronised")
}
var out bytes.Buffer
out.WriteString("ID3")
out.Write([]byte{3, 0x00, 0x80}) // 0x80 = unsynchronisation
out.Write(synchsafeBytes(len(encoded)))
out.Write(encoded)
return out.Bytes()
}
got, err := readID3v2GenreValues(bytes.NewReader(out.Bytes()))
if err != nil {
t.Fatal(err)
}
if !equalStrings(got, []string{"Roÿck", "Pop"}) {
t.Errorf("genres = %q, want [Roÿck Pop]", got)
// Minstrel reads ID3v2 genre frames itself because dhowden/tag rejoins
// multiple values with the empty string ("Alternative RockRock"). Each case is
// a detail of the format a reader gets subtly wrong.
func TestReadID3v2GenreValues(t *testing.T) {
multi := utf8Frame("Alternative Rock", "Rock")
for _, tc := range []struct {
name string
data func(t *testing.T) []byte
want []string
err bool
}{
// Frame size encoding differs per version: 2.4 is synchsafe, 2.2 and
// 2.3 are plain.
{"v2.2 multi-value", func(t *testing.T) []byte { return buildID3v2(t, 2, rawFrame{"TCO", multi}) }, []string{"Alternative Rock", "Rock"}, false},
{"v2.3 multi-value", func(t *testing.T) []byte { return buildID3v2(t, 3, rawFrame{"TCON", multi}) }, []string{"Alternative Rock", "Rock"}, false},
{"v2.4 multi-value", func(t *testing.T) []byte { return buildID3v2(t, 4, rawFrame{"TCON", multi}) }, []string{"Alternative Rock", "Rock"}, false},
{"a trailing terminator adds no empty value", func(t *testing.T) []byte {
return buildID3v2(t, 4, rawFrame{"TCON", append(utf8Frame("Jazz"), 0x00)})
}, []string{"Jazz"}, false},
// UTF-16 uses a two-byte separator; splitting on single nulls would
// cut every ASCII character in half.
{"utf16le, BOM on each value", func(t *testing.T) []byte {
return buildID3v2(t, 4, rawFrame{"TCON", concat([]byte{0x01},
[]byte{0xFF, 0xFE}, utf16LE("Rock"), []byte{0x00, 0x00}, []byte{0xFF, 0xFE}, utf16LE("Pop"))})
}, []string{"Rock", "Pop"}, false},
// Sloppy but common; without carrying the byte order forward, "Pop"
// decodes byte-swapped to CJK.
{"utf16le, BOM only on the first value", func(t *testing.T) []byte {
return buildID3v2(t, 4, rawFrame{"TCON", concat([]byte{0x01},
[]byte{0xFF, 0xFE}, utf16LE("Rock"), []byte{0x00, 0x00}, utf16LE("Pop"))})
}, []string{"Rock", "Pop"}, false},
{"utf16be, no BOM", func(t *testing.T) []byte {
return buildID3v2(t, 4, rawFrame{"TCON", concat([]byte{0x02}, utf16BE("Rock"), []byte{0x00, 0x00}, utf16BE("Pop"))})
}, []string{"Rock", "Pop"}, false},
// ISO-8859-1 is widened, not reinterpreted as UTF-8.
{"latin-1", func(t *testing.T) []byte {
return buildID3v2(t, 3, rawFrame{"TCON", append([]byte{0x00}, []byte("Chanson Fran\xe7aise")...)})
}, []string{"Chanson Française"}, false},
// A wrongly decoded size lands the walk mid-frame and misses TCON.
{"v2.3 frames before TCON", func(t *testing.T) []byte {
return buildID3v2(t, 3, rawFrame{"TIT2", utf8Frame("Some Title")}, rawFrame{"TPE1", utf8Frame("Some Artist")},
rawFrame{"TCON", utf8Frame("Shoegaze", "Dream Pop")})
}, []string{"Shoegaze", "Dream Pop"}, false},
{"v2.4 frames before TCON", func(t *testing.T) []byte {
return buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("Some Title")}, rawFrame{"TPE1", utf8Frame("Some Artist")},
rawFrame{"TCON", utf8Frame("Shoegaze", "Dream Pop")})
}, []string{"Shoegaze", "Dream Pop"}, false},
// The walk stops at padding rather than reading a frame id of zeros.
{"padding after the last frame", paddedTag, []string{"Rock"}, false},
{"tag unsynchronisation", unsynchronisedTag, []string{"Roÿck", "Pop"}, false},
{"no genre frame", func(t *testing.T) []byte { return buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("Only A Title")}) }, nil, true},
{"not an ID3 file", func(*testing.T) []byte { return []byte("not a tag at all") }, nil, true},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := readID3v2GenreValues(bytes.NewReader(tc.data(t)))
if (err != nil) != tc.err {
t.Fatalf("err = %v, want error: %v", err, tc.err)
}
if !equalStrings(got, tc.want) {
t.Errorf("genres = %q, want %q", got, tc.want)
}
})
}
}
@@ -288,6 +196,19 @@ func TestNormaliseGenreValue(t *testing.T) {
// A label that merely starts with digits is text, not a reference.
{"digits in a name", "1980s", []string{"1980s"}},
{"hyphenated", "Lo-Fi Hip Hop", []string{"Lo-Fi Hip Hop"}},
// Casing repair runs on text from the file, including the
// parenthesised and refinement paths; punctuation around an acronym
// does not hide it.
{"casing repaired", "Edm", []string{"EDM"}},
{"casing repaired after a reference", "(17)Uk Garage", []string{"Rock", "UK Garage"}},
{"casing repaired inside parentheses", "(Live Edm)", []string{"(Live EDM)"}},
{"casing repaired after an escaped paren", "((Children'S Music", []string{"(Children's Music"}},
// It never touches a name from the ID3v1 table, which is kept
// canonical: entry 40's 1990s spelling stays though it reads like
// damage.
{"table name not recased", "40", []string{"AlternRock"}},
{"parenthesised table name not recased", "(40)", []string{"AlternRock"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
@@ -299,88 +220,64 @@ func TestNormaliseGenreValue(t *testing.T) {
}
}
func TestNormaliseGenres_DedupesCaseInsensitively(t *testing.T) {
got := normaliseGenres([]string{"Rock", "rock", "ROCK", "Pop"})
// First spelling wins — we are not imposing a canonical case here, only
// removing values that repeat within a single file.
if !equalStrings(got, []string{"Rock", "Pop"}) {
t.Errorf("genres = %q, want [Rock Pop]", got)
// normaliseGenres removes values that repeat within one file, keeping the
// first spelling; it imposes no canonical case beyond the acronym repair.
func TestNormaliseGenres(t *testing.T) {
for _, tc := range []struct {
name string
in []string
want []string
}{
{"case-insensitive repeats", []string{"Rock", "rock", "ROCK", "Pop"}, []string{"Rock", "Pop"}},
// "(40)AlternRock" declares one genre twice, numerically and in text.
{"a reference and its own name", []string{"(40)AlternRock"}, []string{"AlternRock"}},
{"acronym spellings", []string{"Edm", "EDM", "edm"}, []string{"EDM"}},
{"nothing usable", []string{"", " ", "9999"}, nil},
} {
t.Run(tc.name, func(t *testing.T) {
if got := normaliseGenres(tc.in); !equalStrings(got, tc.want) {
t.Errorf("normaliseGenres(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
}
// "(40)AlternRock" declares the same genre twice — numerically and in text.
func TestNormaliseGenres_DedupesResolvedNumeric(t *testing.T) {
got := normaliseGenres([]string{"(40)AlternRock"})
if !equalStrings(got, []string{"AlternRock"}) {
t.Errorf("genres = %q, want [AlternRock]", got)
}
}
func TestNormaliseGenres_AllJunkYieldsNil(t *testing.T) {
if got := normaliseGenres([]string{"", " ", "9999"}); got != nil {
t.Errorf("genres = %q, want nil", got)
}
}
// End-to-end through dhowden/tag, which is what the scanner actually calls.
// Proves the welded value never reaches the caller.
func TestExtractGenres_EndToEnd(t *testing.T) {
data := buildID3v2(t, 4,
rawFrame{"TIT2", utf8Frame("A Song")},
rawFrame{"TCON", utf8Frame("Alternative Rock", "Rock")},
)
rs := bytes.NewReader(data)
meta, err := tag.ReadFrom(rs)
if err != nil {
t.Fatalf("tag.ReadFrom: %v", err)
}
// Confirm the upstream behaviour this reader works around is still present —
// if dhowden ever fixes it, this test tells us the workaround can go.
if welded := meta.Genre(); welded != "Alternative RockRock" {
t.Logf("note: dhowden/tag no longer welds multi-values (got %q)", welded)
}
genres, fellBack := extractGenres(meta, rs)
if fellBack {
t.Error("fellBack = true, want false — the TCON frame is parseable")
}
if !equalStrings(genres, []string{"Alternative Rock", "Rock"}) {
t.Errorf("genres = %q, want [Alternative Rock Rock]", genres)
}
if joined := strings.Join(genres, genreDelimiter); joined != "Alternative Rock;Rock" {
t.Errorf("stored value = %q, want %q", joined, "Alternative Rock;Rock")
}
}
// The digit-soup case, end to end: numeric references resolve to names.
func TestExtractGenres_ResolvesNumericReferences(t *testing.T) {
data := buildID3v2(t, 4, rawFrame{"TCON", utf8Frame("40", "17")})
rs := bytes.NewReader(data)
meta, err := tag.ReadFrom(rs)
if err != nil {
t.Fatalf("tag.ReadFrom: %v", err)
}
genres, _ := extractGenres(meta, rs)
if !equalStrings(genres, []string{"AlternRock", "Rock"}) {
t.Errorf("genres = %q, want [AlternRock Rock]", genres)
}
}
// A file with no genre at all must yield nothing and must NOT be reported as a
// fallback — that would log a warning for every untagged file in the library.
func TestExtractGenres_NoGenreIsNotAFallback(t *testing.T) {
data := buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("A Song")})
rs := bytes.NewReader(data)
meta, err := tag.ReadFrom(rs)
if err != nil {
t.Fatalf("tag.ReadFrom: %v", err)
}
genres, fellBack := extractGenres(meta, rs)
if len(genres) != 0 {
t.Errorf("genres = %q, want none", genres)
}
if fellBack {
t.Error("fellBack = true for an untagged file; would log on every such file")
// extractGenres is what the scanner calls, after dhowden/tag has read the
// file. In every format the values stay separate (dhowden welds ID3 values
// together and keeps only the last Vorbis GENRE field), numeric ID3
// references resolve to names, and a file with no genre yields nothing and is
// not reported as a fallback, which would log a warning for every untagged
// file in the library.
func TestExtractGenres(t *testing.T) {
oggComment := append([]byte("\x03vorbis"), vorbisComment(genreFields("Shoegaze", "Dream Pop")...)...)
oggComment = append(oggComment, 1) // framing bit
for _, tc := range []struct {
name string
data []byte
want []string
}{
{"id3 multi-value", buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("A Song")},
rawFrame{"TCON", utf8Frame("Alternative Rock", "Rock")}), []string{"Alternative Rock", "Rock"}},
{"id3 numeric references", buildID3v2(t, 4, rawFrame{"TCON", utf8Frame("40", "17")}), []string{"AlternRock", "Rock"}},
{"id3 with no genre", buildID3v2(t, 4, rawFrame{"TIT2", utf8Frame("A Song")}), nil},
{"flac repeated fields", buildFLAC(false, append([]string{"TITLE=Eons"}, genreFields(lifeForms...)...)...), lifeForms},
{"ogg vorbis repeated fields", buildOgg(7, vorbisIdent(), oggComment), []string{"Shoegaze", "Dream Pop"}},
{"mp4 several data atoms", buildMP4(true, mp4Box("\xa9gen", mp4Text("Hip Hop"), mp4Text("Lo-Fi"))), []string{"Hip Hop", "Lo-Fi"}},
} {
t.Run(tc.name, func(t *testing.T) {
rs := bytes.NewReader(tc.data)
meta, err := tag.ReadFrom(rs)
if err != nil {
t.Fatalf("tag.ReadFrom: %v", err)
}
genres, fellBack := extractGenres(meta, rs)
if fellBack {
t.Error("fellBack = true, want false")
}
if !equalStrings(genres, tc.want) {
t.Errorf("genres = %q, want %q", genres, tc.want)
}
})
}
}
@@ -475,46 +372,3 @@ func TestTrueUpCasing(t *testing.T) {
})
}
}
// The casing repair must never touch a name resolved from the ID3v1 table.
// That table is kept canonical, so entry 40's 1990s spelling "AlternRock"
// stays as-is even though it reads like damage.
func TestNormaliseGenreValue_CanonicalTableNamesNotRecased(t *testing.T) {
if got := normaliseGenreValue("40"); !equalStrings(got, []string{"AlternRock"}) {
t.Errorf("bare 40 = %q, want [AlternRock]", got)
}
if got := normaliseGenreValue("(40)"); !equalStrings(got, []string{"AlternRock"}) {
t.Errorf("(40) = %q, want [AlternRock]", got)
}
}
// Casing runs on values that came from the file, including the parenthesised
// and refinement paths.
func TestNormaliseGenreValue_CasingAppliedToFileText(t *testing.T) {
tests := []struct {
in string
want []string
}{
{"Edm", []string{"EDM"}},
{"(17)Uk Garage", []string{"Rock", "UK Garage"}},
// Punctuation around the acronym must not hide it — the letter core is
// what gets matched, and the trimmed edges are re-attached.
{"(Live Edm)", []string{"(Live EDM)"}},
{"((Children'S Music", []string{"(Children's Music"}},
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
if got := normaliseGenreValue(tc.in); !equalStrings(got, tc.want) {
t.Errorf("normaliseGenreValue(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
}
// Two spellings of one acronym in the same file collapse to a single tag rather
// than surviving as near-duplicates.
func TestNormaliseGenres_AcronymVariantsDedupe(t *testing.T) {
if got := normaliseGenres([]string{"Edm", "EDM", "edm"}); !equalStrings(got, []string{"EDM"}) {
t.Errorf("genres = %q, want [EDM]", got)
}
}
+49 -228
View File
@@ -31,215 +31,65 @@ func (s stubMeta) Lyrics() string { return "" }
func (s stubMeta) Comment() string { return "" }
func (s stubMeta) Raw() map[string]interface{} { return s.raw }
func TestExtractMBIDs_Vorbis(t *testing.T) {
// dhowden lowercases all Vorbis comment keys at parse time.
m := stubMeta{
format: tag.VORBIS,
raw: map[string]interface{}{
"musicbrainz_albumid": "abc",
"musicbrainz_artistid": "def",
},
}
ids := ReadTagMBIDs(m)
a, ar := ids.Release, ids.Artist
if a != "abc" || ar != "def" {
t.Errorf("got (%q, %q), want (\"abc\", \"def\")", a, ar)
}
}
func TestExtractMBIDs_ID3v2(t *testing.T) {
// dhowden stores TXXX frames under bare "TXXX"/"TXXX_N" keys with
// *tag.Comm values whose Description holds the Picard tag name.
m := stubMeta{
format: tag.ID3v2_4,
raw: map[string]interface{}{
"TXXX": &tag.Comm{
Description: "MusicBrainz Album Id",
Text: "abc-123",
},
"TXXX_0": &tag.Comm{
Description: "MusicBrainz Artist Id",
Text: "def-456",
},
},
}
ids := ReadTagMBIDs(m)
a, ar := ids.Release, ids.Artist
if a != "abc-123" || ar != "def-456" {
t.Errorf("got (%q, %q), want (\"abc-123\", \"def-456\")", a, ar)
}
}
func TestExtractMBIDs_MP4(t *testing.T) {
// dhowden stores freeform iTunes atoms under their bare sub-name.
// mbz.Extract maps the human-readable form back to its lowercase key.
m := stubMeta{
format: tag.MP4,
raw: map[string]interface{}{
"MusicBrainz Album Id": "abc",
"MusicBrainz Artist Id": "def",
},
}
ids := ReadTagMBIDs(m)
a, ar := ids.Release, ids.Artist
if a != "abc" || ar != "def" {
t.Errorf("got (%q, %q), want (\"abc\", \"def\")", a, ar)
}
}
func TestExtractMBIDs_MissingTagsReturnEmpty(t *testing.T) {
m := stubMeta{format: tag.VORBIS, raw: map[string]interface{}{}}
ids := ReadTagMBIDs(m)
a, ar := ids.Release, ids.Artist
if a != "" || ar != "" {
t.Errorf("got (%q, %q), want empty", a, ar)
}
}
func TestExtractMBIDs_VorbisUppercaseKeysMiss(t *testing.T) {
// Real dhowden never produces uppercase Vorbis keys. Looking up
// "MUSICBRAINZ_ALBUMID" directly would find nothing, and every album
// would be skipped; this test keeps that lookup returning empty.
m := stubMeta{
format: tag.VORBIS,
raw: map[string]interface{}{
"MUSICBRAINZ_ALBUMID": "wrong-case",
"MUSICBRAINZ_ARTISTID": "wrong-case",
},
}
ids := ReadTagMBIDs(m)
a, ar := ids.Release, ids.Artist
if a != "" || ar != "" {
t.Errorf("uppercase Vorbis keys must not match dhowden output; got (%q, %q)", a, ar)
}
}
func TestExtractMBIDs_ID3v2StripsTrailingNUL(t *testing.T) {
// dhowden's readTextWithDescrFrame leaves the ID3v2.4 frame-
// terminator NUL on TXXX values. Postgres rejects NULs in text
// columns (SQLSTATE 22021), so we must strip them.
m := stubMeta{
format: tag.ID3v2_4,
raw: map[string]interface{}{
"TXXX": &tag.Comm{
Description: "MusicBrainz Album Id",
Text: "abc-123\x00",
},
"TXXX_0": &tag.Comm{
Description: "MusicBrainz Artist Id",
Text: "def-456\x00",
},
},
}
ids := ReadTagMBIDs(m)
a, ar := ids.Release, ids.Artist
if a != "abc-123" || ar != "def-456" {
t.Errorf("got (%q, %q), want trailing NUL stripped", a, ar)
}
}
func TestExtractMBIDs_ID3v2MultiValueTakesFirst(t *testing.T) {
// Some Picard configs emit multi-value TXXX:MusicBrainz Artist Id
// for collaborations, NUL-separated. Minstrel uses the primary
// release artist for MBCAA, so first wins.
m := stubMeta{
format: tag.ID3v2_4,
raw: map[string]interface{}{
"TXXX": &tag.Comm{
Description: "MusicBrainz Artist Id",
Text: "primary-mbid\x00collab-mbid",
},
},
}
ar := ReadTagMBIDs(m).Artist
if ar != "primary-mbid" {
t.Errorf("got %q, want %q", ar, "primary-mbid")
}
}
func TestCleanMBID_OnlyNULReturnsEmpty(t *testing.T) {
// Defensive: a TXXX value that is purely NULs (or empty after
// trimming) must round-trip to empty so the caller skips the row
// instead of writing a NUL-only string to Postgres.
if got := cleanMBID("\x00\x00"); got != "" {
t.Errorf("got %q, want empty", got)
}
if got := cleanMBID(""); got != "" {
t.Errorf("got %q, want empty", got)
}
}
// The release-group id is read beside the release id, from each
// format's own key, and the two are never confused.
func TestExtractReleaseGroupMBID(t *testing.T) {
cases := []struct {
// ReadTagMBIDs reads each MusicBrainz id from each format's own Picard key,
// in dhowden/tag's Raw() shape for that format: Vorbis keys lowercased, ID3
// TXXX frames under "TXXX"/"TXXX_N" with the Picard name in the Description,
// MP4 freeform atoms under their bare name. The release and the release
// group, and the recording and the release track, are never confused.
func TestReadTagMBIDs(t *testing.T) {
all := TagMBIDs{Release: "rel-1", Artist: "ar-1", AlbumArtist: "aa-1", ReleaseGroup: "rg-1", Recording: "rec-1"}
txxx := func(name, text string) *tag.Comm { return &tag.Comm{Description: name, Text: text} }
for _, tc := range []struct {
name string
meta stubMeta
want TagMBIDs
}{
{"vorbis", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{
"musicbrainz_albumid": "release-1",
"musicbrainz_releasegroupid": "group-1",
}}},
"musicbrainz_albumid": "rel-1", "musicbrainz_artistid": "ar-1", "musicbrainz_albumartistid": "aa-1",
"musicbrainz_releasegroupid": "rg-1",
// Picard calls the recording MUSICBRAINZ_TRACKID in Vorbis, the
// name mbz gives the release track.
"musicbrainz_trackid": "rec-1", "musicbrainz_releasetrackid": "reltrack-1",
}}, all},
// dhowden leaves ID3v2.4's terminating NUL on TXXX values, and
// Postgres rejects NULs in text (SQLSTATE 22021).
{"id3v2", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{
"TXXX": &tag.Comm{Description: "MusicBrainz Album Id", Text: "release-1"},
"TXXX_0": &tag.Comm{Description: "MusicBrainz Release Group Id", Text: "group-1\x00"},
}}},
{"mp4", stubMeta{format: tag.MP4, raw: map[string]interface{}{
"MusicBrainz Album Id": "release-1",
"MusicBrainz Release Group Id": "group-1",
}}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := ReadTagMBIDs(c.meta).ReleaseGroup; got != "group-1" {
t.Errorf("release group = %q, want group-1", got)
}
if album := ReadTagMBIDs(c.meta).Release; album != "release-1" {
t.Errorf("album (release) = %q, want release-1", album)
}
})
}
none := stubMeta{format: tag.VORBIS, raw: map[string]interface{}{"musicbrainz_albumid": "release-1"}}
if got := ReadTagMBIDs(none).ReleaseGroup; got != "" {
t.Errorf("untagged release group = %q, want empty", got)
}
}
// Each format's recording id lands in Recording, and the release-track
// id never does. Picard calls the recording MUSICBRAINZ_TRACKID in Vorbis
// comments, the name mbz gives the release track.
func TestReadTagMBIDs_Recording(t *testing.T) {
cases := []struct {
name string
meta stubMeta
}{
{"vorbis", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{
"musicbrainz_trackid": "rec-1",
"musicbrainz_releasetrackid": "reltrack-1",
}}},
{"id3v2 ufid", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{
"TXXX": txxx("MusicBrainz Album Id", "rel-1\x00"),
"TXXX_0": txxx("MusicBrainz Artist Id", "ar-1"),
"TXXX_1": txxx("MusicBrainz Album Artist Id", "aa-1\x00"),
"TXXX_2": txxx("MusicBrainz Release Group Id", "rg-1\x00"),
"TXXX_3": txxx("MusicBrainz Release Track Id", "reltrack-1\x00"),
"UFID": &tag.UFID{Provider: "http://musicbrainz.org", Identifier: []byte("rec-1")},
"TXXX_0": &tag.Comm{Description: "MusicBrainz Release Track Id", Text: "reltrack-1\x00"},
}}},
}}, all},
{"mp4", stubMeta{format: tag.MP4, raw: map[string]interface{}{
"MusicBrainz Track Id": "rec-1",
"MusicBrainz Release Track Id": "reltrack-1",
}}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := ReadTagMBIDs(c.meta).Recording; got != "rec-1" {
t.Errorf("recording = %q, want rec-1", got)
"MusicBrainz Album Id": "rel-1", "MusicBrainz Artist Id": "ar-1", "MusicBrainz Album Artist Id": "aa-1",
"MusicBrainz Release Group Id": "rg-1", "MusicBrainz Track Id": "rec-1", "MusicBrainz Release Track Id": "reltrack-1",
}}, all},
{"untagged", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{}}, TagMBIDs{}},
// dhowden never produces uppercase Vorbis keys; a lookup by the
// uppercase name would find nothing in a real file.
{"uppercase vorbis keys", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{
"MUSICBRAINZ_ALBUMID": "wrong-case", "MUSICBRAINZ_ARTISTID": "wrong-case",
}}, TagMBIDs{}},
{"a vorbis release track is not a recording", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{
"musicbrainz_releasetrackid": "reltrack-1",
}}, TagMBIDs{}},
// Some Picard configs write collaborations NUL-separated; Minstrel
// uses the primary artist, so the first value wins.
{"id3 multi-value takes the first", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{
"TXXX": txxx("MusicBrainz Artist Id", "primary-mbid\x00collab-mbid"),
}}, TagMBIDs{Artist: "primary-mbid"}},
// A value that is only NULs is absent, not a NUL string for Postgres.
{"id3 value of only NULs", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{
"TXXX": txxx("MusicBrainz Album Id", "\x00\x00"),
}}, TagMBIDs{}},
} {
t.Run(tc.name, func(t *testing.T) {
if got := ReadTagMBIDs(tc.meta); got != tc.want {
t.Errorf("got %+v\nwant %+v", got, tc.want)
}
})
}
// A Vorbis file carrying only the release-track id has no recording id.
only := stubMeta{format: tag.VORBIS, raw: map[string]interface{}{"musicbrainz_releasetrackid": "reltrack-1"}}
if got := ReadTagMBIDs(only).Recording; got != "" {
t.Errorf("release track only: recording = %q, want empty", got)
}
}
// A Vorbis TRACKNUMBER of "3/20" is track 3: dhowden/tag reads it as 0.
@@ -259,32 +109,3 @@ func TestReadTrackAndDisc(t *testing.T) {
}
}
}
// The album artist's id is read from each format's Picard name.
func TestReadTagMBIDs_AlbumArtist(t *testing.T) {
cases := []struct {
name string
meta stubMeta
}{
{"vorbis", stubMeta{format: tag.VORBIS, raw: map[string]interface{}{
"musicbrainz_albumartistid": "aa-1",
"musicbrainz_artistid": "ar-1",
}}},
{"id3v2", stubMeta{format: tag.ID3v2_4, raw: map[string]interface{}{
"TXXX": &tag.Comm{Description: "MusicBrainz Album Artist Id", Text: "aa-1\x00"},
"TXXX_0": &tag.Comm{Description: "MusicBrainz Artist Id", Text: "ar-1"},
}}},
{"mp4", stubMeta{format: tag.MP4, raw: map[string]interface{}{
"MusicBrainz Album Artist Id": "aa-1",
"MusicBrainz Artist Id": "ar-1",
}}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
ids := ReadTagMBIDs(c.meta)
if ids.AlbumArtist != "aa-1" || ids.Artist != "ar-1" {
t.Errorf("album artist = %q, artist = %q; want aa-1 and ar-1", ids.AlbumArtist, ids.Artist)
}
})
}
}
+62 -223
View File
@@ -6,8 +6,6 @@ import (
"errors"
"testing"
"github.com/jackc/pgx/v5/pgtype"
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
)
@@ -72,234 +70,75 @@ const (
newPath = "/music/Lincoln Yard/Minutes to Noon/04 - Bleed It Out.mp3"
)
func TestAdoptMovedTrack_MatchesByMbid(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(7, oldPath)}, adoptRows: 1}
if !s.adoptMovedTrack(context.Background(), q, newPath, audioHash(1), "rec-mbid") {
t.Fatal("expected the moved track to be adopted")
}
if len(q.adopted) != 1 || q.adopted[0].ID != testUUID(7) || q.adopted[0].FilePath != newPath {
t.Fatalf("adopted = %+v, want row 7 at %q", q.adopted, newPath)
}
// MBID matched, so the weaker signal should not have been consulted.
if len(q.hashQueried) != 0 {
t.Errorf("queried the audio hash despite an MBID match")
}
}
func TestAdoptMovedTrack_FallsBackToAudioHash(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{hash: audioHash(3), byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(3, oldPath)}, adoptRows: 1}
// No MBID: an untagged file, which is exactly what the fallback is for.
if !s.adoptMovedTrack(context.Background(), q, newPath, audioHash(3), "") {
t.Fatal("expected adoption via the audio hash")
}
if len(q.mbidQueried) != 0 {
t.Errorf("queried by MBID with no MBID available")
}
if len(q.hashQueried) != 1 || !bytes.Equal(q.hashQueried[0], audioHash(3)) {
t.Fatalf("hash queried = %x, want exactly the file's hash", q.hashQueried)
}
if len(q.adopted) != 1 || q.adopted[0].ID != testUUID(3) {
t.Errorf("adopted = %+v, want row 3", q.adopted)
}
}
// An unrelated file that happens to share a size and a duration with a missing
// track is not adopted. Size and duration are not inputs at all; only the
// audio itself can match, and a different recording has a different hash.
func TestAdoptMovedTrack_DifferentAudioIsNotAdopted(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{hash: audioHash(0xAA), byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1}
if s.adoptMovedTrack(context.Background(), q, newPath, audioHash(0xBB), "") {
t.Fatal("adopted a missing track whose audio differs")
}
if len(q.adopted) != 0 {
t.Errorf("adopted = %+v, want none", q.adopted)
}
}
// Two missing rows carrying the same recording MBID means real duplicates.
// Adopting one arbitrarily would attach this file's future history to a coin
// flip, so it must insert fresh instead.
func TestAdoptMovedTrack_RefusesAmbiguousMbidMatch(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{
mbidRow(1, "/music/a.mp3"),
mbidRow(2, "/music/b.mp3"),
}, adoptRows: 1}
if s.adoptMovedTrack(context.Background(), q, newPath, nil, "rec-mbid") {
t.Fatal("expected refusal on an ambiguous MBID match")
}
if len(q.adopted) != 0 {
t.Errorf("adopted despite ambiguity: %+v", q.adopted)
}
}
// An ambiguous MBID may still be resolvable by the audio hash, which is a
// narrower signal — so falling through is allowed to succeed.
func TestAdoptMovedTrack_AmbiguousMbidFallsThroughToAudioHash(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{
byMbid: []dbq.FindMissingTrackByMbidRow{
mbidRow(1, "/music/a.mp3"),
mbidRow(2, "/music/b.mp3"),
},
hash: audioHash(2),
byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(2, "/music/b.mp3")},
adoptRows: 1,
}
if !s.adoptMovedTrack(context.Background(), q, newPath, audioHash(2), "rec-mbid") {
t.Fatal("expected the audio hash to disambiguate")
}
if len(q.adopted) != 1 || q.adopted[0].ID != testUUID(2) {
t.Errorf("adopted = %+v, want row 2", q.adopted)
}
}
// Two missing tracks with identical audio are duplicates of each other; a new
// file matching both cannot be assigned to either.
func TestAdoptMovedTrack_RefusesAmbiguousAudioHashMatch(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{hash: audioHash(5), byHash: []dbq.FindMissingTrackByAudioHashRow{
hashRow(1, "/music/a.mp3"),
hashRow(2, "/music/b.mp3"),
}, adoptRows: 1}
if s.adoptMovedTrack(context.Background(), q, newPath, audioHash(5), "") {
t.Fatal("expected refusal on an ambiguous audio-hash match")
}
if len(q.adopted) != 0 {
t.Errorf("adopted despite ambiguity: %+v", q.adopted)
}
}
// No hash means it could not be taken. An empty hash must never be looked up:
// every unhashable file would pair with every other.
func TestAdoptMovedTrack_SkipsAudioHashWhenAbsent(t *testing.T) {
for name, hash := range map[string][]byte{"nil": nil, "empty": {}} {
t.Run(name, func(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{hash: hash, byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1}
if s.adoptMovedTrack(context.Background(), q, newPath, hash, "") {
t.Error("adopted without an audio hash")
}
if len(q.hashQueried) != 0 {
t.Error("looked up an absent audio hash")
}
})
}
}
func TestAdoptMovedTrack_NoCandidates(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{adoptRows: 1}
if s.adoptMovedTrack(context.Background(), q, newPath, audioHash(9), "rec-mbid") {
t.Fatal("expected no adoption when nothing matches")
}
if len(q.adopted) != 0 {
t.Errorf("adopted with no candidates: %+v", q.adopted)
}
}
// The row's mark was cleared between lookup and update — another file adopted
// it first. AdoptTrackPath's `missing_since IS NOT NULL` predicate reports 0
// rows.
func TestAdoptMovedTrack_LostRaceReportsNotAdopted(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{
byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(5, oldPath)},
adoptRows: 0,
}
if s.adoptMovedTrack(context.Background(), q, newPath, audioHash(5), "rec-mbid") {
t.Fatal("expected not-adopted when the update matched no rows")
}
}
// Failing to detect a move must never fail the file: the caller falls back to
// inserting a fresh row.
func TestAdoptMovedTrack_ToleratesQueryErrors(t *testing.T) {
// A new file is adopted as a missing track that moved when its recording MBID
// names exactly one missing track, or failing that its audio hash does. Size
// and duration are not inputs: only identity can match. Anything ambiguous, or
// any failure, inserts the file fresh instead: adopting by coin flip would
// attach the wrong history, and failing to detect a move must never fail the
// file.
func TestAdoptMovedTrack(t *testing.T) {
sentinel := errors.New("db down")
tests := []struct {
twoMbid := []dbq.FindMissingTrackByMbidRow{mbidRow(1, "/music/a.mp3"), mbidRow(2, "/music/b.mp3")}
for _, tc := range []struct {
name string
q *fakeAdopter
hash []byte
mbid string
// want is the adopted row's id byte; 0 means nothing adopted.
want byte
// noHashLookup: the audio hash must not be looked up at all.
noHashLookup bool
}{
{"mbid lookup fails", &fakeAdopter{mbidErr: sentinel}},
{"audio hash lookup fails", &fakeAdopter{hashErr: sentinel}},
{"adopt fails", &fakeAdopter{
byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(1, oldPath)},
adoptErr: sentinel,
}},
}
for _, tc := range tests {
{name: "by MBID, without consulting the hash", hash: audioHash(1), mbid: "rec-mbid", want: 7, noHashLookup: true,
q: &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(7, oldPath)}, adoptRows: 1}},
{name: "by audio hash when untagged", hash: audioHash(3), want: 3,
q: &fakeAdopter{hash: audioHash(3), byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(3, oldPath)}, adoptRows: 1}},
{name: "different audio", hash: audioHash(0xBB),
q: &fakeAdopter{hash: audioHash(0xAA), byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1}},
{name: "two missing tracks share the MBID", mbid: "rec-mbid",
q: &fakeAdopter{byMbid: twoMbid, adoptRows: 1}},
{name: "an ambiguous MBID settled by the hash", hash: audioHash(2), mbid: "rec-mbid", want: 2,
q: &fakeAdopter{byMbid: twoMbid, hash: audioHash(2),
byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(2, "/music/b.mp3")}, adoptRows: 1}},
{name: "two missing tracks share the audio", hash: audioHash(5),
q: &fakeAdopter{hash: audioHash(5), byHash: []dbq.FindMissingTrackByAudioHashRow{
hashRow(1, "/music/a.mp3"), hashRow(2, "/music/b.mp3")}, adoptRows: 1}},
// Every unhashable file would pair with every other.
{name: "no hash taken (nil)", hash: nil, noHashLookup: true,
q: &fakeAdopter{hash: nil, byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1}},
{name: "no hash taken (empty)", hash: []byte{}, noHashLookup: true,
q: &fakeAdopter{hash: []byte{}, byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(1, oldPath)}, adoptRows: 1}},
{name: "no candidates", hash: audioHash(9), mbid: "rec-mbid",
q: &fakeAdopter{adoptRows: 1}},
// Another file adopted the row between lookup and update; the
// missing_since predicate matches no row.
{name: "lost the race", hash: audioHash(5), mbid: "rec-mbid",
q: &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(5, oldPath)}, adoptRows: 0}},
{name: "the hash lookup fails", hash: audioHash(1), mbid: "rec-mbid",
q: &fakeAdopter{hashErr: sentinel}},
{name: "the adopt fails", hash: audioHash(1), mbid: "rec-mbid",
q: &fakeAdopter{byMbid: []dbq.FindMissingTrackByMbidRow{mbidRow(1, oldPath)}, adoptErr: sentinel}},
{name: "an MBID lookup error still tries the hash", hash: audioHash(9), mbid: "rec-mbid", want: 9,
q: &fakeAdopter{mbidErr: sentinel, hash: audioHash(9),
byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(9, oldPath)}, adoptRows: 1}},
} {
t.Run(tc.name, func(t *testing.T) {
s := testScanner(t)
if s.adoptMovedTrack(context.Background(), tc.q, newPath, audioHash(1), "rec-mbid") {
t.Error("reported adoption despite a query error")
got := s.adoptMovedTrack(context.Background(), tc.q, newPath, tc.hash, tc.mbid)
if got != (tc.want != 0) {
t.Fatalf("adopted = %v, want %v", got, tc.want != 0)
}
if tc.want != 0 {
if n := len(tc.q.adopted); n == 0 || tc.q.adopted[n-1].ID != testUUID(tc.want) || tc.q.adopted[n-1].FilePath != newPath {
t.Errorf("adopted %+v, want row %d at %q", tc.q.adopted, tc.want, newPath)
}
}
if tc.mbid == "" && len(tc.q.mbidQueried) != 0 {
t.Error("queried by MBID with no MBID available")
}
if tc.noHashLookup && len(tc.q.hashQueried) != 0 {
t.Errorf("looked up the audio hash: %x", tc.q.hashQueried)
}
})
}
}
// A failed MBID lookup must not stop the audio hash from being tried.
func TestAdoptMovedTrack_MbidErrorStillTriesAudioHash(t *testing.T) {
s := testScanner(t)
q := &fakeAdopter{
mbidErr: errors.New("db hiccup"),
hash: audioHash(9),
byHash: []dbq.FindMissingTrackByAudioHashRow{hashRow(9, oldPath)},
adoptRows: 1,
}
if !s.adoptMovedTrack(context.Background(), q, newPath, audioHash(9), "rec-mbid") {
t.Fatal("expected the audio hash to be tried after an MBID lookup error")
}
if len(q.adopted) != 1 || q.adopted[0].ID != testUUID(9) {
t.Errorf("adopted = %+v, want row 9", q.adopted)
}
}
func TestUniqueMatch(t *testing.T) {
s := testScanner(t)
if _, ok := s.uniqueMatch(nil, newPath, "mbid"); ok {
t.Error("empty candidate set matched")
}
c, ok := s.uniqueMatch([]candidate{{id: testUUID(4), filePath: oldPath}}, newPath, "mbid")
if !ok {
t.Fatal("single candidate did not match")
}
if c.id != testUUID(4) || c.filePath != oldPath {
t.Errorf("candidate = %+v, want id 4 at %q", c, oldPath)
}
if _, ok := s.uniqueMatch([]candidate{
{id: testUUID(1)}, {id: testUUID(2)},
}, newPath, "mbid"); ok {
t.Error("multiple candidates matched")
}
}
func TestRowConverters(t *testing.T) {
got := rowsFromMbid([]dbq.FindMissingTrackByMbidRow{mbidRow(1, "/a"), mbidRow(2, "/b")})
if len(got) != 2 || got[0].id != testUUID(1) || got[1].filePath != "/b" {
t.Errorf("rowsFromMbid = %+v", got)
}
got = rowsFromAudioHash([]dbq.FindMissingTrackByAudioHashRow{hashRow(3, "/c")})
if len(got) != 1 || got[0].id != testUUID(3) || got[0].filePath != "/c" {
t.Errorf("rowsFromAudioHash = %+v", got)
}
}
// pgtype.UUID zero value must not be mistaken for a real id.
func TestUniqueMatch_ZeroUUIDNotValid(t *testing.T) {
var zero pgtype.UUID
if zero.Valid {
t.Fatal("zero pgtype.UUID should not be Valid")
}
}
+52 -151
View File
@@ -2,7 +2,6 @@ package library
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
@@ -99,13 +98,15 @@ func testScanner(t *testing.T, roots ...string) *Scanner {
}
}
// A row the walk did not see is marked missing, and the mark reaches clients
// as a change row. Without one the mark is invisible: /api/library/sync is a
// change-log feed, so a plain UPDATE never reaches anyone.
func TestReconcileMissing_MarksRowsTheWalkDidNotSee(t *testing.T) {
root := populatedRoot(t)
s := testScanner(t, root)
// 10 rows with 2 absent — 20%, deliberately under missingMarkMaxFraction so
// this exercises marking rather than the cap. (An earlier version of this
// test used 2-of-4 and was really testing the guard by accident.)
// this exercises marking rather than the cap.
rows := make([]dbq.ListTrackPathsForReconcileRow, 0, 10)
seen := map[string]struct{}{}
for i := 0; i < 10; i++ {
@@ -121,11 +122,8 @@ func TestReconcileMissing_MarksRowsTheWalkDidNotSee(t *testing.T) {
if err := s.reconcileMissing(context.Background(), q, seen, &stats); err != nil {
t.Fatalf("reconcile: %v", err)
}
if len(q.marked) != 2 {
t.Fatalf("marked %d rows, want 2", len(q.marked))
}
if q.marked[0] != testUUID(0) || q.marked[1] != testUUID(1) {
t.Errorf("marked the wrong rows: %v", q.marked)
if len(q.marked) != 2 || q.marked[0] != testUUID(0) || q.marked[1] != testUUID(1) {
t.Fatalf("marked %v, want rows 0 and 1", q.marked)
}
if stats.Missing != 2 {
t.Errorf("stats.Missing = %d, want 2", stats.Missing)
@@ -133,8 +131,20 @@ func TestReconcileMissing_MarksRowsTheWalkDidNotSee(t *testing.T) {
if len(q.cleared) != 0 {
t.Errorf("cleared %d rows, want 0", len(q.cleared))
}
if len(q.loggedChanges) != 1 {
t.Fatalf("want one batch of change rows, got %d", len(q.loggedChanges))
}
got := q.loggedChanges[0]
// Upsert, not delete: the track still exists and keeps its history. A
// delete would tell clients to drop the row, and a missing file is
// expected to come back.
if got.EntityType != "track" || got.Op != "upsert" || len(got.EntityIds) != 2 {
t.Errorf("change rows = (%s, %s, %d ids), want an upsert of both tracks", got.EntityType, got.Op, len(got.EntityIds))
}
}
// A file coming back clears its mark and reaches clients too, or a restored
// track stays greyed out on every device until something unrelated touches it.
func TestReconcileMissing_ClearsRowsWhoseFileReturned(t *testing.T) {
root := populatedRoot(t)
s := testScanner(t, root)
@@ -160,6 +170,9 @@ func TestReconcileMissing_ClearsRowsWhoseFileReturned(t *testing.T) {
if len(q.marked) != 0 {
t.Errorf("marked %d rows, want 0", len(q.marked))
}
if len(q.loggedChanges) != 1 || q.loggedChanges[0].Op != "upsert" {
t.Errorf("change rows = %+v, want one upsert batch for the restored track", q.loggedChanges)
}
}
// An already-marked row must not be re-marked: the timestamp is the "how long
@@ -242,67 +255,40 @@ func TestReconcileMissing_ClearsEvenWhenMarkCapTrips(t *testing.T) {
}
}
func TestReconcileMissing_RefusesOnEmptyWalk(t *testing.T) {
root := populatedRoot(t)
s := testScanner(t, root)
q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{
row(1, "/music/a.mp3", false),
}}
var stats Stats
if err := s.reconcileMissing(context.Background(), q, map[string]struct{}{}, &stats); err == nil {
t.Fatal("expected refusal when the walk saw no files")
}
if len(q.marked) != 0 {
t.Errorf("marked rows on an empty walk: %v", q.marked)
}
}
// The unmounted-volume case: the configured root doesn't exist at all.
func TestReconcileMissing_RefusesWhenRootMissing(t *testing.T) {
s := testScanner(t, filepath.Join(t.TempDir(), "not-mounted"))
q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{
row(1, "/music/a.mp3", false),
}}
var stats Stats
if err := s.reconcileMissing(context.Background(), q, map[string]struct{}{"/x": {}}, &stats); err == nil {
t.Fatal("expected refusal when a scan root is absent")
}
if len(q.marked) != 0 {
t.Errorf("marked rows with an absent root: %v", q.marked)
}
}
// A mount point that exists but has nothing mounted on it: os.Stat succeeds on
// the bare directory, which is why emptiness is checked separately.
func TestReconcileMissing_RefusesWhenRootEmpty(t *testing.T) {
s := testScanner(t, t.TempDir())
q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{
row(1, "/music/a.mp3", false),
}}
var stats Stats
if err := s.reconcileMissing(context.Background(), q, map[string]struct{}{"/x": {}}, &stats); err == nil {
t.Fatal("expected refusal when a scan root is empty")
}
}
// Several roots, one detached. Marking must not proceed on partial evidence
// just because the other roots looked fine.
func TestReconcileMissing_RefusesWhenAnyRootMissing(t *testing.T) {
good := populatedRoot(t)
s := testScanner(t, good, filepath.Join(t.TempDir(), "detached"))
q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{
row(1, "/music/a.mp3", false),
}}
var stats Stats
if err := s.reconcileMissing(context.Background(), q, map[string]struct{}{"/x": {}}, &stats); err == nil {
t.Fatal("expected refusal when one of several roots is absent")
// A walk that cannot be trusted marks nothing: one that saw no files, a root
// that is not mounted (absent), a mount point with nothing on it (present but
// empty, which os.Stat alone would pass), one detached root among several,
// or no roots configured at all.
func TestReconcileMissing_RefusesWhenAVolumeLooksAbsent(t *testing.T) {
seenSomething := map[string]struct{}{"/x": {}}
for _, tc := range []struct {
name string
roots func(t *testing.T) []string
seen map[string]struct{}
}{
{"the walk saw no files", func(t *testing.T) []string { return []string{populatedRoot(t)} }, map[string]struct{}{}},
{"a root is absent", func(t *testing.T) []string { return []string{filepath.Join(t.TempDir(), "not-mounted")} }, seenSomething},
{"a root is empty", func(t *testing.T) []string { return []string{t.TempDir()} }, seenSomething},
{"one of several roots is absent", func(t *testing.T) []string {
return []string{populatedRoot(t), filepath.Join(t.TempDir(), "detached")}
}, seenSomething},
{"no roots configured", func(*testing.T) []string { return nil }, seenSomething},
} {
t.Run(tc.name, func(t *testing.T) {
s := testScanner(t, tc.roots(t)...)
q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{row(1, "/music/a.mp3", false)}}
var stats Stats
if err := s.reconcileMissing(context.Background(), q, tc.seen, &stats); err == nil {
t.Fatal("reconcile went ahead; want a refusal")
}
if len(q.marked) != 0 {
t.Errorf("marked rows: %v", q.marked)
}
})
}
}
// A fresh install has no tracks yet; its first scan must not fail.
func TestReconcileMissing_NoRowsIsNotAnError(t *testing.T) {
root := populatedRoot(t)
s := testScanner(t, root)
@@ -313,88 +299,3 @@ func TestReconcileMissing_NoRowsIsNotAnError(t *testing.T) {
t.Fatalf("empty library should reconcile cleanly, got %v", err)
}
}
func TestReconcileMissing_PropagatesListError(t *testing.T) {
root := populatedRoot(t)
s := testScanner(t, root)
sentinel := errors.New("boom")
q := &fakeReconciler{listErr: sentinel}
var stats Stats
err := s.reconcileMissing(context.Background(), q, map[string]struct{}{"/x": {}}, &stats)
if !errors.Is(err, sentinel) {
t.Fatalf("err = %v, want it to wrap %v", err, sentinel)
}
}
func TestVerifyRootsPresent_NoRootsConfigured(t *testing.T) {
s := testScanner(t)
if err := s.verifyRootsPresent(); err == nil {
t.Fatal("expected an error with no scan roots configured")
}
}
// Without a change row the mark is invisible to every client:
// /api/library/sync is a change-log feed, so a plain UPDATE never reaches
// anyone, and the wire field would exist with nothing ever telling a client to
// re-read the track.
func TestReconcileMissing_MarkingEmitsSyncChanges(t *testing.T) {
s := testScanner(t, populatedRoot(t))
// 10 rows, 2 absent — under the cap, so this exercises marking.
rows := make([]dbq.ListTrackPathsForReconcileRow, 0, 10)
seen := map[string]struct{}{}
for i := 0; i < 10; i++ {
path := fmt.Sprintf("/music/track-%02d.mp3", i)
rows = append(rows, row(byte(i), path, false))
if i >= 2 {
seen[path] = struct{}{}
}
}
q := &fakeReconciler{rows: rows}
var stats Stats
if err := s.reconcileMissing(context.Background(), q, seen, &stats); err != nil {
t.Fatalf("reconcile: %v", err)
}
if len(q.loggedChanges) != 1 {
t.Fatalf("want one batch of change rows, got %d", len(q.loggedChanges))
}
got := q.loggedChanges[0]
if got.EntityType != "track" {
t.Errorf("entity_type = %q, want track", got.EntityType)
}
// Upsert, not delete: the track still exists and keeps its history. A
// delete would tell clients to drop the row, and a missing file is
// expected to come back.
if got.Op != "upsert" {
t.Errorf("op = %q, want upsert — the row survives, only its state changed", got.Op)
}
if len(got.EntityIds) != 2 {
t.Errorf("want both missing tracks logged, got %d ids", len(got.EntityIds))
}
}
// A file coming back must reach clients too, or a restored track stays
// greyed out on every device until something unrelated touches it.
func TestReconcileMissing_RestoringEmitsSyncChanges(t *testing.T) {
s := testScanner(t, populatedRoot(t))
q := &fakeReconciler{rows: []dbq.ListTrackPathsForReconcileRow{
row(1, "/music/back.mp3", true),
}}
var stats Stats
if err := s.reconcileMissing(
context.Background(), q, map[string]struct{}{"/music/back.mp3": {}}, &stats,
); err != nil {
t.Fatalf("reconcile: %v", err)
}
if len(q.loggedChanges) != 1 {
t.Fatalf("a restored file must produce a change row, got %d batches", len(q.loggedChanges))
}
if q.loggedChanges[0].Op != "upsert" {
t.Errorf("op = %q, want upsert", q.loggedChanges[0].Op)
}
}
-15
View File
@@ -142,21 +142,6 @@ func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) {
}
}
// With auto-resolve off the resolver links nothing.
func TestCrossReleaseLinkNeedsAutoResolve_Integration(t *testing.T) {
pool := dbtest.Pool(t)
ctx := context.Background()
q := dbq.New(pool)
f := newSongLinkFixture(t, pool)
if _, err := ResolveDuplicates(ctx, pool, nil, false); err != nil {
t.Fatal(err)
}
keys := songKeys(t, q, f.single.ID, f.albumCut.ID)
if keys[0] == keys[1] {
t.Error("linked with auto-resolve off")
}
}
// A merge keeps the removed copy's link to the song on another release,
// whichever copy's id names the song. That copy has no song_id of its own,
// and its link must survive whichever way the random ids fall, including when
+30 -79
View File
@@ -25,22 +25,29 @@ func newTestPublisher(t *testing.T, flushEvery int, flushPeriod time.Duration) (
return pub, &marshalCalls, &persistCalls
}
func TestStagePublisher_Tick_FlushesAtCountThreshold(t *testing.T) {
pub, _, persists := newTestPublisher(t, 3, 1*time.Hour) // huge time so only count fires
for i := 0; i < 3; i++ {
pub.Tick()
// Progress is persisted every flushEvery ticks, and a Flush persists at once
// and starts the count again.
func TestStagePublisher_FlushesEveryNTicksAndOnFlush(t *testing.T) {
pub, _, persists := newTestPublisher(t, 5, time.Hour) // a long period, so only the count fires
tick := func(n int, want int32) {
t.Helper()
for range n {
pub.Tick()
}
if got := persists.Load(); got != want {
t.Fatalf("persists = %d, want %d", got, want)
}
}
if persists.Load() != 1 {
t.Errorf("persists after 3 ticks = %d, want 1", persists.Load())
tick(5, 1)
tick(4, 1)
if err := pub.Flush(); err != nil {
t.Fatal(err)
}
for i := 0; i < 3; i++ {
pub.Tick()
}
if persists.Load() != 2 {
t.Errorf("persists after 6 ticks = %d, want 2", persists.Load())
if got := persists.Load(); got != 2 {
t.Fatalf("persists after Flush = %d, want 2", got)
}
tick(4, 2) // the count restarted at the Flush
tick(1, 3)
}
func TestStagePublisher_Tick_FlushesOnTimeout(t *testing.T) {
@@ -58,78 +65,22 @@ func TestStagePublisher_Tick_FlushesOnTimeout(t *testing.T) {
}
}
func TestStagePublisher_Flush_AlwaysPersists(t *testing.T) {
pub, _, persists := newTestPublisher(t, 1000, 1*time.Hour)
pub.Tick() // doesn't flush — count too low, time too long
if err := pub.Flush(); err != nil {
t.Errorf("Flush() err = %v, want nil", err)
}
if persists.Load() != 1 {
t.Errorf("persists after Flush = %d, want 1", persists.Load())
}
}
func TestStagePublisher_Tick_SwallowsPersistErrors(t *testing.T) {
persistCalls := atomic.Int32{}
pub := newStagePublisher(context.Background(), 1, 1*time.Hour,
// A failed persist doesn't stop later ticks from persisting (a scan carries
// on through a database hiccup), but Flush, the final write, reports it.
func TestStagePublisher_PersistErrors(t *testing.T) {
wantErr := errors.New("simulated DB failure")
var calls atomic.Int32
pub := newStagePublisher(context.Background(), 1, time.Hour,
func() []byte { return []byte(`{}`) },
func(_ []byte) error {
persistCalls.Add(1)
return errors.New("simulated DB failure")
},
func([]byte) error { calls.Add(1); return wantErr },
)
// Ticks should not panic, should keep firing the persist (which keeps
// erroring).
for i := 0; i < 5; i++ {
for range 5 {
pub.Tick()
}
if persistCalls.Load() != 5 {
t.Errorf("persistCalls after 5 ticks = %d, want 5 (errors should not stop subsequent ticks)", persistCalls.Load())
if calls.Load() != 5 {
t.Errorf("persist calls after 5 ticks = %d, want 5", calls.Load())
}
}
func TestStagePublisher_Flush_PropagatesPersistError(t *testing.T) {
wantErr := errors.New("DB exploded")
pub := newStagePublisher(context.Background(), 1, 1*time.Hour,
func() []byte { return []byte(`{}`) },
func(_ []byte) error { return wantErr },
)
if err := pub.Flush(); !errors.Is(err, wantErr) {
t.Errorf("Flush() err = %v, want %v", err, wantErr)
}
}
func TestStagePublisher_FlushResetsCounters(t *testing.T) {
pub, _, persists := newTestPublisher(t, 5, 1*time.Hour)
for i := 0; i < 4; i++ {
pub.Tick()
}
if persists.Load() != 0 {
t.Errorf("persists at 4 ticks = %d, want 0", persists.Load())
}
if err := pub.Flush(); err != nil {
t.Fatal(err)
}
if persists.Load() != 1 {
t.Fatalf("persists after Flush = %d, want 1", persists.Load())
}
// After Flush, the counter resets — need 5 more ticks to flush again.
for i := 0; i < 4; i++ {
pub.Tick()
}
if persists.Load() != 1 {
t.Errorf("persists after Flush + 4 ticks = %d, want 1 (counter should have reset)", persists.Load())
}
pub.Tick() // 5th tick after reset → flush
if persists.Load() != 2 {
t.Errorf("persists after Flush + 5 ticks = %d, want 2", persists.Load())
}
}
+56 -118
View File
@@ -2,20 +2,18 @@ package library
import (
"context"
"errors"
"io"
"log/slog"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Fabled-Sword/minstrel/internal/dbtest"
)
// triggerTestPool returns a pool against MINSTREL_TEST_DATABASE_URL or skips.
// triggerTestPool opens the test database with no scan runs recorded.
func triggerTestPool(t *testing.T) *pgxpool.Pool {
t.Helper()
pool := dbtest.Open(t)
@@ -31,121 +29,61 @@ func quietLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
func TestTryStartScan_NoInFlight_Starts(t *testing.T) {
pool := triggerTestPool(t)
// A scan starts unless another is running. A run that has been "running" for
// two hours is a crashed one: it is closed as reaped and a new scan starts.
func TestTryStartScan_StartsUnlessAFreshScanIsRunning(t *testing.T) {
for _, tc := range []struct {
name string
inFlightAge string // "" seeds no run
wantStarted bool
}{
{"nothing running", "", true},
{"a fresh run", "0 seconds", false},
{"a stale run", "2 hours", true},
} {
t.Run(tc.name, func(t *testing.T) {
pool := triggerTestPool(t)
ctx := context.Background()
var seeded pgtype.UUID
if tc.inFlightAge != "" {
if err := pool.QueryRow(ctx,
`INSERT INTO scan_runs (started_at) VALUES (now() - $1::interval) RETURNING id`, tc.inFlightAge,
).Scan(&seeded); err != nil {
t.Fatalf("seed: %v", err)
}
}
started, existing, err := TryStartScan(
context.Background(), pool,
nil, nil, // scanner/enricher: nil OK because the goroutine that uses them is detached and we don't await it.
quietLogger(), RunScanConfig{},
)
if err != nil {
t.Fatalf("err = %v, want nil", err)
}
if !started {
t.Errorf("started = false, want true")
}
if existing != nil {
t.Errorf("existing = %v, want nil", existing)
}
// Give the detached goroutine a moment.
time.Sleep(50 * time.Millisecond)
}
func TestTryStartScan_FreshInFlight_Skips(t *testing.T) {
pool := triggerTestPool(t)
// Seed a fresh in-flight row.
var rowID pgtype.UUID
if err := pool.QueryRow(context.Background(),
`INSERT INTO scan_runs (started_at) VALUES (now()) RETURNING id`,
).Scan(&rowID); err != nil {
t.Fatalf("seed: %v", err)
}
started, existing, err := TryStartScan(
context.Background(), pool,
nil, nil,
quietLogger(), RunScanConfig{},
)
if err != nil {
t.Fatalf("err = %v, want nil", err)
}
if started {
t.Errorf("started = true, want false")
}
if existing == nil {
t.Fatal("existing = nil, want non-nil")
}
if existing.ID != rowID {
t.Errorf("existing.ID = %v, want %v", existing.ID, rowID)
}
}
func TestTryStartScan_StaleInFlight_Reaps(t *testing.T) {
pool := triggerTestPool(t)
// Seed a stale in-flight row (started 2 hours ago).
var staleID pgtype.UUID
if err := pool.QueryRow(context.Background(),
`INSERT INTO scan_runs (started_at) VALUES (now() - interval '2 hours') RETURNING id`,
).Scan(&staleID); err != nil {
t.Fatalf("seed: %v", err)
}
started, existing, err := TryStartScan(
context.Background(), pool,
nil, nil,
quietLogger(), RunScanConfig{},
)
if err != nil {
t.Fatalf("err = %v, want nil", err)
}
if !started {
t.Errorf("started = false, want true (stale row should reap and proceed)")
}
if existing != nil {
t.Errorf("existing = %v, want nil", existing)
}
// Verify the stale row was reaped: finished_at non-NULL, error_message
// contains "reaped".
var finishedAt pgtype.Timestamptz
var errMsg *string
if err := pool.QueryRow(context.Background(),
`SELECT finished_at, error_message FROM scan_runs WHERE id = $1`, staleID,
).Scan(&finishedAt, &errMsg); err != nil {
t.Fatalf("verify reap: %v", err)
}
if !finishedAt.Valid {
t.Errorf("finished_at = NULL, want non-NULL after reap")
}
if errMsg == nil || *errMsg != "reaped (stale)" {
t.Errorf("error_message = %v, want 'reaped (stale)'", errMsg)
}
time.Sleep(50 * time.Millisecond)
}
func TestTryStartScan_DBError_Propagates(t *testing.T) {
pool := dbtest.Open(t)
pool.Close() // close immediately to force errors on subsequent queries
started, existing, err := TryStartScan(
context.Background(), pool,
nil, nil,
quietLogger(), RunScanConfig{},
)
if err == nil {
t.Errorf("err = nil, want non-nil for closed pool")
}
if errors.Is(err, pgx.ErrNoRows) {
t.Errorf("err is ErrNoRows; want a different DB error type")
}
if started {
t.Errorf("started = true, want false on DB error")
}
if existing != nil {
t.Errorf("existing = %v, want nil on DB error", existing)
// scanner/enricher nil: the goroutine that uses them is detached
// and not awaited.
started, existing, err := TryStartScan(ctx, pool, nil, nil, quietLogger(), RunScanConfig{})
if err != nil {
t.Fatalf("err = %v, want nil", err)
}
if started != tc.wantStarted {
t.Errorf("started = %v, want %v", started, tc.wantStarted)
}
if tc.wantStarted && existing != nil {
t.Errorf("existing = %v, want nil", existing)
}
if !tc.wantStarted && (existing == nil || existing.ID != seeded) {
t.Errorf("existing = %v, want the running row %v", existing, seeded)
}
if tc.name == "a stale run" {
var finishedAt pgtype.Timestamptz
var errMsg *string
if err := pool.QueryRow(ctx,
`SELECT finished_at, error_message FROM scan_runs WHERE id = $1`, seeded,
).Scan(&finishedAt, &errMsg); err != nil {
t.Fatalf("verify reap: %v", err)
}
if !finishedAt.Valid || errMsg == nil || *errMsg != "reaped (stale)" {
t.Errorf("stale row finished=%v message=%v, want closed as 'reaped (stale)'", finishedAt.Valid, errMsg)
}
}
if started {
// Give the detached goroutine a moment.
time.Sleep(50 * time.Millisecond)
}
})
}
}
+23 -74
View File
@@ -5,8 +5,6 @@ import (
"encoding/binary"
"strings"
"testing"
"github.com/dhowden/tag"
)
// vorbisComment builds a comment block: vendor, count, then each "KEY=value".
@@ -161,28 +159,6 @@ func genreFields(values ...string) []string {
return out
}
// Shaped like a real multi-genre FLAC:
// eight GENRE fields, of which dhowden/tag keeps the last.
func TestExtractGenres_FLACRepeatedFields(t *testing.T) {
data := buildFLAC(false, append([]string{"TITLE=Eons"}, genreFields(lifeForms...)...)...)
rs := bytes.NewReader(data)
meta, err := tag.ReadFrom(rs)
if err != nil {
t.Fatalf("tag.ReadFrom: %v", err)
}
// Confirm the upstream behaviour this reader works around is still present.
if got := meta.Genre(); got != "Instrumental Hip Hop" {
t.Logf("note: dhowden/tag no longer keeps only the last GENRE (got %q)", got)
}
genres, fellBack := extractGenres(meta, rs)
if fellBack {
t.Error("fellBack = true, want false")
}
if !equalStrings(genres, lifeForms) {
t.Errorf("genres = %q, want %q", genres, lifeForms)
}
}
func TestReadFLACGenreValues(t *testing.T) {
tests := []struct {
name string
@@ -196,6 +172,7 @@ func TestReadFLACGenreValues(t *testing.T) {
{"empty values dropped", buildFLAC(false, "GENRE= ", "GENRE=Rock"), []string{"Rock"}, false},
{"a key that only starts with GENRE", buildFLAC(false, "GENRES=Rock", "GENRE=Jazz"), []string{"Jazz"}, false},
{"not a FLAC", []byte("RIFF....WAVEfmt "), nil, true},
{"a cut-off comment block", func() []byte { d := buildFLAC(false, "GENRE=Jazz", "GENRE=Bop"); return d[:len(d)-2] }(), nil, true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
@@ -210,44 +187,28 @@ func TestReadFLACGenreValues(t *testing.T) {
}
}
func TestReadFLACGenreValues_TruncatedCommentIsAnError(t *testing.T) {
data := buildFLAC(false, "GENRE=Jazz", "GENRE=Bop")
if _, err := readFLACGenreValues(bytes.NewReader(data[:len(data)-2])); err == nil {
t.Error("err = nil for a cut-off comment block")
}
}
func TestExtractGenres_OggVorbisRepeatedFields(t *testing.T) {
comment := append([]byte("\x03vorbis"), vorbisComment(genreFields("Shoegaze", "Dream Pop")...)...)
comment = append(comment, 1) // framing bit
rs := bytes.NewReader(buildOgg(7, vorbisIdent(), comment))
meta, err := tag.ReadFrom(rs)
if err != nil {
t.Fatalf("tag.ReadFrom: %v", err)
}
genres, fellBack := extractGenres(meta, rs)
if fellBack || !equalStrings(genres, []string{"Shoegaze", "Dream Pop"}) {
t.Errorf("genres = %q (fellBack %v), want [Shoegaze Dream Pop]", genres, fellBack)
}
}
func TestReadOggGenreValues_Opus(t *testing.T) {
head := append([]byte("OpusHead"), make([]byte, 11)...)
tags := append([]byte("OpusTags"), vorbisComment(genreFields("Ambient", "Drone")...)...)
got, err := readOggGenreValues(bytes.NewReader(buildOgg(3, head, tags)))
if err != nil || !equalStrings(got, []string{"Ambient", "Drone"}) {
t.Errorf("got %q, %v; want [Ambient Drone]", got, err)
}
}
// Cover art makes the comment packet span pages. A reader that stopped at the
// first page boundary would read a truncated block.
func TestReadOggGenreValues_PacketSpansPages(t *testing.T) {
fields := append([]string{"METADATA_BLOCK_PICTURE=" + strings.Repeat("A", 70000)}, genreFields("Jazz", "Bop")...)
comment := append([]byte("\x03vorbis"), vorbisComment(fields...)...)
got, err := readOggGenreValues(bytes.NewReader(buildOgg(9, vorbisIdent(), comment)))
if err != nil || !equalStrings(got, []string{"Jazz", "Bop"}) {
t.Errorf("got %q, %v; want [Jazz Bop]", got, err)
// Ogg genres are read from Vorbis and Opus comment packets. Cover art makes
// the comment packet span pages, so a reader that stopped at the first page
// boundary would read a truncated block.
func TestReadOggGenreValues(t *testing.T) {
opusHead := append([]byte("OpusHead"), make([]byte, 11)...)
opusTags := append([]byte("OpusTags"), vorbisComment(genreFields("Ambient", "Drone")...)...)
bigFields := append([]string{"METADATA_BLOCK_PICTURE=" + strings.Repeat("A", 70000)}, genreFields("Jazz", "Bop")...)
bigComment := append([]byte("\x03vorbis"), vorbisComment(bigFields...)...)
for _, tc := range []struct {
name string
data []byte
want []string
}{
{"opus", buildOgg(3, opusHead, opusTags), []string{"Ambient", "Drone"}},
{"a packet spanning pages", buildOgg(9, vorbisIdent(), bigComment), []string{"Jazz", "Bop"}},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := readOggGenreValues(bytes.NewReader(tc.data))
if err != nil || !equalStrings(got, tc.want) {
t.Errorf("got %q, %v; want %q", got, err, tc.want)
}
})
}
}
@@ -274,15 +235,3 @@ func TestReadMP4GenreValues(t *testing.T) {
})
}
}
func TestExtractGenres_MP4MultiValue(t *testing.T) {
rs := bytes.NewReader(buildMP4(true, mp4Box("\xa9gen", mp4Text("Hip Hop"), mp4Text("Lo-Fi"))))
meta, err := tag.ReadFrom(rs)
if err != nil {
t.Fatalf("tag.ReadFrom: %v", err)
}
genres, fellBack := extractGenres(meta, rs)
if fellBack || !equalStrings(genres, []string{"Hip Hop", "Lo-Fi"}) {
t.Errorf("genres = %q (fellBack %v), want [Hip Hop Lo-Fi]", genres, fellBack)
}
}