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
+3
View File
@@ -223,6 +223,9 @@ jobs:
PG_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_ID")
test -n "$PG_IP"
export MINSTREL_TEST_DATABASE_URL="postgres://minstrel:minstrel@${PG_IP}:5432/minstrel_test?sslmode=disable"
# A database test that finds no database fails here instead of
# skipping, so this lane can't pass with nothing run.
export MINSTREL_TEST_DATABASE_REQUIRED=1
# Wait for Postgres to accept connections. Asked of the service
# container itself: the run: shell is dash, where a `/dev/tcp`
+3 -11
View File
@@ -1,7 +1,6 @@
package api
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -9,7 +8,7 @@ import (
"path/filepath"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Fabled-Sword/minstrel/internal/dbtest"
)
// getArt fetches path and returns the image body, or "" with the status
@@ -52,13 +51,6 @@ func detailCoverURL(t *testing.T, h *handlers, id string) string {
return got.CoverURL
}
func exec(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)
}
}
// An artist's image is the picture fetched for them, or else their newest
// album cover; artist listings point at it when there is a picture, and the
// artist page whenever the artist has albums.
@@ -75,7 +67,7 @@ func TestArtistImage_PictureOrNewestAlbumCover(t *testing.T) {
}
orchard := seedArtist(t, pool, "Tin Orchard")
album := seedAlbum(t, pool, orchard.ID, "Paper Boats", 2012)
exec(t, pool, `UPDATE albums SET cover_art_path = $2 WHERE id = $1`, album.ID, write("boats.jpg", "boats"))
dbtest.On(t, pool).Exec(`UPDATE albums SET cover_art_path = $2 WHERE id = $1`, album.ID, write("boats.jpg", "boats"))
quiet := seedArtist(t, pool, "Quiet Field")
orchardImage := "/api/artists/" + uuidToString(orchard.ID) + "/image"
albumCover := "/api/albums/" + uuidToString(album.ID) + "/cover"
@@ -87,7 +79,7 @@ func TestArtistImage_PictureOrNewestAlbumCover(t *testing.T) {
t.Errorf("no picture: listing cover_url = %v, want the album cover for Tin Orchard and none for Quiet Field", got)
}
exec(t, pool, `UPDATE artists SET artist_thumb_path = $2 WHERE id = $1`, orchard.ID, write("thumb.jpg", "thumb"))
dbtest.On(t, pool).Exec(`UPDATE artists SET artist_thumb_path = $2 WHERE id = $1`, orchard.ID, write("thumb.jpg", "thumb"))
if got, code := getArt(t, h, orchardImage); got != "thumb" {
t.Errorf("with a picture: got %q (status %d), want the picture", got, code)
}
+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)
+18 -11
View File
@@ -37,18 +37,9 @@ func Open(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
// to call concurrently with application traffic only if the database is idle;
// in practice this runs once at startup before the HTTP server binds.
func Migrate(dsn string, logger *slog.Logger) error {
if dsn == "" {
return errors.New("db: database URL is empty")
}
src, err := iofs.New(migrationsFS, "migrations")
m, err := newMigrator(dsn)
if err != nil {
return fmt.Errorf("db: iofs source: %w", err)
}
m, err := migrate.NewWithSourceInstance("iofs", src, "pgx5://"+trimScheme(dsn))
if err != nil {
return fmt.Errorf("db: migrate init: %w", err)
return err
}
defer func() {
if srcErr, dbErr := m.Close(); srcErr != nil || dbErr != nil {
@@ -67,6 +58,22 @@ func Migrate(dsn string, logger *slog.Logger) error {
return nil
}
// newMigrator opens the embedded migrations against dsn. The caller closes it.
func newMigrator(dsn string) (*migrate.Migrate, error) {
if dsn == "" {
return nil, errors.New("db: database URL is empty")
}
src, err := iofs.New(migrationsFS, "migrations")
if err != nil {
return nil, fmt.Errorf("db: iofs source: %w", err)
}
m, err := migrate.NewWithSourceInstance("iofs", src, "pgx5://"+trimScheme(dsn))
if err != nil {
return nil, fmt.Errorf("db: migrate init: %w", err)
}
return m, nil
}
// trimScheme rewrites a postgres://... or postgresql://... DSN to the bare
// form expected by the migrate pgx driver (it registers its own scheme).
func trimScheme(dsn string) string {
+2 -9
View File
@@ -4,7 +4,6 @@ import (
"context"
"io"
"log/slog"
"os"
"testing"
)
@@ -12,15 +11,9 @@ import (
// Postgres indicated by MINSTREL_TEST_DATABASE_URL. Intended flow for local
// development: `docker compose up -d postgres` then
// `MINSTREL_TEST_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel?sslmode=disable go test ./...`.
// Skipped in `-short` mode (which is what CI runs) and when the env var is unset.
// Skipped under -short and without a database (see testDSN).
func TestMigrateAgainstPostgres(t *testing.T) {
if testing.Short() {
t.Skip("skipping migration test in -short mode")
}
dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set; skipping")
}
dsn := testDSN(t)
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+192
View File
@@ -0,0 +1,192 @@
package db
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"net/url"
"os"
"strings"
"testing"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/jackc/pgx/v5"
)
// TestMigrationsRoundTrip applies every migration up, every one after the
// baseline down, and every one up again, in a database of its own. After the
// down pass the schema must equal a database migrated to the baseline alone,
// so a down file that leaves a column, index or constraint behind fails here
// rather than on someone's rollback.
//
// The baseline is the whole schema and its down file refuses to run on
// purpose, so the round trip stops at it.
func TestMigrationsRoundTrip(t *testing.T) {
dsn := testDSN(t)
ctx := context.Background()
scratch := scratchDatabase(ctx, t, dsn)
src, err := iofs.New(migrationsFS, "migrations")
if err != nil {
t.Fatalf("iofs source: %v", err)
}
baseline, err := src.First()
if err != nil {
t.Fatalf("first migration: %v", err)
}
m, err := newMigrator(scratch)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { m.Close() })
step := func(name string, run func() error) {
t.Helper()
if err := run(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
t.Fatalf("%s: %v", name, err)
}
}
step("migrate to the baseline", func() error { return m.Migrate(baseline) })
want := schemaOf(ctx, t, scratch)
step("up", m.Up)
step("down to the baseline", func() error { return m.Migrate(baseline) })
got := schemaOf(ctx, t, scratch)
if missing, extra := diffLines(want, got); len(missing)+len(extra) > 0 {
t.Errorf("the down migrations do not return the schema to the baseline\n"+
"missing after down:\n %s\nleft behind by down:\n %s",
strings.Join(missing, "\n "), strings.Join(extra, "\n "))
}
step("up again", m.Up)
}
// testDSN is dbtest.URL for this package, which dbtest imports and so cannot
// import back: it skips under -short, and without MINSTREL_TEST_DATABASE_URL
// it skips, or fails when MINSTREL_TEST_DATABASE_REQUIRED is set.
func testDSN(t *testing.T) string {
t.Helper()
if testing.Short() {
t.Skip("database test; skipped under -short")
}
dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL")
if dsn == "" {
if os.Getenv("MINSTREL_TEST_DATABASE_REQUIRED") != "" {
t.Fatal("MINSTREL_TEST_DATABASE_URL is not set, and MINSTREL_TEST_DATABASE_REQUIRED says this run needs a database")
}
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
return dsn
}
// scratchDatabase creates an empty database beside the one dsn names and
// returns its URL. It is dropped when the test ends, so the shared test
// database the other packages truncate is never migrated down.
func scratchDatabase(ctx context.Context, t *testing.T, dsn string) string {
t.Helper()
admin, err := pgx.Connect(ctx, dsn)
if err != nil {
t.Fatalf("connect: %v", err)
}
t.Cleanup(func() { admin.Close(context.Background()) })
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
t.Fatal(err)
}
name := "migrations_roundtrip_" + hex.EncodeToString(b)
if _, err := admin.Exec(ctx, "CREATE DATABASE "+name); err != nil {
t.Fatalf("create database: %v", err)
}
t.Cleanup(func() {
if _, err := admin.Exec(context.Background(), "DROP DATABASE IF EXISTS "+name+" WITH (FORCE)"); err != nil {
t.Logf("drop %s: %v", name, err)
}
})
u, err := url.Parse(dsn)
if err != nil {
t.Fatalf("parse dsn: %v", err)
}
u.Path = "/" + name
return u.String()
}
// schemaOf lists the public schema as sorted lines: every column with its type,
// nullability and default, every index, constraint, sequence, enum value,
// function and trigger. schema_migrations is left out; its version moves.
func schemaOf(ctx context.Context, t *testing.T, dsn string) []string {
t.Helper()
conn, err := pgx.Connect(ctx, dsn)
if err != nil {
t.Fatalf("connect: %v", err)
}
defer conn.Close(ctx)
const q = `
SELECT 'column ' || table_name || '.' || column_name || ' ' || data_type
|| CASE WHEN is_nullable = 'NO' THEN ' not null' ELSE '' END
|| COALESCE(' default ' || column_default, '')
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name <> 'schema_migrations'
UNION ALL
SELECT 'index ' || indexdef
FROM pg_indexes
WHERE schemaname = 'public' AND tablename <> 'schema_migrations'
UNION ALL
SELECT 'constraint ' || c.conrelid::regclass || ' ' || c.conname || ' ' || pg_get_constraintdef(c.oid)
FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace
WHERE n.nspname = 'public' AND c.conrelid <> 0
AND c.conrelid::regclass::text <> 'schema_migrations'
UNION ALL
SELECT 'sequence ' || sequence_name
FROM information_schema.sequences
WHERE sequence_schema = 'public'
UNION ALL
SELECT 'enum ' || t.typname || ' ' || e.enumlabel
FROM pg_enum e JOIN pg_type t ON t.oid = e.enumtypid
JOIN pg_namespace n ON n.oid = t.typnamespace
WHERE n.nspname = 'public'
UNION ALL
SELECT 'function ' || p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')'
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public'
UNION ALL
SELECT 'trigger ' || event_object_table || ' ' || trigger_name || ' ' || event_manipulation
FROM information_schema.triggers
WHERE trigger_schema = 'public'
ORDER BY 1`
rows, err := conn.Query(ctx, q)
if err != nil {
t.Fatalf("read schema: %v", err)
}
lines, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
t.Fatalf("read schema: %v", err)
}
return lines
}
// diffLines returns the lines of want missing from got, and the lines of got
// that want lacks. Both inputs are sorted.
func diffLines(want, got []string) (missing, extra []string) {
i, j := 0, 0
for i < len(want) || j < len(got) {
switch {
case j == len(got) || (i < len(want) && want[i] < got[j]):
missing = append(missing, want[i])
i++
case i == len(want) || got[j] < want[i]:
extra = append(extra, got[j])
j++
default:
i++
j++
}
}
return missing, extra
}
+60
View File
@@ -0,0 +1,60 @@
package dbtest
import (
"context"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
// DB is what Fixtures writes through: a pool, a connection or a transaction.
type DB interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}
// Fixtures writes a test's own rows and fails the test on any error, so a
// test reads as its data rather than its error handling:
//
// fx := dbtest.On(t, pool)
// artist := fx.One(`INSERT INTO artists (name, sort_name) VALUES ('A', 'a') RETURNING id`)
// fx.Exec(`UPDATE artists SET artist_thumb_path = $2 WHERE id = $1`, artist, path)
// if n := fx.Count(`SELECT count(*) FROM artists`); n != 1 { … }
type Fixtures struct {
t testing.TB
db DB
}
// On returns Fixtures writing through db for t.
func On(t testing.TB, db DB) Fixtures { return Fixtures{t: t, db: db} }
// One runs a statement that returns one uuid, usually an INSERT … RETURNING
// id, and returns it.
func (f Fixtures) One(sql string, args ...any) pgtype.UUID {
f.t.Helper()
var id pgtype.UUID
if err := f.db.QueryRow(context.Background(), sql, args...).Scan(&id); err != nil {
f.t.Fatalf("%s: %v", sql, err)
}
return id
}
// Exec runs a statement.
func (f Fixtures) Exec(sql string, args ...any) {
f.t.Helper()
if _, err := f.db.Exec(context.Background(), sql, args...); err != nil {
f.t.Fatalf("%s: %v", sql, err)
}
}
// Count runs a query that returns one number, usually a SELECT count(*).
func (f Fixtures) Count(sql string, args ...any) int {
f.t.Helper()
var n int
if err := f.db.QueryRow(context.Background(), sql, args...).Scan(&n); err != nil {
f.t.Fatalf("%s: %v", sql, err)
}
return n
}
+28 -11
View File
@@ -14,27 +14,44 @@ import (
)
// EnvDatabaseURL names the variable holding the Postgres DSN integration
// tests run against. Without it, every test that asks for a pool skips.
// tests run against. Without it, every test that asks for a pool skips,
// unless EnvDatabaseRequired is set.
const EnvDatabaseURL = "MINSTREL_TEST_DATABASE_URL"
// EnvDatabaseRequired, set to any value, makes a missing database fail the
// test instead of skipping it. The integration lane sets it, so a lane that
// lost its database goes red rather than passing with nothing run.
const EnvDatabaseRequired = "MINSTREL_TEST_DATABASE_REQUIRED"
// URL returns the test database's DSN. It skips t under -short, and when no
// database is configured it skips t, or fails it under EnvDatabaseRequired.
func URL(t testing.TB) string {
t.Helper()
if testing.Short() {
t.Skip("database test; skipped under -short")
}
dsn := os.Getenv(EnvDatabaseURL)
if dsn == "" {
if os.Getenv(EnvDatabaseRequired) != "" {
t.Fatal(EnvDatabaseURL + " is not set, and " + EnvDatabaseRequired + " says this run needs a database")
}
t.Skip(EnvDatabaseURL + " not set")
}
return dsn
}
var (
migrateOnce sync.Once
errMigrate error
)
// Open returns a pool on the test database with the schema migrated to the
// latest version, closed when t ends. It skips t under -short or when
// MINSTREL_TEST_DATABASE_URL is unset. It does not clear any data: use Pool
// for that, unless the test manages its own rows.
// latest version, closed when t ends. Without a database it skips or fails t,
// as URL does. It does not clear any data: use Pool for that, unless the test
// manages its own rows.
func Open(t *testing.T) *pgxpool.Pool {
t.Helper()
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
dsn := os.Getenv(EnvDatabaseURL)
if dsn == "" {
t.Skip(EnvDatabaseURL + " not set")
}
dsn := URL(t)
// Migrating is idempotent but not free; once per test binary is enough.
migrateOnce.Do(func() {
errMigrate = db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil)))
+1 -6
View File
@@ -87,12 +87,7 @@ func seed(t *testing.T, opts seedOpts) setup {
func countQueueRows(t *testing.T, s setup) int {
t.Helper()
var n int
if err := s.pool.QueryRow(context.Background(),
`SELECT count(*) FROM scrobble_queue WHERE play_event_id = $1`, s.playEvent).Scan(&n); err != nil {
t.Fatalf("count: %v", err)
}
return n
return dbtest.On(t, s.pool).Count(`SELECT count(*) FROM scrobble_queue WHERE play_event_id = $1`, s.playEvent)
}
func TestMaybeEnqueue_QualifyingPlayWithEnabledUser_InsertsRow(t *testing.T) {
+2 -12
View File
@@ -132,22 +132,12 @@ func stubLB(recordingsBody, artistsBody string, status int) *httptest.Server {
func countTrackSim(t *testing.T, f fixture, a pgtype.UUID) int {
t.Helper()
var n int
if err := f.pool.QueryRow(context.Background(),
`SELECT count(*) FROM track_similarity WHERE track_a_id = $1`, a).Scan(&n); err != nil {
t.Fatalf("count: %v", err)
}
return n
return dbtest.On(t, f.pool).Count(`SELECT count(*) FROM track_similarity WHERE track_a_id = $1`, a)
}
func countArtistSim(t *testing.T, f fixture, a pgtype.UUID) int {
t.Helper()
var n int
if err := f.pool.QueryRow(context.Background(),
`SELECT count(*) FROM artist_similarity WHERE artist_a_id = $1`, a).Scan(&n); err != nil {
t.Fatalf("count: %v", err)
}
return n
return dbtest.On(t, f.pool).Count(`SELECT count(*) FROM artist_similarity WHERE artist_a_id = $1`, a)
}
func TestTickOnce_NoPlayedTracks_NoOp(t *testing.T) {