test: migrations round-trip down and up; dbtest fails when the lane has no database (#8509, #8510)

Migration round trip (family idea "Migration CI lane"):
- TestMigrationsRoundTrip, in the integration lane, migrates a scratch
  database to the baseline, then all the way up, then every migration
  after the baseline down, then up again.
- The schema after the down pass must match a database migrated to the
  baseline alone: columns, indexes, constraints, sequences, enums,
  functions and triggers. So a down file that leaves something behind
  fails, as well as one that errors.
- The baseline's own down file refuses to run by design, so the round
  trip stops there.
- The test uses golang-migrate as a library, with no migrator binary.
- The scratch database is dropped afterwards, and the shared test
  database is never migrated down.

dbtest (family idea "dbtest Pool and Fixtures"):
- dbtest.URL skips without a database. It fails instead when
  MINSTREL_TEST_DATABASE_REQUIRED is set, and the integration lane sets
  it.
- dbtest.On(t, db) gives One/Exec/Count fixtures. The local copies are
  repointed to them: exec in api, mustExec/mustID in backup,
  countQueueRows in scrobble, and countTrackSim/countArtistSim in
  similarity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 10:44:18 -05:00
co-authored by Claude Opus 5.5
parent d1c63acf78
commit 7491a7b60f
11 changed files with 340 additions and 103 deletions
+21 -37
View File
@@ -9,7 +9,6 @@ import (
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Fabled-Sword/minstrel/internal/backup"
"github.com/Fabled-Sword/minstrel/internal/dbtest"
@@ -93,44 +92,29 @@ func TestOmittedColumnsExist_Integration(t *testing.T) {
}
}
func mustExec(t *testing.T, pool *pgxpool.Pool, sql string, args ...any) {
t.Helper()
if _, err := pool.Exec(context.Background(), sql, args...); err != nil {
t.Fatalf("%s: %v", sql, err)
}
}
func mustID(t *testing.T, pool *pgxpool.Pool, sql string, args ...any) string {
t.Helper()
var id string
if err := pool.QueryRow(context.Background(), sql, args...).Scan(&id); err != nil {
t.Fatalf("%s: %v", sql, err)
}
return id
}
// A backup restored into an emptied instance gives back the same rows, byte
// for byte, without the credentials and markers it leaves out.
func TestARestoredInstanceHoldsWhatTheBackupHeld_Integration(t *testing.T) {
pool := dbtest.Pool(t)
fx := dbtest.On(t, pool)
ctx := context.Background()
user := mustID(t, pool, `INSERT INTO users (username, password_hash, api_token_hash, listenbrainz_token, listenbrainz_enabled)
VALUES ($1, 'hash', 'backup-token', 'lb-token', true) RETURNING id::text`, dbtest.TestUserPrefix+"backup")
artist := mustID(t, pool, `INSERT INTO artists (name, sort_name, artist_art_source) VALUES ('Artist', 'artist', 'none') RETURNING id::text`)
album := mustID(t, pool, `INSERT INTO albums (title, sort_title, artist_id, cover_art_source, cover_art_path)
VALUES ('Album', 'album', $1, 'mbcaa', '/data/covers/a.jpg') RETURNING id::text`, artist)
track := mustID(t, pool, `INSERT INTO tracks (title, album_id, artist_id, duration_ms, file_path, file_size, file_format, tag_source)
VALUES ('Track', $1, $2, 180000, '/music/a.flac', 1000, 'flac', 'musicbrainz') RETURNING id::text`, album, artist)
session := mustID(t, pool, `INSERT INTO play_sessions (user_id, started_at, last_event_at) VALUES ($1, now(), now()) RETURNING id::text`, user)
mustExec(t, pool, `INSERT INTO play_events (user_id, track_id, session_id, started_at) VALUES ($1, $2, $3, now())`, user, track, session)
mustExec(t, pool, `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2)`, user, track)
mustExec(t, pool, `INSERT INTO play_queues (user_id, track_ids, current_track_id, position_ms, changed_by)
user := fx.One(`INSERT INTO users (username, password_hash, api_token_hash, listenbrainz_token, listenbrainz_enabled)
VALUES ($1, 'hash', 'backup-token', 'lb-token', true) RETURNING id`, dbtest.TestUserPrefix+"backup")
artist := fx.One(`INSERT INTO artists (name, sort_name, artist_art_source) VALUES ('Artist', 'artist', 'none') RETURNING id`)
album := fx.One(`INSERT INTO albums (title, sort_title, artist_id, cover_art_source, cover_art_path)
VALUES ('Album', 'album', $1, 'mbcaa', '/data/covers/a.jpg') RETURNING id`, artist)
track := fx.One(`INSERT INTO tracks (title, album_id, artist_id, duration_ms, file_path, file_size, file_format, tag_source)
VALUES ('Track', $1, $2, 180000, '/music/a.flac', 1000, 'flac', 'musicbrainz') RETURNING id`, album, artist)
session := fx.One(`INSERT INTO play_sessions (user_id, started_at, last_event_at) VALUES ($1, now(), now()) RETURNING id`, user)
fx.Exec(`INSERT INTO play_events (user_id, track_id, session_id, started_at) VALUES ($1, $2, $3, now())`, user, track, session)
fx.Exec(`INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2)`, user, track)
fx.Exec(`INSERT INTO play_queues (user_id, track_ids, current_track_id, position_ms, changed_by)
VALUES ($1, ARRAY[$2::uuid, $2::uuid], $2, 61000, 'an app')`, user, track)
playlist := mustID(t, pool, `INSERT INTO playlists (user_id, name) VALUES ($1, 'Mine') RETURNING id::text`, user)
mustExec(t, pool, `INSERT INTO playlist_tracks (playlist_id, position, track_id, title, artist_name, album_title, duration_sec)
playlist := fx.One(`INSERT INTO playlists (user_id, name) VALUES ($1, 'Mine') RETURNING id`, user)
fx.Exec(`INSERT INTO playlist_tracks (playlist_id, position, track_id, title, artist_name, album_title, duration_sec)
VALUES ($1, 0, $2, 'Track', 'Artist', 'Album', 180)`, playlist, track)
mustExec(t, pool, `INSERT INTO library_changes (entity_type, entity_id, op) VALUES ('track', $1, 'upsert')`, track)
fx.Exec(`INSERT INTO library_changes (entity_type, entity_id, op) VALUES ('track', $1, 'upsert')`, track)
first, err := backup.Snapshot(ctx, pool)
if err != nil {
@@ -168,12 +152,12 @@ func TestARestoredInstanceHoldsWhatTheBackupHeld_Integration(t *testing.T) {
// a library, here with a track the backup doesn't know. It still takes
// the backup: the backup's library replaces what the scan found, which the
// next scan finds again under the backup's ids.
mustExec(t, pool, "TRUNCATE users CASCADE")
scannedArtist := mustID(t, pool, `INSERT INTO artists (name, sort_name) VALUES ('Scanned', 'scanned') RETURNING id::text`)
scannedAlbum := mustID(t, pool, `INSERT INTO albums (title, sort_title, artist_id) VALUES ('Scanned', 'scanned', $1) RETURNING id::text`, scannedArtist)
scanned := mustID(t, pool, `INSERT INTO tracks (title, album_id, artist_id, duration_ms, file_path, file_size, file_format)
VALUES ('Scanned', $1, $2, 1000, '/music/b.flac', 10, 'flac') RETURNING id::text`, scannedAlbum, scannedArtist)
mustExec(t, pool, `INSERT INTO library_changes (entity_type, entity_id, op) VALUES ('track', $1, 'upsert')`, scanned)
fx.Exec("TRUNCATE users CASCADE")
scannedArtist := fx.One(`INSERT INTO artists (name, sort_name) VALUES ('Scanned', 'scanned') RETURNING id`)
scannedAlbum := fx.One(`INSERT INTO albums (title, sort_title, artist_id) VALUES ('Scanned', 'scanned', $1) RETURNING id`, scannedArtist)
scanned := fx.One(`INSERT INTO tracks (title, album_id, artist_id, duration_ms, file_path, file_size, file_format)
VALUES ('Scanned', $1, $2, 1000, '/music/b.flac', 10, 'flac') RETURNING id`, scannedAlbum, scannedArtist)
fx.Exec(`INSERT INTO library_changes (entity_type, entity_id, op) VALUES ('track', $1, 'upsert')`, scanned)
if err := backup.Restore(ctx, pool, first); err != nil {
t.Fatalf("restore: %v", err)
}
+10 -6
View File
@@ -14,15 +14,17 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Fabled-Sword/minstrel/internal/backup"
"github.com/Fabled-Sword/minstrel/internal/dbtest"
)
// library writes music files under a new library folder and adds a track for
// each. It returns the folder.
func library(t *testing.T, pool *pgxpool.Pool, files map[string]string) string {
t.Helper()
fx := dbtest.On(t, pool)
root := t.TempDir()
artist := mustID(t, pool, `INSERT INTO artists (name, sort_name) VALUES ('Artist', 'artist') RETURNING id::text`)
album := mustID(t, pool, `INSERT INTO albums (title, sort_title, artist_id) VALUES ('Album', 'album', $1) RETURNING id::text`, artist)
artist := fx.One(`INSERT INTO artists (name, sort_name) VALUES ('Artist', 'artist') RETURNING id`)
album := fx.One(`INSERT INTO albums (title, sort_title, artist_id) VALUES ('Album', 'album', $1) RETURNING id`, artist)
for rel, body := range files {
path := filepath.Join(root, filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
@@ -31,7 +33,7 @@ func library(t *testing.T, pool *pgxpool.Pool, files map[string]string) string {
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
mustExec(t, pool, `INSERT INTO tracks (title, album_id, artist_id, duration_ms, file_path, file_size, file_format)
fx.Exec(`INSERT INTO tracks (title, album_id, artist_id, duration_ms, file_path, file_size, file_format)
VALUES ($1, $2, $3, 1000, $4, $5, 'flac')`, rel, album, artist, path, len(body))
}
return root
@@ -52,6 +54,7 @@ func runOnce(t *testing.T, svc *backup.Service) backup.Run {
func TestTheMusicGoesToTheFolderOnceAndAgainOnlyWhenItChanges_Integration(t *testing.T) {
svc, pool := newService(t)
fx := dbtest.On(t, pool)
ctx := context.Background()
lib := library(t, pool, map[string]string{"A/one.flac": "one", "B/two.flac": "second"})
svc.Roots = func() []string { return []string{lib} }
@@ -83,7 +86,7 @@ func TestTheMusicGoesToTheFolderOnceAndAgainOnlyWhenItChanges_Integration(t *tes
}
// A scan that touched the track but found the same file sends nothing.
mustExec(t, pool, `UPDATE tracks SET updated_at = now()`)
fx.Exec(`UPDATE tracks SET updated_at = now()`)
if touched := runOnce(t, svc); touched.MusicFiles != 0 {
t.Errorf("after a scan touched the tracks the run sent %d files, want none", touched.MusicFiles)
}
@@ -100,7 +103,7 @@ func TestTheMusicGoesToTheFolderOnceAndAgainOnlyWhenItChanges_Integration(t *tes
if err := os.Chtimes(path, later, later); err != nil {
t.Fatal(err)
}
mustExec(t, pool, `UPDATE tracks SET file_size = $1 WHERE file_path = $2`, len("one, retagged"), path)
fx.Exec(`UPDATE tracks SET file_size = $1 WHERE file_path = $2`, len("one, retagged"), path)
if changed := runOnce(t, svc); changed.MusicFiles != 1 {
t.Errorf("after one file changed the run sent %d files, want 1", changed.MusicFiles)
}
@@ -136,6 +139,7 @@ func (b lockedBucket) ServeHTTP(w http.ResponseWriter, r *http.Request) {
func TestTheMusicGoesToTheBucketAndARefusedOverwriteIsKept_Integration(t *testing.T) {
svc, pool := newService(t)
fx := dbtest.On(t, pool)
ctx := context.Background()
fake := &fakeBucket{puts: map[string][]byte{}}
srv := httptest.NewServer(lockedBucket{fakeBucket: fake})
@@ -162,7 +166,7 @@ func TestTheMusicGoesToTheBucketAndARefusedOverwriteIsKept_Integration(t *testin
if err := os.WriteFile(path, []byte("one, retagged"), 0o644); err != nil {
t.Fatal(err)
}
mustExec(t, pool, `UPDATE tracks SET file_size = $1, updated_at = now() WHERE file_path = $2`, len("one, retagged"), path)
fx.Exec(`UPDATE tracks SET file_size = $1, updated_at = now() WHERE file_path = $2`, len("one, retagged"), path)
run := runOnce(t, svc)
if run.MusicFiles != 0 || run.MusicNote != "" {
t.Errorf("a refused overwrite: sent %d, note %q; want nothing sent and no note", run.MusicFiles, run.MusicNote)