diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index a0a45a4c..8720149d 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -8,7 +8,6 @@ import ( "log/slog" "net/http" "net/http/httptest" - "os" "strings" "testing" @@ -19,7 +18,6 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/auth" "git.fabledsword.com/bvandeusen/minstrel/internal/config" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/library" @@ -37,23 +35,8 @@ import ( // used elsewhere (scanner_test.go, etc.). func testHandlers(t *testing.T) (*handlers, *pgxpool.Pool) { t.Helper() - if testing.Short() { - t.Skip("skipping api integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) w := playevents.NewWriter(pool, logger, 30*time.Minute, 0.5, 30000) recCfg := config.RecommendationConfig{ RecentlyPlayedHours: 1, RadioSize: 50, RadioSizeMax: 200, diff --git a/internal/audit/audit_test.go b/internal/audit/audit_test.go index 3dc1db97..5d77e8de 100644 --- a/internal/audit/audit_test.go +++ b/internal/audit/audit_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "log/slog" - "os" "strings" "testing" @@ -12,19 +11,12 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/audit" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func newTestPool(t *testing.T) *pgxpool.Pool { t.Helper() - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) // Reset audit_log so each test runs against a known state. if _, err := pool.Exec(context.Background(), `DELETE FROM audit_log`); err != nil { t.Fatalf("reset audit_log: %v", err) @@ -102,14 +94,7 @@ func TestWriteOrLog_Success(t *testing.T) { // closed pool, and asserts the logger captured a Warn record with // action + err keys. func TestWriteOrLog_DBFailure_Logs(t *testing.T) { - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } + pool := dbtest.Open(t) pool.Close() // force subsequent ops to fail var buf bytes.Buffer @@ -135,14 +120,7 @@ func TestWriteOrLog_DBFailure_Logs(t *testing.T) { // TestWriteOrLog_NilLogger ensures a nil logger + failing pool does // not panic. Uses a closed pool to force the failure branch. func TestWriteOrLog_NilLogger(t *testing.T) { - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } + pool := dbtest.Open(t) pool.Close() var nilUUID pgtype.UUID diff --git a/internal/backup/backup_test.go b/internal/backup/backup_test.go index 0e34bdd8..7ffafb4f 100644 --- a/internal/backup/backup_test.go +++ b/internal/backup/backup_test.go @@ -5,9 +5,6 @@ import ( "context" "encoding/json" "errors" - "io" - "log/slog" - "os" "slices" "testing" @@ -15,31 +12,9 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/backup" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func index(name string) int { return slices.IndexFunc(backup.Tables, func(t backup.Table) bool { return t.Name == name }) } @@ -47,7 +22,7 @@ func index(name string) int { // Every table in the schema is backed up or excluded with a reason, so a new // table fails here until someone decides which. func TestEveryTableIsAccountedFor_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) rows, err := pool.Query(context.Background(), "SELECT tablename FROM pg_tables WHERE schemaname = 'public'") if err != nil { t.Fatal(err) @@ -64,7 +39,7 @@ func TestEveryTableIsAccountedFor_Integration(t *testing.T) { // A restore loads each table after the ones it references, and never needs a // table the backup leaves out. func TestTablesComeAfterWhatTheyReference_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) rows, err := pool.Query(context.Background(), ` SELECT cl.relname, pc.relname FROM pg_constraint co @@ -104,7 +79,7 @@ func TestTablesComeAfterWhatTheyReference_Integration(t *testing.T) { // Every omitted column exists, so a renamed column fails here rather than a // sealed credential slipping into the file under its new name. func TestOmittedColumnsExist_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) for _, tbl := range backup.Tables { for _, col := range tbl.Omit { var n int @@ -137,7 +112,7 @@ func mustID(t *testing.T, pool *pgxpool.Pool, sql string, args ...any) string { // 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 := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() user := mustID(t, pool, `INSERT INTO users (username, password_hash, api_token_hash, listenbrainz_token) diff --git a/internal/backup/service_integration_test.go b/internal/backup/service_integration_test.go index 039adbbe..b7b3c77f 100644 --- a/internal/backup/service_integration_test.go +++ b/internal/backup/service_integration_test.go @@ -19,11 +19,12 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/backup" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func newService(t *testing.T) (*backup.Service, *pgxpool.Pool) { t.Helper() - pool := newPool(t) + pool := dbtest.Pool(t) svc := backup.NewService(pool, slog.New(slog.NewTextHandler(io.Discard, nil)), "test-build") t.Cleanup(svc.Close) return svc, pool diff --git a/internal/catalogue/catalogue_test.go b/internal/catalogue/catalogue_test.go index b0b829d7..4df74476 100644 --- a/internal/catalogue/catalogue_test.go +++ b/internal/catalogue/catalogue_test.go @@ -4,43 +4,16 @@ import ( "context" "errors" "fmt" - "io" - "log/slog" "net/http" "net/http/httptest" - "os" "sync/atomic" "testing" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/musicbrainz" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - const ( apes = "0a11ce00-0000-4000-8000-000000000001" ghostNights = "0a11ce00-0000-4000-8000-000000000002" @@ -95,7 +68,7 @@ func (f *fakeMB) client() *musicbrainz.Client { func TestRefreshReleaseGroup_ReadsEditionsAndTrackLists_Integration(t *testing.T) { ctx := context.Background() mb := newFakeMB(t) - pool := newPool(t) + pool := dbtest.Pool(t) s := New(pool, mb.client(), nil) q := dbq.New(pool) @@ -139,7 +112,7 @@ func TestRefreshReleaseGroup_ReadsEditionsAndTrackLists_Integration(t *testing.T func TestRefreshReleaseGroup_UnknownAndUnreachable_Integration(t *testing.T) { ctx := context.Background() mb := newFakeMB(t) - s := New(newPool(t), mb.client(), nil) + s := New(dbtest.Pool(t), mb.client(), nil) if err := s.RefreshReleaseGroup(ctx, "00000000-0000-4000-8000-000000000000"); !errors.Is(err, ErrNotFound) { t.Errorf("unknown group: err = %v, want ErrNotFound", err) diff --git a/internal/coplay/worker_integration_test.go b/internal/coplay/worker_integration_test.go index e38475f0..07221bc3 100644 --- a/internal/coplay/worker_integration_test.go +++ b/internal/coplay/worker_integration_test.go @@ -4,39 +4,16 @@ import ( "context" "io" "log/slog" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func testPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } func seedUser(t *testing.T, q *dbq.Queries, name string) pgtype.UUID { @@ -105,7 +82,7 @@ func coplayEdgeCount(t *testing.T, pool *pgxpool.Pool) int { // TestCoplayWorker_BuildsEdges: two users who both play two artists produce a // perfect-overlap co-play edge (Jaccard 1.0) in each direction. func TestCoplayWorker_BuildsEdges(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -143,7 +120,7 @@ func TestCoplayWorker_BuildsEdges(t *testing.T) { // TestCoplayWorker_SingleUserNoEdges: one user's own co-listening yields no // edges — the >= 2 distinct-co-player gate keeps single-user servers empty. func TestCoplayWorker_SingleUserNoEdges(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/coverart/artist_enricher_test.go b/internal/coverart/artist_enricher_test.go index 2751eb49..13f5f6d7 100644 --- a/internal/coverart/artist_enricher_test.go +++ b/internal/coverart/artist_enricher_test.go @@ -9,6 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) // stubArtistProvider is a configurable ArtistArtProvider for artist enricher @@ -46,7 +47,7 @@ func insertArtist(t *testing.T, q *dbq.Queries, ctx context.Context, name, mbid // --- Eligibility tests --- func TestEnrichArtist_NullSource_Eligible(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -78,7 +79,7 @@ func TestEnrichArtist_NullSource_Eligible(t *testing.T) { } func TestEnrichArtist_FoundSource_Skip(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -124,7 +125,7 @@ func TestEnrichArtist_FoundSource_Skip(t *testing.T) { } func TestEnrichArtist_NoneCurrentVersion_Skip(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -165,7 +166,7 @@ func TestEnrichArtist_NoneCurrentVersion_Skip(t *testing.T) { } func TestEnrichArtist_NoneStaleVersion_FlipAndRetry(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -212,7 +213,7 @@ func TestEnrichArtist_NoneStaleVersion_FlipAndRetry(t *testing.T) { // --- Atomicity: thumb-only / fanart-only --- func TestEnrichArtist_ThumbOnly_ThumbPathSetFanartNull(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -259,7 +260,7 @@ func TestEnrichArtist_ThumbOnly_ThumbPathSetFanartNull(t *testing.T) { } func TestEnrichArtist_FanartOnly_FanartPathSetThumbNull(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -299,7 +300,7 @@ func TestEnrichArtist_FanartOnly_FanartPathSetThumbNull(t *testing.T) { // --- All-404 settles to 'none' --- func TestEnrichArtist_All404_SettlesNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -335,7 +336,7 @@ func TestEnrichArtist_All404_SettlesNone(t *testing.T) { // --- Empty providers list settles vacuously to 'none' --- func TestEnrichArtist_EmptyProviders_SettlesNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -365,7 +366,7 @@ func TestEnrichArtist_EmptyProviders_SettlesNone(t *testing.T) { // --- ErrTransient leaves row NULL --- func TestEnrichArtist_ErrTransient_LeavesNull(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -399,7 +400,7 @@ func TestEnrichArtist_ErrTransient_LeavesNull(t *testing.T) { // --- Filesystem layout --- func TestEnrichArtist_FilesystemLayout(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -497,7 +498,7 @@ func TestCleanupArtistArt_IdempotentMissingDir(t *testing.T) { // --- MBID guard --- func TestEnrichArtist_NoMBID_SettlesNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/coverart/enricher_test.go b/internal/coverart/enricher_test.go index 36e8c38a..747bfa71 100644 --- a/internal/coverart/enricher_test.go +++ b/internal/coverart/enricher_test.go @@ -13,32 +13,10 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } @@ -97,7 +75,7 @@ func seedAlbumWithTrack(t *testing.T, pool *pgxpool.Pool, title, artistName, mbi } func TestEnrichAlbum_SidecarFound(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Sid", "Artist", "") if err := os.WriteFile(filepath.Join(dir, "cover.jpg"), []byte("img"), 0o644); err != nil { t.Fatal(err) @@ -122,7 +100,7 @@ func TestEnrichAlbum_SidecarFound(t *testing.T) { } func TestEnrichAlbum_NoSidecarNoMBID_SettlesNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, _ := seedAlbumWithTrack(t, pool, "NoMbid", "Artist", "") resetRegistryForTests() // deterministic empty registry (no provider can supply) t.Cleanup(resetRegistryForTests) @@ -143,7 +121,7 @@ func TestEnrichAlbum_NoSidecarNoMBID_SettlesNone(t *testing.T) { } func TestEnrichAlbum_ProviderFetchSuccess(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Prov", "Artist", "test-mbid-123") upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -194,7 +172,7 @@ func TestEnrichAlbum_ProviderFetchSuccess(t *testing.T) { } func TestEnrichAlbum_All404_RecordsNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, _ := seedAlbumWithTrack(t, pool, "Missing", "Artist", "missing-mbid") upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -231,7 +209,7 @@ func TestEnrichAlbum_All404_RecordsNone(t *testing.T) { } func TestEnrichAlbum_AlreadySidecar_NoOp(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Already", "Artist", "") if err := os.WriteFile(filepath.Join(dir, "cover.jpg"), []byte("first"), 0o644); err != nil { t.Fatal(err) @@ -258,7 +236,7 @@ func TestEnrichAlbum_AlreadySidecar_NoOp(t *testing.T) { } func TestEnrichBatch_DrainsNullSourceOnly(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id1, dir1 := seedAlbumWithTrack(t, pool, "Drain1", "A", "") if err := os.WriteFile(filepath.Join(dir1, "cover.jpg"), []byte("c"), 0o644); err != nil { t.Fatal(err) @@ -305,7 +283,7 @@ func TestEnrichBatch_DrainsNullSourceOnly(t *testing.T) { } func TestRetryAlbum_DeletesWrittenFileAndRefetches(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Retry", "Artist", "retry-mbid") hits := 0 @@ -351,7 +329,7 @@ func TestRetryAlbum_DeletesWrittenFileAndRefetches(t *testing.T) { } func TestEnrichRetryMissing_DrainsNullAndNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) // Three albums: // id1: NULL source, has sidecar → drains, becomes 'sidecar'. // id2: 'none' source, has sidecar → cleared then drained, becomes 'sidecar'. @@ -412,7 +390,7 @@ func TestEnrichRetryMissing_DrainsNullAndNone(t *testing.T) { // TestEnrichAlbum_MultiProviderChain verifies that when provider A // returns ErrNotFound, the enricher continues to provider B. func TestEnrichAlbum_MultiProviderChain(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "Multi", "Artist", "multi-mbid") // Provider A: always 404. @@ -473,7 +451,7 @@ func TestEnrichAlbum_MultiProviderChain(t *testing.T) { // TestEnrichAlbum_TransientLeavesNull verifies that a transient error // from the provider leaves the row NULL for next-pass retry. func TestEnrichAlbum_TransientLeavesNull(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, _ := seedAlbumWithTrack(t, pool, "Transient", "Artist", "transient-mbid") upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -514,7 +492,7 @@ func TestEnrichAlbum_TransientLeavesNull(t *testing.T) { // cover_art_source='none' and a stale version gets cleared and // re-enriched (sidecar wins because the album dir now has a cover file). func TestEnrichAlbum_StaleNoneFlipsAndRetries(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) id, dir := seedAlbumWithTrack(t, pool, "StaleNone", "Artist", "") // Mark the album as 'none' (simulating a previous pass). diff --git a/internal/coverart/settings_test.go b/internal/coverart/settings_test.go index a43496cb..d63c2de3 100644 --- a/internal/coverart/settings_test.go +++ b/internal/coverart/settings_test.go @@ -4,6 +4,8 @@ import ( "context" "errors" "testing" + + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) // fakeArtistProvider opts into ArtistArtProvider for capability tests. @@ -27,7 +29,7 @@ func (f *fakeTestableAlbumProvider) TestConnection(_ context.Context) error { } func TestSettingsService_BootInsertsDefaultRows(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -60,7 +62,7 @@ func TestSettingsService_BootInsertsDefaultRows(t *testing.T) { } func TestSettingsService_UpdateProvider_FlippingEnabledBumpsVersion(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -92,7 +94,7 @@ func TestSettingsService_UpdateProvider_FlippingEnabledBumpsVersion(t *testing.T } func TestSettingsService_UpdateProvider_KeyOnlyDoesNotBumpVersion(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -131,7 +133,7 @@ func TestSettingsService_UpdateProvider_KeyOnlyDoesNotBumpVersion(t *testing.T) } func TestSettingsService_UpdateProvider_ClearKey(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -161,7 +163,7 @@ func TestSettingsService_UpdateProvider_ClearKey(t *testing.T) { } func TestSettingsService_TestProvider_Routing(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -195,7 +197,7 @@ func TestSettingsService_TestProvider_Routing(t *testing.T) { } func TestSettingsService_ListProviderInfo_Capabilities(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -235,7 +237,7 @@ func TestSettingsService_ListProviderInfo_Capabilities(t *testing.T) { // TestSettingsService_BumpVersionIfProvidersChanged_FirstBoot: stored // hash is empty (column default ""), so a real provider set produces a bump. func TestSettingsService_BumpVersionIfProvidersChanged_FirstBoot(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -266,7 +268,7 @@ func TestSettingsService_BumpVersionIfProvidersChanged_FirstBoot(t *testing.T) { // call back-to-back returns bumped=false because the stored hash now // matches the registered set. func TestSettingsService_BumpVersionIfProvidersChanged_NoChange(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() @@ -299,7 +301,7 @@ func TestSettingsService_BumpVersionIfProvidersChanged_NoChange(t *testing.T) { // path. Distinct from BumpVersionIfProvidersChanged, this always writes // regardless of the stored provider-set hash. func TestSettingsService_BumpVersion_Increments(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) resetRegistryForTests() defer resetRegistryForTests() diff --git a/internal/dbtest/pool.go b/internal/dbtest/pool.go new file mode 100644 index 00000000..2477c7b7 --- /dev/null +++ b/internal/dbtest/pool.go @@ -0,0 +1,60 @@ +package dbtest + +import ( + "context" + "io" + "log/slog" + "os" + "sync" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "git.fabledsword.com/bvandeusen/minstrel/internal/db" +) + +// EnvDatabaseURL names the variable holding the Postgres DSN integration +// tests run against. Without it, every test that asks for a pool skips. +const EnvDatabaseURL = "MINSTREL_TEST_DATABASE_URL" + +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. +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") + } + // 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))) + }) + if errMigrate != nil { + t.Fatalf("migrate: %v", errMigrate) + } + pool, err := pgxpool.New(context.Background(), dsn) + if err != nil { + t.Fatalf("connect to test database: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// Pool is Open followed by ResetDB: a migrated pool with every data table +// empty and only non-test users left. +func Pool(t *testing.T) *pgxpool.Pool { + t.Helper() + pool := Open(t) + ResetDB(t, pool) + return pool +} diff --git a/internal/gc/worker_test.go b/internal/gc/worker_test.go index 19868cb7..30f00120 100644 --- a/internal/gc/worker_test.go +++ b/internal/gc/worker_test.go @@ -4,14 +4,12 @@ import ( "context" "io" "log/slog" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) @@ -22,23 +20,8 @@ import ( // to seed. func testWorker(t *testing.T) (*Worker, *pgxpool.Pool) { t.Helper() - if testing.Short() { - t.Skip("skipping gc integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) return NewWorker(pool, logger), pool } diff --git a/internal/library/acoustid_lookup_test.go b/internal/library/acoustid_lookup_test.go index aa0fdc5a..c4725106 100644 --- a/internal/library/acoustid_lookup_test.go +++ b/internal/library/acoustid_lookup_test.go @@ -158,7 +158,7 @@ func addTrack(t *testing.T, q *dbq.Queries, album dbq.Album, artist dbq.Artist, // restoring `mbid = EXCLUDED.mbid` in UpsertTrack: the first re-read below // then erases the looked-up id. func TestUpsertTrack_KeepsALookedUpMbidUntilATagCarriesOne_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() @@ -198,7 +198,7 @@ func TestUpsertTrack_KeepsALookedUpMbidUntilATagCarriesOne_Integration(t *testin } func TestAcoustIDLookup_FillsOnlyWhatItCanSettle_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() @@ -269,7 +269,7 @@ func TestAcoustIDLookup_FillsOnlyWhatItCanSettle_Integration(t *testing.T) { } func TestAcoustIDLookup_StopsWhenTheServiceCannotAnswer_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() @@ -306,7 +306,7 @@ func TestAcoustIDLookup_StopsWhenTheServiceCannotAnswer_Integration(t *testing.T // similarity worker picks the track as a seed and can map ListenBrainz's // answers back to it. func TestAcoustIDLookup_FilledTrackReachesSimilarity_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/album_loudness_test.go b/internal/library/album_loudness_test.go index 93f2cf98..132952c2 100644 --- a/internal/library/album_loudness_test.go +++ b/internal/library/album_loudness_test.go @@ -9,6 +9,7 @@ import ( "testing" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" ) @@ -115,7 +116,7 @@ func TestComputeAlbumLoudness(t *testing.T) { // stored histograms, does nothing when nothing changed, and recomputes on // each kind of membership change. func TestAlbumLoudness_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/delete_test.go b/internal/library/delete_test.go index f51af5c3..3676f9a1 100644 --- a/internal/library/delete_test.go +++ b/internal/library/delete_test.go @@ -3,9 +3,7 @@ package library import ( "context" "errors" - "io" "io/fs" - "log/slog" "os" "path/filepath" "syscall" @@ -14,32 +12,10 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func seedTrack(t *testing.T, pool *pgxpool.Pool, filePath string) (dbq.Track, dbq.Album, dbq.Artist) { t.Helper() q := dbq.New(pool) @@ -76,7 +52,7 @@ func stubRemoveFile(t *testing.T, fn func(string) error) { } func TestDeleteTrackFile_HappyPath(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) dir := t.TempDir() @@ -114,7 +90,7 @@ func TestDeleteTrackFile_HappyPath(t *testing.T) { } func TestDeleteTrackFile_EmptiedAlbumAndArtistGoToo(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) path := filepath.Join(t.TempDir(), "lone.mp3") @@ -157,7 +133,7 @@ func TestDeleteTrackFile_UnremovableFileDeletesNothing(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) dir := t.TempDir() @@ -202,7 +178,7 @@ func TestDeleteTrackFile_UnremovableFileDeletesNothing(t *testing.T) { } func TestDeleteTrackFile_FileAlreadyGoneSucceeds(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) track, _, _ := seedTrack(t, pool, "/no/such/file/anywhere.mp3") @@ -216,7 +192,7 @@ func TestDeleteTrackFile_FileAlreadyGoneSucceeds(t *testing.T) { } func TestDeleteTrackFile_NotFoundReturnsErr(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) var bogus pgtype.UUID bogus.Bytes = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} diff --git a/internal/library/duplicate_merge_test.go b/internal/library/duplicate_merge_test.go index a8143b14..335d531d 100644 --- a/internal/library/duplicate_merge_test.go +++ b/internal/library/duplicate_merge_test.go @@ -32,7 +32,7 @@ type mergeFixture struct { func newMergeFixture(t *testing.T) mergeFixture { t.Helper() - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/duplicate_resolve_test.go b/internal/library/duplicate_resolve_test.go index 6403d741..f0b51faf 100644 --- a/internal/library/duplicate_resolve_test.go +++ b/internal/library/duplicate_resolve_test.go @@ -12,6 +12,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" ) @@ -26,7 +27,7 @@ type resolveFixture struct { func newResolveFixture(t *testing.T) resolveFixture { t.Helper() - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := filepath.Join(t.TempDir(), "Plastic Apes", "Mammalz (2017)") @@ -145,7 +146,7 @@ type crossReleaseRipFixture struct { func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture { t.Helper() - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) root := t.TempDir() @@ -279,7 +280,7 @@ type oneAlbumFixture struct { func newOneAlbumFixture(t *testing.T, tier, titleA, titleB string) oneAlbumFixture { t.Helper() - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := filepath.Join(t.TempDir(), "Savanta", "Void") diff --git a/internal/library/duplicate_sweep_test.go b/internal/library/duplicate_sweep_test.go index 676425ff..d8cd557d 100644 --- a/internal/library/duplicate_sweep_test.go +++ b/internal/library/duplicate_sweep_test.go @@ -14,6 +14,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" ) @@ -41,7 +42,7 @@ func TestCoveredByDismissal(t *testing.T) { // out, and how re-sweeping treats a dismissal and a proposal that no longer // holds. func TestDuplicateSweep_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/fingerprint_backfill_test.go b/internal/library/fingerprint_backfill_test.go index ae37c662..3d030cff 100644 --- a/internal/library/fingerprint_backfill_test.go +++ b/internal/library/fingerprint_backfill_test.go @@ -13,12 +13,13 @@ import ( "testing" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) // TestFingerprintBackfill_Integration pins which tracks a pass touches, that a // pass ends, and that the coverage gauge counts what the pass wrote. func TestFingerprintBackfill_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/fingerprint_scan_test.go b/internal/library/fingerprint_scan_test.go index 8d505438..d70b8cd0 100644 --- a/internal/library/fingerprint_scan_test.go +++ b/internal/library/fingerprint_scan_test.go @@ -14,9 +14,8 @@ import ( "time" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) // TestScanner_FingerprintsOnlyNewOrChangedBytes_Integration pins WHEN the scan @@ -27,24 +26,10 @@ import ( // The fingerprinter is stubbed. CI has no real audio, and the tools' output is // covered by the parser tests; this covers the scan's decisions. func TestScanner_FingerprintsOnlyNewOrChangedBytes_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } diff --git a/internal/library/fingerprint_settings_test.go b/internal/library/fingerprint_settings_test.go index 4a517641..87f213bf 100644 --- a/internal/library/fingerprint_settings_test.go +++ b/internal/library/fingerprint_settings_test.go @@ -6,6 +6,8 @@ import ( "math" "testing" "time" + + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func TestValidateFingerprintSettings(t *testing.T) { @@ -64,7 +66,7 @@ func TestFingerprintSettingsService_NilServesDefaults(t *testing.T) { } func TestFingerprintSettingsService_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() reload := func(step string) FingerprintSettings { t.Helper() diff --git a/internal/library/library_paths_test.go b/internal/library/library_paths_test.go index aa3cd5e2..943eb1b2 100644 --- a/internal/library/library_paths_test.go +++ b/internal/library/library_paths_test.go @@ -14,6 +14,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func mkdir(t *testing.T, parts ...string) string { @@ -84,7 +85,7 @@ func clearSavedRoots(t *testing.T, pool *pgxpool.Pool) { } func TestSetRoots_TracksMoveWithTheirFolder_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) clearSavedRoots(t, pool) ctx := context.Background() base := t.TempDir() @@ -126,7 +127,7 @@ func TestSetRoots_TracksMoveWithTheirFolder_Integration(t *testing.T) { } func TestSetRoots_RefusesAMoveToAFolderWithoutTheFiles_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) clearSavedRoots(t, pool) ctx := context.Background() base := t.TempDir() diff --git a/internal/library/loudness_backfill_test.go b/internal/library/loudness_backfill_test.go index b650f733..d2b9f70a 100644 --- a/internal/library/loudness_backfill_test.go +++ b/internal/library/loudness_backfill_test.go @@ -11,6 +11,7 @@ import ( "testing" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" ) @@ -18,7 +19,7 @@ import ( // stores for each kind of result, that a pass ends, and that the gauge counts // what the passes wrote. func TestLoudnessBackfill_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() @@ -230,7 +231,7 @@ func TestLoudnessBackfill_Integration(t *testing.T) { // The Go defaults must match the migration's, or a database that cannot be // read would analyze differently from a fresh install. func TestLoudnessSettings_DefaultsMatchMigration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s, err := NewLoudnessSettingsService(context.Background(), pool) if err != nil { t.Fatalf("load: %v", err) diff --git a/internal/library/mbidbackfill_test.go b/internal/library/mbidbackfill_test.go index 990d6e45..dedd82c6 100644 --- a/internal/library/mbidbackfill_test.go +++ b/internal/library/mbidbackfill_test.go @@ -10,13 +10,14 @@ import ( "testing" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) // The MBID backfills read tags from files, so a track whose file is gone has // nothing to give them: they skip it rather than log an "open failed" warning // per missing track on every scan. func TestMBIDBackfill_SkipsMissingTracks_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/missing_pairs_test.go b/internal/library/missing_pairs_test.go index 7e2b24fc..dc9f5232 100644 --- a/internal/library/missing_pairs_test.go +++ b/internal/library/missing_pairs_test.go @@ -114,7 +114,7 @@ func (f pairFixture) count(sql string, args ...any) int { // On rows: each rule folds the pair it should, history moves onto // the replacement, and every shape the pass must leave alone is left alone. func TestPairMissingTracks_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Pair Artist", SortName: "Pair Artist"}) @@ -236,7 +236,7 @@ func TestPairMissingTracks_Integration(t *testing.T) { // arrives at a new path with no recording MBID, so move adoption has nothing to // match. The scan must still end with one row, carrying the old row's history. func TestScanner_FoldsUpgradedFile_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) diff --git a/internal/library/new_music_test.go b/internal/library/new_music_test.go index 972b8bfa..096ed08f 100644 --- a/internal/library/new_music_test.go +++ b/internal/library/new_music_test.go @@ -38,7 +38,7 @@ func newMusicNotices(t *testing.T, q *dbq.Queries, user dbq.User) []notification // into an empty library is the library being set up, and an album that only // formed because tracks already held were retagged into it is not new music. func TestAnnounceNewAlbums_TellsEveryoneOfEachNewAlbumOnce(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := notifyingAdmin(t, pool) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/library/normalization_prefs_test.go b/internal/library/normalization_prefs_test.go index 6dd54616..2b23ed05 100644 --- a/internal/library/normalization_prefs_test.go +++ b/internal/library/normalization_prefs_test.go @@ -30,7 +30,7 @@ func TestNormalizationPrefs_Validate(t *testing.T) { // migration's defaults for any column the insert left out; the two must // agree, or a user would hear a different level after their first save. func TestNormalizationPrefs_DefaultsAndRoundTrip_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) user, err := q.CreateUser(ctx, dbq.CreateUserParams{ diff --git a/internal/library/notify_test.go b/internal/library/notify_test.go index 1885f878..2db00321 100644 --- a/internal/library/notify_test.go +++ b/internal/library/notify_test.go @@ -62,7 +62,7 @@ func unreadNotices(t *testing.T, pool *pgxpool.Pool, user dbq.User) []notice { } func TestNotifyScanFinished_FailuresCoalesceAndShutdownIsSilent(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := notifyingAdmin(t, pool) ctx := context.Background() @@ -91,7 +91,7 @@ func TestNotifyScanFinished_FailuresCoalesceAndShutdownIsSilent(t *testing.T) { // it has adopted moves and folded replacements, so a file it marked and then // healed is never reported as lost. func TestReconcileMissing_RecordsTheMarksWithoutNotifying(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := notifyingAdmin(t, pool) s := testScanner(t, populatedRoot(t)) @@ -117,7 +117,7 @@ func TestReconcileMissing_RecordsTheMarksWithoutNotifying(t *testing.T) { } func TestNotifyStillMissing_NamesOnlyTheTracksStillGone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := notifyingAdmin(t, pool) ctx := context.Background() q := dbq.New(pool) @@ -158,7 +158,7 @@ func TestNotifyStillMissing_NamesOnlyTheTracksStillGone(t *testing.T) { // it for them. A group the resolver settles or links is never news, and a // group already seen by an earlier pass is not news again. func TestResolveDuplicates_TellsAdminsOnlyOfNewGroupsLeftForThem(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := notifyingAdmin(t, pool) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/library/remove_test.go b/internal/library/remove_test.go index 2d3218ce..d7882169 100644 --- a/internal/library/remove_test.go +++ b/internal/library/remove_test.go @@ -19,7 +19,7 @@ import ( // A removed file's track stays, missing, with its likes and plays and the // reason it waits, and the good copy that lands later takes its history over. func TestRemoveFile_KeepsTheTrackUntilAGoodCopyLands(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) admin, err := q.CreateUser(ctx, dbq.CreateUserParams{ @@ -86,7 +86,7 @@ func TestRemoveFile_KeepsTheTrackUntilAGoodCopyLands(t *testing.T) { // ForgetMBID drops the recording MBID that came from a file that was not the // track's song. func TestRemoveFile_ForgetsADoubtedMBID(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() path := filepath.Join(t.TempDir(), "rip.mp3") if err := os.WriteFile(path, []byte("x"), 0o644); err != nil { @@ -112,7 +112,7 @@ func TestRemoveFile_ForgetsADoubtedMBID(t *testing.T) { // A file that cannot be removed leaves the track as it was. func TestRemoveFile_FailedRemovalMarksNothing(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() path := filepath.Join(t.TempDir(), "stuck.mp3") if err := os.WriteFile(path, []byte("x"), 0o644); err != nil { @@ -139,7 +139,7 @@ func TestRemoveFile_FailedRemovalMarksNothing(t *testing.T) { // The reason describes one missing spell: a file back at its path clears it // with the missing mark. func TestRemoveFile_ReasonGoesWhenTheFileIsBack(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() path := filepath.Join(t.TempDir(), "back.mp3") if err := os.WriteFile(path, []byte("x"), 0o644); err != nil { diff --git a/internal/library/replaygain_test.go b/internal/library/replaygain_test.go index ae18d735..6da6efb2 100644 --- a/internal/library/replaygain_test.go +++ b/internal/library/replaygain_test.go @@ -9,6 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func TestGainDBAndLinearPeak(t *testing.T) { @@ -45,7 +46,7 @@ func TestGainDBAndLinearPeak(t *testing.T) { } func TestReplayGainForTracks_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/scanner_test.go b/internal/library/scanner_test.go index 783dbc3b..16e636a4 100644 --- a/internal/library/scanner_test.go +++ b/internal/library/scanner_test.go @@ -11,10 +11,9 @@ import ( "testing" "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func TestReleaseDateFromYear(t *testing.T) { @@ -45,24 +44,10 @@ func TestReleaseDateFromYear(t *testing.T) { // TestScanner_Integration exercises walk → tag-parse → upsert → incremental // skip against a real Postgres. Gated on MINSTREL_TEST_DATABASE_URL. func TestScanner_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) @@ -221,24 +206,10 @@ func writeTestMP3(t *testing.T, path string, frames map[string]string) { // reconcile would refuse to mark, adoption could not fire, and the file would // fork. See the "reconcile skipped" warning in Scan. func TestScanner_AdoptsMovedFile_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } @@ -315,24 +286,10 @@ func TestScanner_AdoptsMovedFile_Integration(t *testing.T) { // read existed gets it on the next scan, through the tagReadVersion bump, // without its file changing. func TestScanner_ReleaseGroupMBID_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } @@ -392,23 +349,9 @@ func TestScanner_ReleaseGroupMBID_Integration(t *testing.T) { // track of the same group joins its album, and a track filed under the other // album's row by the old lookup moves to its own on the tagReadVersion re-read. func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } @@ -493,7 +436,7 @@ func TestScanner_SameTitledAlbumsOfTwoGroupsAreTwoAlbums_Integration(t *testing. // with its old mtime, which takes the unchanged-file skip. The track keeps its // id, and clients are told it plays again. func TestScanFiles_ClearsTheMarkWhenAFileReturnsToItsPath_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) @@ -554,23 +497,9 @@ func TestScanFiles_ClearsTheMarkWhenAFileReturnsToItsPath_Integration(t *testing // one album, and every track keeps its own artist. The row the old filing // left behind is removed by the scan's tidy-up once a re-read empties it. func TestScanner_AlbumArtistKeepsAnAlbumTogether_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping scanner integration in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } ctx := context.Background() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) if _, err := pool.Exec(ctx, "TRUNCATE tracks, albums, artists RESTART IDENTITY CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } diff --git a/internal/library/song_link_test.go b/internal/library/song_link_test.go index 0f9976e5..903c37be 100644 --- a/internal/library/song_link_test.go +++ b/internal/library/song_link_test.go @@ -75,7 +75,7 @@ func newSongLinkFixture(t *testing.T, pool *pgxpool.Pool) songLinkFixture { // list shows the song once, a like or unlike on either copy reaches both, and // "not the same song" undoes the link. func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) f := newSongLinkFixture(t, pool) @@ -153,7 +153,7 @@ func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) { // With auto-resolve off the resolver links nothing. func TestCrossReleaseLinkNeedsAutoResolve_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) f := newSongLinkFixture(t, pool) @@ -172,7 +172,7 @@ func TestCrossReleaseLinkNeedsAutoResolve_Integration(t *testing.T) { // they make it the key. func TestMergeInheritsSongLink_Integration(t *testing.T) { for _, removeAlbumCut := range []bool{true, false} { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) f := newSongLinkFixture(t, pool) @@ -226,7 +226,7 @@ func songKeys(t *testing.T, q *dbq.Queries, ids ...pgtype.UUID) []pgtype.UUID { // extra copy is merged into its FLAC, the single stays, and the two copies // left are linked as one song. func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) dir := t.TempDir() diff --git a/internal/library/trigger_test.go b/internal/library/trigger_test.go index 24f20049..3ddda5fa 100644 --- a/internal/library/trigger_test.go +++ b/internal/library/trigger_test.go @@ -5,27 +5,20 @@ import ( "errors" "io" "log/slog" - "os" "testing" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" + + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) // triggerTestPool returns a pool against MINSTREL_TEST_DATABASE_URL or skips. func triggerTestPool(t *testing.T) *pgxpool.Pool { t.Helper() - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) // Reset scan_runs so each test starts clean. if _, err := pool.Exec(context.Background(), `DELETE FROM scan_runs`); err != nil { t.Fatalf("reset: %v", err) @@ -135,14 +128,7 @@ func TestTryStartScan_StaleInFlight_Reaps(t *testing.T) { } func TestTryStartScan_DBError_Propagates(t *testing.T) { - url := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if url == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - pool, err := pgxpool.New(context.Background(), url) - if err != nil { - t.Fatalf("connect: %v", err) - } + pool := dbtest.Open(t) pool.Close() // close immediately to force errors on subsequent queries started, existing, err := TryStartScan( diff --git a/internal/lookups/lookups_test.go b/internal/lookups/lookups_test.go index 9175e4c2..ff9d77b0 100644 --- a/internal/lookups/lookups_test.go +++ b/internal/lookups/lookups_test.go @@ -2,14 +2,8 @@ package lookups import ( "context" - "io" - "log/slog" - "os" "testing" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) @@ -24,23 +18,8 @@ func TestGet_WithoutAServiceBothLookupsAreOn(t *testing.T) { // A new install starts with both on; a save is cached for the workers and // read back by a server started afterwards. func TestSettings_StartOnAndKeepWhatIsSaved_Integration(t *testing.T) { - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } ctx := context.Background() - pool, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) s, err := New(ctx, pool) if err != nil { diff --git a/internal/notifications/digest_db_test.go b/internal/notifications/digest_db_test.go index 9b9cfc89..55e02748 100644 --- a/internal/notifications/digest_db_test.go +++ b/internal/notifications/digest_db_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" ) @@ -30,7 +31,7 @@ func digestWith(pool *pgxpool.Pool) (*notifications.Digest, *mailer.FakeSender) } func TestDigest_BatchGoesOutOnceAWindowAfterTheFirstItem(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() alice := emailUser(t, pool, "alice", true) n := notifications.New(pool, nil, nil) @@ -57,7 +58,7 @@ func TestDigest_BatchGoesOutOnceAWindowAfterTheFirstItem(t *testing.T) { } func TestDigest_ReadBeforeTheEmailIsNotEmailed(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) alice := emailUser(t, pool, "alice", true) @@ -74,7 +75,7 @@ func TestDigest_ReadBeforeTheEmailIsNotEmailed(t *testing.T) { } func TestDigest_EmailOffAtNotifyTimeIsNeverSent(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) alice := emailUser(t, pool, "alice", true) @@ -99,7 +100,7 @@ func TestDigest_EmailOffAtNotifyTimeIsNeverSent(t *testing.T) { } func TestDigest_NoAddressNoEmail(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() bob := mkUser(t, dbq.New(pool), "bob", true) n := notifications.New(pool, nil, nil) @@ -111,7 +112,7 @@ func TestDigest_NoAddressNoEmail(t *testing.T) { } func TestDigest_CoalescedItemAppearsOnceWithItsLatestCount(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) root := emailUser(t, pool, "root", true) @@ -134,7 +135,7 @@ func TestDigest_CoalescedItemAppearsOnceWithItsLatestCount(t *testing.T) { } func TestDigest_MailerFailureRetriesWithBackoffAndSendsOnce(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() alice := emailUser(t, pool, "alice", true) n := notifications.New(pool, nil, nil) @@ -158,7 +159,7 @@ func TestDigest_MailerFailureRetriesWithBackoffAndSendsOnce(t *testing.T) { } func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() alice := emailUser(t, pool, "alice", true) // timezone defaults to UTC n := notifications.New(pool, nil, nil) @@ -192,7 +193,7 @@ func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) { } func TestEmailSettings_DefaultsMatchTheMigrationAndRoundTrip(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) @@ -209,7 +210,7 @@ func TestEmailSettings_DefaultsMatchTheMigrationAndRoundTrip(t *testing.T) { } func TestDigest_UsesTheConfiguredBatchWindow(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() alice := emailUser(t, pool, "alice", true) _, err := notifications.SaveEmailSettings(ctx, dbq.New(pool), notifications.EmailSettings{SummaryHour: 9, BatchWindowMinutes: 15}) diff --git a/internal/notifications/notifier_db_test.go b/internal/notifications/notifier_db_test.go index 14673f59..f191ab0b 100644 --- a/internal/notifications/notifier_db_test.go +++ b/internal/notifications/notifier_db_test.go @@ -5,43 +5,19 @@ import ( "encoding/json" "io" "log/slog" - "os" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" "github.com/stretchr/testify/require" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" "git.fabledsword.com/bvandeusen/minstrel/internal/notifications" ) -func testPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func mkUser(t *testing.T, q *dbq.Queries, name string, admin bool) pgtype.UUID { t.Helper() u, err := q.CreateUser(context.Background(), dbq.CreateUserParams{ @@ -71,7 +47,7 @@ func count(t *testing.T, payload []byte) int64 { } func TestNotify_WritesARowAndNudgesOnlyThatUser(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() alice := mkUser(t, q, "alice", false) @@ -103,7 +79,7 @@ func TestNotify_WritesARowAndNudgesOnlyThatUser(t *testing.T) { } func TestNotify_AdminKindReachesAdminsOnly_AndNeverTheExcepted(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() flagger := mkUser(t, q, "admin-flagger", true) @@ -122,7 +98,7 @@ func TestNotify_AdminKindReachesAdminsOnly_AndNeverTheExcepted(t *testing.T) { } func TestNotify_CoalescedCountAddsUpWhileUnread_AndStartsAfreshOnceRead(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() admin := mkUser(t, q, "admin", true) @@ -150,7 +126,7 @@ func TestNotify_CoalescedCountAddsUpWhileUnread_AndStartsAfreshOnceRead(t *testi // created_at would announce it again on the phone, and a cleared emailed_at // would email it again. func TestNotify_ACoalescedUpdateMergesNamesAndKeepsItsArrival(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() admin := mkUser(t, q, "admin", true) @@ -186,7 +162,7 @@ func TestNotify_ACoalescedUpdateMergesNamesAndKeepsItsArrival(t *testing.T) { // Each scan's new music is its own notice: one already emailed in the daily // summary must not quietly take in albums that arrive after it. func TestNotify_NewMusicNeverCoalesces(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() alice := mkUser(t, q, "alice", false) @@ -198,7 +174,7 @@ func TestNotify_NewMusicNeverCoalesces(t *testing.T) { } func TestNotify_EveryoneReachesEveryUser(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() admin := mkUser(t, q, "admin", true) @@ -215,7 +191,7 @@ func TestNotify_EveryoneReachesEveryUser(t *testing.T) { } func TestNotify_InboxOffStoresNothing_AndDefaultsApplyWithoutAPref(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() muted := mkUser(t, q, "muted", false) @@ -233,7 +209,7 @@ func TestNotify_InboxOffStoresNothing_AndDefaultsApplyWithoutAPref(t *testing.T) } func TestMarkRead_ScopedToTheOwner_AndIdempotent(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() alice := mkUser(t, q, "alice", false) @@ -261,7 +237,7 @@ func TestMarkRead_ScopedToTheOwner_AndIdempotent(t *testing.T) { // added in Go without its migration fails here, not in production at INSERT // time. func TestEveryKindPassesTheSchemaChecks(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() user := mkUser(t, q, "kinds", true) @@ -278,7 +254,7 @@ func TestEveryKindPassesTheSchemaChecks(t *testing.T) { } func TestRetention_TrimsOldReadRowsAndAncientUnreadOnes(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) ctx := context.Background() user := mkUser(t, q, "retention", false) diff --git a/internal/playevents/writer_test.go b/internal/playevents/writer_test.go index 65f70266..425319ee 100644 --- a/internal/playevents/writer_test.go +++ b/internal/playevents/writer_test.go @@ -5,39 +5,16 @@ import ( "encoding/json" "io" "log/slog" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func testPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - type fixture struct { pool *pgxpool.Pool q *dbq.Queries @@ -48,7 +25,7 @@ type fixture struct { func newFixture(t *testing.T, durationMs int32) fixture { t.Helper() - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) u, err := q.CreateUser(context.Background(), dbq.CreateUserParams{ Username: dbtest.TestUserPrefix + "tester", PasswordHash: "x", ApiTokenHash: "x", IsAdmin: false, diff --git a/internal/playlists/collage_test.go b/internal/playlists/collage_test.go index 8005d73b..4fccbac2 100644 --- a/internal/playlists/collage_test.go +++ b/internal/playlists/collage_test.go @@ -10,11 +10,12 @@ import ( "github.com/jackc/pgx/v5/pgtype" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" ) func TestGenerateCollage_EmptyPlaylist(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") dir := t.TempDir() svc := playlists.NewService(pool, nil, dir) @@ -34,7 +35,7 @@ func TestGenerateCollage_EmptyPlaylist(t *testing.T) { } func TestGenerateCollage_OneTrack(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") tk := seedTrack(t, pool, "Prismatic", "FoO") dir := t.TempDir() diff --git a/internal/playlists/cover_albums_db_test.go b/internal/playlists/cover_albums_db_test.go index fb1fd8c5..082598a9 100644 --- a/internal/playlists/cover_albums_db_test.go +++ b/internal/playlists/cover_albums_db_test.go @@ -9,6 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" ) @@ -16,7 +17,7 @@ import ( // order they first appear, at most six: a shelf of tiles picks from them so // no two tiles show the same cover. func TestCoverAlbums_DistinctCoveredInTrackOrderCappedAtSix(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) user := seedUser(t, pool, "covers") @@ -91,7 +92,7 @@ func TestCoverAlbums_DistinctCoveredInTrackOrderCappedAtSix(t *testing.T) { // A playlist with no covered albums lists none, rather than failing the // List call that carries every other playlist. func TestCoverAlbums_EmptyPlaylistHasNone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() user := seedUser(t, pool, "nocovers") svc := playlists.NewService(pool, nil, t.TempDir()) diff --git a/internal/playlists/discover_taste_db_test.go b/internal/playlists/discover_taste_db_test.go index a6084d61..28ce2c4c 100644 --- a/internal/playlists/discover_taste_db_test.go +++ b/internal/playlists/discover_taste_db_test.go @@ -9,6 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func setGenre(t *testing.T, pool *pgxpool.Pool, trackID pgtype.UUID, genre string) { @@ -35,7 +36,7 @@ func seedTasteTag(t *testing.T, pool *pgxpool.Pool, userID pgtype.UUID, tag stri // and the bucket shrink to its 3. Capped before, the artist keeps 3 and the // single-tag artists below it fill the rest. func TestListTasteUnheardTracksForDiscover_CapsBeforeLimit(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "tastecap") diff --git a/internal/playlists/genre_mixes_db_test.go b/internal/playlists/genre_mixes_db_test.go index 3ccdfc24..310fa692 100644 --- a/internal/playlists/genre_mixes_db_test.go +++ b/internal/playlists/genre_mixes_db_test.go @@ -11,6 +11,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" ) @@ -39,7 +40,7 @@ func seedGenre(t *testing.T, pool *pgxpool.Pool, genre string, artists, perArtis // tier 2, an untouched one is tier 3, and a genre too small for a mix is not // offered at all. func TestListGenreMixCandidates_TiersAndSizeFloor(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "gmixcand") now := time.Now().UTC() @@ -85,7 +86,7 @@ func TestListGenreMixCandidates_TiersAndSizeFloor(t *testing.T) { // also carries an excluded genre (matched case-insensitively) belongs to that // genre's mix and is left out of this one. func TestListGenreMixTracks_LeavesOutSongsOfGenresAlreadyPicked(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "gmixexcl") @@ -120,7 +121,7 @@ func TestListGenreMixTracks_LeavesOutSongsOfGenresAlreadyPicked(t *testing.T) { // often than played through is left out, while a favourite with stray skips // stays; tracks of other genres never appear. func TestListGenreMixTracks_SplitsFamiliarAndDropsRejectedTracks(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "gmixtracks") now := time.Now().UTC() @@ -178,7 +179,7 @@ func TestListGenreMixTracks_SplitsFamiliarAndDropsRejectedTracks(t *testing.T) { // the genre they listen to, holding only that genre's tracks, with both // halves of the blend stamped. func TestBuildSystemPlaylists_GenreMixes(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "gmixbuild") now := time.Now().UTC() @@ -270,7 +271,7 @@ func meanPosition(sum map[pgtype.UUID]int, tracks []dbq.Track) float64 { // user knows, ones played often and liked come up earlier than ones played // once. func TestListGenreMixTracks_FamiliarLeansTowardFavourites(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "gmixfav") now := time.Now().UTC() @@ -301,7 +302,7 @@ func TestListGenreMixTracks_FamiliarLeansTowardFavourites(t *testing.T) { // have never met, and so does an artist similar to theirs. The stranger // still appears: the lean tilts the draw, it does not exclude. func TestListGenreMixTracks_UnheardLeansTowardTheUsersArtists(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "gmixartist") now := time.Now().UTC() diff --git a/internal/playlists/offline_replay_test.go b/internal/playlists/offline_replay_test.go index 20d582b2..472a44ce 100644 --- a/internal/playlists/offline_replay_test.go +++ b/internal/playlists/offline_replay_test.go @@ -9,6 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" ) @@ -40,7 +41,7 @@ func TestOrderByTracks_ArrangesNamedEntriesInTheirOwnPlaces(t *testing.T) { } func TestCreateWithID_ASecondSendFindsTheSameList(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -71,7 +72,7 @@ func TestCreateWithID_ASecondSendFindsTheSameList(t *testing.T) { } func TestRemoveTrack_ASecondSendRemovesNothingMore(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") a := seedTrack(t, pool, "A", "Artist") b := seedTrack(t, pool, "B", "Artist") @@ -95,7 +96,7 @@ func TestRemoveTrack_ASecondSendRemovesNothingMore(t *testing.T) { } func TestReorderTracks_ASecondSendChangesNothing(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") a := seedTrack(t, pool, "A", "Artist") b := seedTrack(t, pool, "B", "Artist") @@ -118,7 +119,7 @@ func TestReorderTracks_ASecondSendChangesNothing(t *testing.T) { // Every change tells the owner's clients, whichever client made it. func TestChanges_TellTheOwnersClients(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") a := seedTrack(t, pool, "A", "Artist") bus := eventbus.New() diff --git a/internal/playlists/seed_missing_db_test.go b/internal/playlists/seed_missing_db_test.go index 22cbaa09..ab7f113c 100644 --- a/internal/playlists/seed_missing_db_test.go +++ b/internal/playlists/seed_missing_db_test.go @@ -8,6 +8,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func likeTrack(t *testing.T, pool *pgxpool.Pool, userID, trackID pgtype.UUID) { @@ -30,7 +31,7 @@ func markMissing(t *testing.T, pool *pgxpool.Pool, trackID pgtype.UUID) { // TestPickTopPlayedTracksForUser_LikedTierSkipsMissing: with no plays, For // You seeds from likes. A liked track whose file is gone is not a seed. func TestPickTopPlayedTracksForUser_LikedTierSkipsMissing(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) u := seedUser(t, pool, "seedmissing") present := seedTrack(t, pool, "Present", "Seed Artist A") gone := seedTrack(t, pool, "Gone", "Seed Artist B") @@ -51,7 +52,7 @@ func TestPickTopPlayedTracksForUser_LikedTierSkipsMissing(t *testing.T) { // Songs-like seeds from the artist's newest album. When that album's track is // missing, the seed comes from the next album rather than the missing file. func TestPickTopPlayedTrackForArtistByUser_FallbackSkipsMissing(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "songslikemissing") older := seedTrack(t, pool, "Older", "Songs Like Artist") diff --git a/internal/playlists/service_test.go b/internal/playlists/service_test.go index e80b4621..2c6c5502 100644 --- a/internal/playlists/service_test.go +++ b/internal/playlists/service_test.go @@ -9,11 +9,12 @@ import ( "github.com/jackc/pgx/v5/pgtype" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" ) func TestCreate_HappyPath(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") dir := t.TempDir() @@ -37,7 +38,7 @@ func TestCreate_HappyPath(t *testing.T) { } func TestCreate_EmptyNameRejected(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -48,7 +49,7 @@ func TestCreate_EmptyNameRejected(t *testing.T) { } func TestGet_NotFound(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -59,7 +60,7 @@ func TestGet_NotFound(t *testing.T) { } func TestGet_Forbidden_PrivatePlaylistFromOtherUser(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -75,7 +76,7 @@ func TestGet_Forbidden_PrivatePlaylistFromOtherUser(t *testing.T) { } func TestGet_Public_VisibleToOtherUser(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -101,7 +102,7 @@ func TestGet_Public_VisibleToOtherUser(t *testing.T) { } func TestGet_Owner_SeesOwnPrivate(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -119,7 +120,7 @@ func TestGet_Owner_SeesOwnPrivate(t *testing.T) { } func TestList_OwnAndPublic(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -152,7 +153,7 @@ func TestList_OwnAndPublic(t *testing.T) { } func TestUpdate_OwnerOnly(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -177,7 +178,7 @@ func TestUpdate_OwnerOnly(t *testing.T) { } func TestUpdate_PartialFieldsLeaveOthersAlone(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -204,7 +205,7 @@ func TestUpdate_PartialFieldsLeaveOthersAlone(t *testing.T) { } func TestUpdate_EmptyNameRejected(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -220,7 +221,7 @@ func TestUpdate_EmptyNameRejected(t *testing.T) { } func TestUpdate_NotFound(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -231,7 +232,7 @@ func TestUpdate_NotFound(t *testing.T) { } func TestDelete_OwnerOnly(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -254,7 +255,7 @@ func TestDelete_OwnerOnly(t *testing.T) { } func TestDelete_NotFound(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -264,7 +265,7 @@ func TestDelete_NotFound(t *testing.T) { } func TestDelete_RemovesCoverFile(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") dir := t.TempDir() svc := playlists.NewService(pool, nil, dir) @@ -299,7 +300,7 @@ func TestDelete_RemovesCoverFile(t *testing.T) { } func TestDelete_MissingCoverFileTolerated(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") dir := t.TempDir() svc := playlists.NewService(pool, nil, dir) @@ -322,7 +323,7 @@ func TestDelete_MissingCoverFileTolerated(t *testing.T) { } func TestAppendTracks_Snapshot(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") track := seedTrack(t, pool, "Prismatic", "Fields of Ontario") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -348,7 +349,7 @@ func TestAppendTracks_Snapshot(t *testing.T) { } func TestAppendTracks_OwnerOnly(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") track := seedTrack(t, pool, "T", "A") @@ -362,7 +363,7 @@ func TestAppendTracks_OwnerOnly(t *testing.T) { } func TestAppendTracks_NonExistentTrack(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -374,7 +375,7 @@ func TestAppendTracks_NonExistentTrack(t *testing.T) { } func TestRemoveTrack_RenumbersPositions(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") t1 := seedTrack(t, pool, "Track 1", "Artist") t2 := seedTrack(t, pool, "Track 2", "Artist") @@ -402,7 +403,7 @@ func TestRemoveTrack_RenumbersPositions(t *testing.T) { } func TestReorder_Permutation(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") t1 := seedTrack(t, pool, "A", "Artist") t2 := seedTrack(t, pool, "B", "Artist") @@ -427,7 +428,7 @@ func TestReorder_Permutation(t *testing.T) { } func TestReorder_RejectsNonPermutation(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") tk := seedTrack(t, pool, "T", "A") svc := playlists.NewService(pool, nil, t.TempDir()) @@ -451,7 +452,7 @@ func TestReorder_RejectsNonPermutation(t *testing.T) { } func TestSnapshotPersistsAfterUpstreamTrackDelete(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") tk := seedTrack(t, pool, "Doomed track", "Artist") svc := playlists.NewService(pool, nil, t.TempDir()) diff --git a/internal/playlists/service_test_helpers_test.go b/internal/playlists/service_test_helpers_test.go index a2c57df6..0d4578a5 100644 --- a/internal/playlists/service_test_helpers_test.go +++ b/internal/playlists/service_test_helpers_test.go @@ -4,9 +4,6 @@ import ( "context" "crypto/rand" "fmt" - "io" - "log/slog" - "os" "path/filepath" "sync/atomic" "testing" @@ -14,7 +11,6 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) @@ -25,31 +21,6 @@ import ( // tests seed multiple tracks within one test function. var seedTrackCounter uint64 -// newPool migrates a fresh schema against MINSTREL_TEST_DATABASE_URL -// and returns a connection pool with all data tables wiped (test -// users only — see internal/dbtest/reset.go for the why). Skips when -// the env var isn't set or -short is passed. -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - // seedUser inserts a `test-`-prefixed user (so dbtest.ResetDB can // clean it without touching the developer's admin row) and returns // the persisted user record. diff --git a/internal/playlists/song_copies_test.go b/internal/playlists/song_copies_test.go index afdfbffd..c8f65b8b 100644 --- a/internal/playlists/song_copies_test.go +++ b/internal/playlists/song_copies_test.go @@ -7,6 +7,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" ) @@ -14,7 +15,7 @@ import ( // album cut, the better-ranked copy stays; a rip is left out and the next copy // of its song takes the place. func TestOneCopyPerSong_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) single := seedTrack(t, pool, "copies-single", "copies-artist") diff --git a/internal/playlists/system_mixes_db_test.go b/internal/playlists/system_mixes_db_test.go index 556150f1..9f1423b9 100644 --- a/internal/playlists/system_mixes_db_test.go +++ b/internal/playlists/system_mixes_db_test.go @@ -11,6 +11,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) // seedTrackForArtist creates another track under an existing artist + @@ -108,7 +109,7 @@ func likeArtist(t *testing.T, pool *pgxpool.Pool, userID, artistID pgtype.UUID) func TestListDeepCutsTracks_SkippedTracksExcluded(t *testing.T) { // Eligibility counts skipped plays too, so a track skipped repeatedly // (and never finished) does not read as "barely heard". - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) u := seedUser(t, pool, "dc1") now := time.Now().UTC() @@ -153,7 +154,7 @@ func TestListOnThisDayTracks_WrapsYearBoundary(t *testing.T) { // The day-of-year window wraps the year: plain ABS would make Dec 28 vs Jan // 3 read as 359 days apart. The build date parameter anchors "today" so the // wrap is testable at any run date. - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) u := seedUser(t, pool, "otd1") @@ -186,7 +187,7 @@ func TestListNewForYouTracks_TiersAndConsumption(t *testing.T) { // affinity albums; tier 2 = affinity albums from the wider 90-day // window; tier 3 = fresh additions without affinity; any attempted // (>=30s) track consumes the album out of the mix entirely. - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) u := seedUser(t, pool, "nfy1") now := time.Now().UTC() @@ -243,7 +244,7 @@ func TestListFirstListensTracks_AttemptThreshold(t *testing.T) { // "Attempted" is track-level at >=30s. A 2-second brush does not // disqualify an album; barely-attempted albums step back // to tier 2 with the attempted tracks themselves excluded. - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) u := seedUser(t, pool, "fl1") now := time.Now().UTC() @@ -301,7 +302,7 @@ func TestListRediscoverTracks_SkippedResurfacingCoolsDown(t *testing.T) { // invitation — the track sits out ~90 days instead of re-qualifying // the next day. Skips from other surfaces don't cool down, and the // cooldown expires. - pool := newPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) u := seedUser(t, pool, "rd1") now := time.Now().UTC() diff --git a/internal/playlists/system_test.go b/internal/playlists/system_test.go index 913468ec..dab6e747 100644 --- a/internal/playlists/system_test.go +++ b/internal/playlists/system_test.go @@ -16,6 +16,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" ) @@ -79,7 +80,7 @@ func seedActiveLibrary(t *testing.T, pool *pgxpool.Pool, name string, numArtists } func TestBuildSystemPlaylists_SufficientActivity(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, _ := seedActiveLibrary(t, pool, "act1", 4, 3) if err := playlists.BuildSystemPlaylists(context.Background(), pool, logger, u.ID, time.Now().UTC(), t.TempDir()); err != nil { @@ -146,7 +147,7 @@ func TestBuildSystemPlaylists_StaleActivity_SongsLikeSurvives(t *testing.T) { // inside 30d) must still seed the mixes — // and the built tracks carry the tier2 stamp so metrics can compare // stale-seeded mixes against fresh ones. - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u := seedUser(t, pool, "stale1") old := time.Now().UTC().Add(-20 * 24 * time.Hour) @@ -193,7 +194,7 @@ func TestBuildSystemPlaylists_StaleActivity_SongsLikeSurvives(t *testing.T) { } func TestBuildSystemPlaylists_QuarantineExcluded(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, tracks := seedActiveLibrary(t, pool, "qact", 3, 3) @@ -228,7 +229,7 @@ func TestBuildSystemPlaylists_QuarantineExcluded(t *testing.T) { } func TestBuildSystemPlaylists_AtomicReplace(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, _ := seedActiveLibrary(t, pool, "atomic", 3, 3) ctx := context.Background() @@ -265,7 +266,7 @@ func TestBuildSystemPlaylists_AtomicReplace(t *testing.T) { } func TestBuildSystemPlaylists_Concurrency(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, _ := seedActiveLibrary(t, pool, "conc", 3, 3) ctx := context.Background() @@ -361,7 +362,7 @@ func seedSharedArtistLibrary( // to survive a filter coming back in a different shape — and because an // absence check would match the comment explaining why there is no filter. func TestBuildSystemPlaylists_SongsLikeIncludesItsSeedArtist(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, _ := seedSharedArtistLibrary(t, pool, "seedartist", 4, 6) ctx := context.Background() @@ -423,7 +424,7 @@ func TestBuildSystemPlaylists_SongsLikeIncludesItsSeedArtist(t *testing.T) { } func TestBuildSystemPlaylists_DailyNonceDeterminism(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, _ := seedActiveLibrary(t, pool, "nonce", 4, 5) ctx := context.Background() @@ -538,7 +539,7 @@ func equalSnapshots(a, b map[string][]string) bool { } func TestListActiveUsersForSystemPlaylists(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() activeU, tracks := seedActiveLibrary(t, pool, "active", 1, 1) inactiveU := seedUser(t, pool, "inactive") @@ -570,7 +571,7 @@ func TestListActiveUsersForSystemPlaylists(t *testing.T) { func TestBuildSystemPlaylists_DiscoverColdStart(t *testing.T) { // User has no plays / likes → Discover's dormant + cross-user // buckets are empty (or minimal), all slots come from random unheard. - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, _ := seedActiveLibrary(t, pool, "discover_cold", 4, 5) // seedActiveLibrary seeds 3 plays per track; delete them so dormant @@ -619,7 +620,7 @@ func systemVariantsOf(rows []dbq.ListPlaylistsByUserAndKindRow) []string { } func TestStartupRecoveryClearsStaleInFlight(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "stale") // Seed a stale in_flight=true row. diff --git a/internal/playlists/you_might_like_db_test.go b/internal/playlists/you_might_like_db_test.go index 05e91df8..726d63ff 100644 --- a/internal/playlists/you_might_like_db_test.go +++ b/internal/playlists/you_might_like_db_test.go @@ -8,6 +8,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" ) @@ -33,7 +34,7 @@ func countYouMightLike(t *testing.T, pool *pgxpool.Pool, userID pgtype.UUID) (al // You-might-like rows — the build ships nothing rather than near-random // tiles. func TestYouMightLike_ColdStartGate(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, _ := seedActiveLibrary(t, pool, "ymlcold", 3, 3) @@ -54,7 +55,7 @@ func TestYouMightLike_ColdStartGate(t *testing.T) { // × 4 tracks = 32 distinct tracks, clearing both gate bars) populates the // You-might-like tables in the daily build. func TestYouMightLike_SufficientActivityPopulates(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, _ := seedActiveLibrary(t, pool, "ymlrich", 8, 4) @@ -76,7 +77,7 @@ func TestYouMightLike_SufficientActivityPopulates(t *testing.T) { // TestYouMightLike_AtomicReplace: a second build replaces rather than // appends, so counts stay bounded by the persisted depth. func TestYouMightLike_AtomicReplace(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) logger := discardLogger() u, _ := seedActiveLibrary(t, pool, "ymlreplace", 8, 4) ctx := context.Background() diff --git a/internal/playsessions/service_test.go b/internal/playsessions/service_test.go index 613eb3d0..999f2ae9 100644 --- a/internal/playsessions/service_test.go +++ b/internal/playsessions/service_test.go @@ -2,41 +2,16 @@ package playsessions import ( "context" - "io" - "log/slog" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func testPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func seedTestUser(t *testing.T, pool *pgxpool.Pool) pgtype.UUID { t.Helper() u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{ @@ -52,7 +27,7 @@ func seedTestUser(t *testing.T, pool *pgxpool.Pool) pgtype.UUID { } func TestFindOrCreate_NoPriorSessionCreatesOne(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) user := seedTestUser(t, pool) q := dbq.New(pool) @@ -77,7 +52,7 @@ func TestFindOrCreate_NoPriorSessionCreatesOne(t *testing.T) { } func TestFindOrCreate_WithinWindowExtendsExisting(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) user := seedTestUser(t, pool) q := dbq.New(pool) @@ -106,7 +81,7 @@ func TestFindOrCreate_WithinWindowExtendsExisting(t *testing.T) { } func TestFindOrCreate_BeyondWindowStartsNew(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) user := seedTestUser(t, pool) q := dbq.New(pool) @@ -125,7 +100,7 @@ func TestFindOrCreate_BeyondWindowStartsNew(t *testing.T) { } func TestFindOrCreate_AtExactBoundaryExtendsExisting(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) user := seedTestUser(t, pool) q := dbq.New(pool) diff --git a/internal/quarantine/service_test.go b/internal/quarantine/service_test.go index d698e7df..57130645 100644 --- a/internal/quarantine/service_test.go +++ b/internal/quarantine/service_test.go @@ -3,8 +3,6 @@ package quarantine import ( "context" "errors" - "io" - "log/slog" "os" "path/filepath" "testing" @@ -12,32 +10,10 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func seedUser(t *testing.T, pool *pgxpool.Pool, name string) dbq.User { t.Helper() u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{ @@ -79,7 +55,7 @@ func seedTrack(t *testing.T, pool *pgxpool.Pool, title, mbid string) (dbq.Track, } func TestFlag_HappyPath(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") track, _, _ := seedTrack(t, pool, "Bad Track", "abc") @@ -97,7 +73,7 @@ func TestFlag_HappyPath(t *testing.T) { } func TestFlag_UpsertOnSecondFlag(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") track, _, _ := seedTrack(t, pool, "T", "x") @@ -118,7 +94,7 @@ func TestFlag_UpsertOnSecondFlag(t *testing.T) { } func TestFlag_NonexistentTrackReturnsErrTrackNotFound(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") var bogus pgtype.UUID @@ -133,7 +109,7 @@ func TestFlag_NonexistentTrackReturnsErrTrackNotFound(t *testing.T) { } func TestFlag_BadReasonRejected(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") track, _, _ := seedTrack(t, pool, "T", "x") @@ -145,7 +121,7 @@ func TestFlag_BadReasonRejected(t *testing.T) { } func TestUnflag_DeletesRow(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") track, _, _ := seedTrack(t, pool, "T", "x") @@ -162,7 +138,7 @@ func TestUnflag_DeletesRow(t *testing.T) { } func TestListMine_OrderedNewestFirst(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") t1, _, _ := seedTrack(t, pool, "T1", "x") t2, _, _ := seedTrack(t, pool, "T2", "y") @@ -189,7 +165,7 @@ func TestListMine_OrderedNewestFirst(t *testing.T) { } func TestListAdminQueue_AggregatesByTrackWithReasonCounts(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") carol := seedUser(t, pool, "carol") @@ -226,7 +202,7 @@ func TestListAdminQueue_AggregatesByTrackWithReasonCounts(t *testing.T) { } func TestResolve_ClearsRowsAndWritesAudit(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") track, _, _ := seedTrack(t, pool, "T", "x") @@ -256,7 +232,7 @@ func TestResolve_ClearsRowsAndWritesAudit(t *testing.T) { } func TestResolve_NoExistingRowsStillWritesAudit(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") track, _, _ := seedTrack(t, pool, "T", "x") @@ -275,7 +251,7 @@ func TestResolve_NoExistingRowsStillWritesAudit(t *testing.T) { } func TestResolve_TrackNotFound(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") var bogus pgtype.UUID bogus.Bytes = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} @@ -289,7 +265,7 @@ func TestResolve_TrackNotFound(t *testing.T) { } func TestDeleteFile_RemovesFileAndAuditsAffected(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") q := dbq.New(pool) @@ -333,7 +309,7 @@ func TestDeleteFile_RemovesFileAndAuditsAffected(t *testing.T) { // the listeners' rows go, open playback errors read deleted, and the history // says the file was removed. A "wrong file" report drops the file's MBID. func TestRemoveFile_KeepsTheTrackAndSettlesItsReports(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() alice := seedUser(t, pool, "alice") admin := seedUser(t, pool, "admin") @@ -401,7 +377,7 @@ func TestRemoveFile_KeepsTheTrackAndSettlesItsReports(t *testing.T) { } func TestDeleteFile_TrackNotFound(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") var bogus pgtype.UUID bogus.Bytes = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} diff --git a/internal/recommendation/candidates_test.go b/internal/recommendation/candidates_test.go index 4da79e8a..b7c6d753 100644 --- a/internal/recommendation/candidates_test.go +++ b/internal/recommendation/candidates_test.go @@ -3,41 +3,16 @@ package recommendation import ( "context" "encoding/json" - "io" - "log/slog" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func testPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - type fixture struct { pool *pgxpool.Pool q *dbq.Queries @@ -47,7 +22,7 @@ type fixture struct { func newFixture(t *testing.T, n int) fixture { t.Helper() - pool := testPool(t) + pool := dbtest.Pool(t) q := dbq.New(pool) u, err := q.CreateUser(context.Background(), dbq.CreateUserParams{ Username: dbtest.TestUserPrefix + "tester", PasswordHash: "x", ApiTokenHash: "x", IsAdmin: false, diff --git a/internal/recommendation/context_device_integration_test.go b/internal/recommendation/context_device_integration_test.go index 7d76ac2a..3752e301 100644 --- a/internal/recommendation/context_device_integration_test.go +++ b/internal/recommendation/context_device_integration_test.go @@ -9,6 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func insertPlayEventDevice( @@ -37,7 +38,7 @@ func insertPlayEventDevice( // the mobile artist out-scores the web artist and vice-versa, while the // device-agnostic (”) pass treats them equally. func TestLoadContextAffinity_DeviceNarrowing(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/recommendation/fixtures_integration_test.go b/internal/recommendation/fixtures_integration_test.go index 49929624..8e3140b1 100644 --- a/internal/recommendation/fixtures_integration_test.go +++ b/internal/recommendation/fixtures_integration_test.go @@ -4,41 +4,16 @@ package recommendation import ( "context" - "io" - "log/slog" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func seedUser(t *testing.T, pool *pgxpool.Pool, name string) dbq.User { t.Helper() u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{ diff --git a/internal/recommendation/home_integration_test.go b/internal/recommendation/home_integration_test.go index 02b94e8f..133a305d 100644 --- a/internal/recommendation/home_integration_test.go +++ b/internal/recommendation/home_integration_test.go @@ -9,6 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) // TestHomeData_YouMightLike_FallbackFillsFromLikedArtists: when the taste @@ -17,7 +18,7 @@ import ( // You-might-like fallback fills the rest disjointly so no artist is shown // twice. 20 liked artists, none played → Rediscover 10 + You-might-like 10. func TestHomeData_YouMightLike_FallbackFillsFromLikedArtists(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-yml-fallback") liked := make(map[pgtype.UUID]bool, 20) for i := 0; i < 20; i++ { @@ -53,7 +54,7 @@ func TestHomeData_YouMightLike_FallbackFillsFromLikedArtists(t *testing.T) { // (most users like tracks/albums, rarely artists). 12 liked tracks by distinct // artists, no artist-likes, no plays → the artist row fills from them. func TestHomeData_YouMightLike_FallbackFromLikedTrackArtists(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-yml-trackartists") fromLiked := make(map[pgtype.UUID]bool, 12) for i := 0; i < 12; i++ { @@ -83,7 +84,7 @@ func TestHomeData_YouMightLike_FallbackFromLikedTrackArtists(t *testing.T) { } func TestHomeData_NewUser_AllSectionsEmpty(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-newuser") got, err := HomeData(context.Background(), pool, user.ID) @@ -116,7 +117,7 @@ func TestHomeData_NewUser_AllSectionsEmpty(t *testing.T) { var _ map[pgtype.UUID]struct{} func TestHomeData_RecentlyAdded_OrderedByCreatedAt(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-recents") a1 := seedArtist(t, pool, "ArtistA", "") // Three albums, oldest first — created_at increases naturally with each insert. @@ -142,7 +143,7 @@ func TestHomeData_RecentlyAdded_OrderedByCreatedAt(t *testing.T) { } func TestHomeData_MostPlayed_RanksByCount_HonorsQuarantine(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-mostplayed") artist := seedArtist(t, pool, "ArtistB", "") album := seedAlbumForArtist(t, pool, artist.ID, "AlbumB") @@ -179,7 +180,7 @@ func TestHomeData_MostPlayed_RanksByCount_HonorsQuarantine(t *testing.T) { } func TestHomeData_RediscoverAlbums_FallbackWhenSparse(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-rediscover") artist := seedArtist(t, pool, "ArtistC", "") // Like one album NOW (won't satisfy >30d eligibility) — should still @@ -208,7 +209,7 @@ func TestHomeData_RediscoverAlbums_FallbackWhenSparse(t *testing.T) { // ago) is enough for the album to appear in Rediscover, even with no // explicit general_likes_albums entry. func TestHomeData_Rediscover_AlbumFromTrackLikes(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-redis-tracklike") artist := seedArtist(t, pool, "ArtistTL", "") al := seedAlbumForArtist(t, pool, artist.ID, "TrackLiked") @@ -240,7 +241,7 @@ func TestHomeData_Rediscover_AlbumFromTrackLikes(t *testing.T) { // track-derived path. The fallback should also miss this since no // album-like exists. func TestHomeData_Rediscover_AlbumTrackLikeThreshold(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-redis-threshold") artist := seedArtist(t, pool, "ArtistTh", "") al := seedAlbumForArtist(t, pool, artist.ID, "OneTrackLiked") @@ -265,7 +266,7 @@ func TestHomeData_Rediscover_AlbumTrackLikeThreshold(t *testing.T) { // albums from the same artist appear in Rediscover even when more are // eligible. func TestHomeData_Rediscover_DiversityCap(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-redis-cap") artist := seedArtist(t, pool, "ArtistDom", "") albums := []dbq.Album{ @@ -299,7 +300,7 @@ func TestHomeData_Rediscover_DiversityCap(t *testing.T) { // dropped from Rediscover (the "you forgot about this" contract is // broken if the user is actively spinning it). func TestHomeData_Rediscover_DedupVsMostPlayed(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) user := seedUser(t, pool, "home-redis-dedup") artist := seedArtist(t, pool, "ArtistD", "") // "Forgotten" album: liked >30d ago, no recent plays — would be diff --git a/internal/recommendation/taste_test.go b/internal/recommendation/taste_test.go index 3dfd97e8..153f38ef 100644 --- a/internal/recommendation/taste_test.go +++ b/internal/recommendation/taste_test.go @@ -9,6 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) func uuidN(n byte) pgtype.UUID { @@ -132,7 +133,7 @@ func almostEq(a, b float64) bool { return math.Abs(a-b) < 1e-9 } // TestLoadTasteProfile_RoundTrip seeds taste_profile rows and verifies the // reader hydrates them into a profile that scores a matching track positively. func TestLoadTasteProfile_RoundTrip(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() u := seedUser(t, pool, "taste-rt") art := seedArtist(t, pool, "Loved Artist", "") diff --git a/internal/recsettings/service_test.go b/internal/recsettings/service_test.go index cf96f8a3..d8b8ab49 100644 --- a/internal/recsettings/service_test.go +++ b/internal/recsettings/service_test.go @@ -6,37 +6,13 @@ import ( "errors" "io" "log/slog" - "os" "testing" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - if err := db.Migrate(dsn, logger); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func newService(t *testing.T, pool *pgxpool.Pool) *Service { t.Helper() s, err := New(context.Background(), pool, slog.New(slog.NewTextHandler(io.Discard, nil))) @@ -80,7 +56,7 @@ func auditRows(t *testing.T, pool *pgxpool.Pool) []struct { } func TestNew_SeedsShippedDefaults(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s := newService(t, pool) if got := s.Weights(ScopeRadio); got != ShippedRadioWeights() { t.Errorf("radio weights = %+v, want shipped defaults", got) @@ -98,7 +74,7 @@ func TestNew_SeedsShippedDefaults(t *testing.T) { } func TestUpdateProfile_PersistsAndAudits(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s := newService(t, pool) if err := s.UpdateProfile(context.Background(), ScopeRadio, map[string]float64{"taste_weight": 2.5, "skip_penalty": 3.0}); err != nil { @@ -132,7 +108,7 @@ func TestUpdateProfile_PersistsAndAudits(t *testing.T) { } func TestUpdateProfile_Validation(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s := newService(t, pool) cases := []struct { name string @@ -159,7 +135,7 @@ func TestUpdateProfile_Validation(t *testing.T) { } func TestUpdateTaste_CurveOrderingEnforced(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s := newService(t, pool) // Moving neutral above full must reject on the PATCHED result. err := s.UpdateTaste(context.Background(), map[string]float64{"engagement_neutral": 0.95}) @@ -183,7 +159,7 @@ func TestUpdateTaste_CurveOrderingEnforced(t *testing.T) { } func TestUpdateTaste_EnrichedTagScale(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s := newService(t, pool) // In-range update persists into cache + the assembled taste config. if err := s.UpdateTaste(context.Background(), @@ -204,7 +180,7 @@ func TestUpdateTaste_EnrichedTagScale(t *testing.T) { } func TestUpdateTaste_EraScale(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s := newService(t, pool) // In-range update persists into cache + the assembled taste config. if err := s.UpdateTaste(context.Background(), @@ -225,7 +201,7 @@ func TestUpdateTaste_EraScale(t *testing.T) { } func TestUpdateTaste_MoodScale(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s := newService(t, pool) if err := s.UpdateTaste(context.Background(), map[string]float64{"mood_scale": 0.8}); err != nil { @@ -244,7 +220,7 @@ func TestUpdateTaste_MoodScale(t *testing.T) { } func TestReset_RestoresShippedAndAudits(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s := newService(t, pool) // Reset with nothing changed is a no-op (no audit row). if err := s.Reset(context.Background(), ScopeDailyMix); err != nil { @@ -270,7 +246,7 @@ func TestReset_RestoresShippedAndAudits(t *testing.T) { } func TestUpdate_NoOpWritesNoAudit(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) s := newService(t, pool) shipped := ShippedRadioWeights() if err := s.UpdateProfile(context.Background(), ScopeRadio, diff --git a/internal/scrobble/queue_test.go b/internal/scrobble/queue_test.go index 69dd33a2..01b22c27 100644 --- a/internal/scrobble/queue_test.go +++ b/internal/scrobble/queue_test.go @@ -2,15 +2,11 @@ package scrobble import ( "context" - "io" - "log/slog" - "os" "testing" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/secret" @@ -18,22 +14,7 @@ import ( func testPool(t *testing.T) (*pgxpool.Pool, *dbq.Queries) { t.Helper() - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) return pool, dbq.New(pool) } diff --git a/internal/secret/stored_test.go b/internal/secret/stored_test.go index 853172b0..5457880a 100644 --- a/internal/secret/stored_test.go +++ b/internal/secret/stored_test.go @@ -3,45 +3,19 @@ package secret_test import ( "context" "fmt" - "io" - "log/slog" - "os" "testing" "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/secret" ) -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - // Every listed column exists, so a renamed or dropped column fails here // rather than leaving a credential unsealed. func TestColumnsExistInTheSchema_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) for _, c := range secret.Columns { var n int err := pool.QueryRow(context.Background(), @@ -57,7 +31,7 @@ func TestColumnsExistInTheSchema_Integration(t *testing.T) { // A database written before sealing existed is sealed in place at startup, // every value opens to what it held, and a second pass has nothing to do. func TestSealStoredSealsWhatIsInTheClear_Integration(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 07677cab..e2c61a40 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -7,18 +7,16 @@ import ( "log/slog" "net/http" "net/http/httptest" - "os" "strings" "testing" "time" "github.com/go-chi/chi/v5" - "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/auth" "git.fabledsword.com/bvandeusen/minstrel/internal/config" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/library" "git.fabledsword.com/bvandeusen/minstrel/internal/subsonic" ) @@ -165,18 +163,7 @@ func TestRouter_RestPathNotSwallowedBySPA(t *testing.T) { // // Gated on MINSTREL_TEST_DATABASE_URL like other integration-leaning tests. func TestRouter_AdminSubtreeNotShadowed(t *testing.T) { - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) + pool := dbtest.Open(t) // Seed a test admin user + session so the request actually reaches the // inner route lookup (auth-middleware short-circuits don't catch shadowing). diff --git a/internal/similarity/worker_integration_test.go b/internal/similarity/worker_integration_test.go index aeabeb79..b96624eb 100644 --- a/internal/similarity/worker_integration_test.go +++ b/internal/similarity/worker_integration_test.go @@ -8,7 +8,6 @@ import ( "log/slog" "net/http" "net/http/httptest" - "os" "strings" "sync" "sync/atomic" @@ -18,7 +17,6 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/scrobble/listenbrainz" @@ -26,22 +24,7 @@ import ( func testPool(t *testing.T) (*pgxpool.Pool, *dbq.Queries) { t.Helper() - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) return pool, dbq.New(pool) } diff --git a/internal/subsonic/albumlist_test.go b/internal/subsonic/albumlist_test.go index da498be3..37428668 100644 --- a/internal/subsonic/albumlist_test.go +++ b/internal/subsonic/albumlist_test.go @@ -3,11 +3,8 @@ package subsonic import ( "context" "encoding/json" - "io" - "log/slog" "net/http" "net/http/httptest" - "os" "slices" "testing" "time" @@ -15,7 +12,6 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) @@ -37,22 +33,7 @@ type playHistoryFixture struct { // E: played many times by another user (in neither list) func seedPlayHistory(t *testing.T) playHistoryFixture { t.Helper() - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/subsonic/getalbum_test.go b/internal/subsonic/getalbum_test.go index 582b3e60..8297f290 100644 --- a/internal/subsonic/getalbum_test.go +++ b/internal/subsonic/getalbum_test.go @@ -3,16 +3,10 @@ package subsonic import ( "context" "encoding/json" - "io" - "log/slog" "net/http" "net/http/httptest" - "os" "testing" - "github.com/jackc/pgx/v5/pgxpool" - - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) @@ -20,22 +14,7 @@ import ( // A compilation's songs are credited to their own performers, as Subsonic // clients show them, not all to Various Artists. func TestGetAlbum_EachSongCreditsItsOwnArtist(t *testing.T) { - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/subsonic/mixes_test.go b/internal/subsonic/mixes_test.go index 6af7f479..4bbbc5ee 100644 --- a/internal/subsonic/mixes_test.go +++ b/internal/subsonic/mixes_test.go @@ -8,7 +8,6 @@ import ( "math/rand/v2" "net/http" "net/http/httptest" - "os" "slices" "strings" "testing" @@ -16,7 +15,6 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists" @@ -63,25 +61,11 @@ type picksFixture struct { func seedPicks(t *testing.T) picksFixture { t.Helper() - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) + var err error f := picksFixture{pool: pool, tracks: map[string]dbq.Track{}, albums: map[string]dbq.Album{}} if f.user, err = q.CreateUser(ctx, dbq.CreateUserParams{ Username: dbtest.TestUserPrefix + "listener", PasswordHash: "x", ApiTokenHash: "x", diff --git a/internal/subsonic/scrobble_test.go b/internal/subsonic/scrobble_test.go index 8cfcfcce..1a010c28 100644 --- a/internal/subsonic/scrobble_test.go +++ b/internal/subsonic/scrobble_test.go @@ -7,13 +7,11 @@ import ( "net/http" "net/http/httptest" "net/url" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playevents" @@ -21,22 +19,7 @@ import ( func testScrobblePool(t *testing.T) (*pgxpool.Pool, dbq.User, dbq.Track) { t.Helper() - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) q := dbq.New(pool) u, err := q.CreateUser(context.Background(), dbq.CreateUserParams{ Username: dbtest.TestUserPrefix + "tester", PasswordHash: "x", ApiTokenHash: "x", IsAdmin: false, diff --git a/internal/subsonic/star_test.go b/internal/subsonic/star_test.go index 40a0d323..7d04834a 100644 --- a/internal/subsonic/star_test.go +++ b/internal/subsonic/star_test.go @@ -8,13 +8,11 @@ import ( "net/http" "net/http/httptest" "net/url" - "os" "testing" "time" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/playevents" @@ -22,22 +20,7 @@ import ( func testStarPool(t *testing.T) (*pgxpool.Pool, dbq.User, dbq.Track, dbq.Album, dbq.Artist) { t.Helper() - if testing.Short() { - t.Skip("skipping in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) + pool := dbtest.Pool(t) q := dbq.New(pool) u, _ := q.CreateUser(context.Background(), dbq.CreateUserParams{ Username: dbtest.TestUserPrefix + "tester", PasswordHash: "x", ApiTokenHash: "x", IsAdmin: false, diff --git a/internal/sync/changes_test.go b/internal/sync/changes_test.go index fc674acd..553a1629 100644 --- a/internal/sync/changes_test.go +++ b/internal/sync/changes_test.go @@ -2,43 +2,17 @@ package sync_test import ( "context" - "io" - "log/slog" - "os" "testing" - "github.com/jackc/pgx/v5/pgxpool" "github.com/stretchr/testify/require" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/sync" ) -func testPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func TestLogChange_WritesRowInTx(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() tx, err := pool.Begin(ctx) @@ -59,7 +33,7 @@ func TestLogChange_WritesRowInTx(t *testing.T) { } func TestLogChange_RollbackDoesNotPersist(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() q := dbq.New(pool) diff --git a/internal/sync/compactor_test.go b/internal/sync/compactor_test.go index 49bb13c9..53b99255 100644 --- a/internal/sync/compactor_test.go +++ b/internal/sync/compactor_test.go @@ -10,6 +10,7 @@ import ( "github.com/jackc/pgx/v5" "github.com/stretchr/testify/require" + "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/sync" ) @@ -18,7 +19,7 @@ import ( // what a newer row supersedes, and deletes past their retention, raising the // trimmed mark past the newest delete it dropped. func TestCompact_KeepsEachEntitysLatestChange_Integration(t *testing.T) { - pool := testPool(t) + pool := dbtest.Pool(t) ctx := context.Background() old := time.Now().Add(-90 * 24 * time.Hour) recent := time.Now().Add(-time.Hour) diff --git a/internal/taste/profile_db_test.go b/internal/taste/profile_db_test.go index fe9a27b3..14f62da8 100644 --- a/internal/taste/profile_db_test.go +++ b/internal/taste/profile_db_test.go @@ -6,7 +6,6 @@ import ( "fmt" "io" "log/slog" - "os" "path/filepath" "sync/atomic" "testing" @@ -16,7 +15,6 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" ) @@ -25,27 +23,6 @@ var seedCounter uint64 func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, discardLogger()); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func seedUser(t *testing.T, pool *pgxpool.Pool, name string) dbq.User { t.Helper() u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{ @@ -142,7 +119,7 @@ func tagWeight(t *testing.T, pool *pgxpool.Pool, userID pgtype.UUID, tag string) // positive weight; an early-skipped artist earns a negative one. Genre tags // follow the same sign. func TestBuildTasteProfile_PositiveVsNegative(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) now := time.Now().UTC() u := seedUser(t, pool, "tp1") @@ -176,7 +153,7 @@ func TestBuildTasteProfile_PositiveVsNegative(t *testing.T) { // completed plays must NOT make a loved artist net-negative (the user's // concern that a track-dislike shouldn't tank the artist). func TestBuildTasteProfile_AggregationProtectsArtist(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) now := time.Now().UTC() u := seedUser(t, pool, "tp2") fav := seedArtist(t, pool, "Fav") @@ -202,7 +179,7 @@ func TestBuildTasteProfile_AggregationProtectsArtist(t *testing.T) { // TestBuildTasteProfile_ArtistLikeBonus: an explicitly-liked artist with no // plays still earns a positive weight from the like bonus. func TestBuildTasteProfile_ArtistLikeBonus(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) u := seedUser(t, pool, "tp3") liked := seedArtist(t, pool, "LikedOnly") if _, err := pool.Exec(context.Background(), @@ -222,7 +199,7 @@ func TestBuildTasteProfile_ArtistLikeBonus(t *testing.T) { // TestBuildTasteProfile_AtomicReplace: a second build replaces, not appends. func TestBuildTasteProfile_AtomicReplace(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) ctx := context.Background() now := time.Now().UTC() u := seedUser(t, pool, "tp4") diff --git a/internal/tracks/service_test.go b/internal/tracks/service_test.go index 93edf459..b9852b58 100644 --- a/internal/tracks/service_test.go +++ b/internal/tracks/service_test.go @@ -3,16 +3,12 @@ package tracks import ( "context" "errors" - "io" - "log/slog" - "os" "path/filepath" "testing" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" - "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/dbtest" "git.fabledsword.com/bvandeusen/minstrel/internal/library" @@ -20,27 +16,6 @@ import ( // --- test seed helpers (inlined; mirrors quarantine patterns) ----------- -func newPool(t *testing.T) *pgxpool.Pool { - t.Helper() - if testing.Short() { - t.Skip("skipping integration test in -short mode") - } - dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil { - t.Fatalf("migrate: %v", err) - } - pool, err := pgxpool.New(context.Background(), dsn) - if err != nil { - t.Fatalf("pool: %v", err) - } - t.Cleanup(pool.Close) - dbtest.ResetDB(t, pool) - return pool -} - func seedAdmin(t *testing.T, pool *pgxpool.Pool, name string) dbq.User { t.Helper() u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{ @@ -108,7 +83,7 @@ func markMissing(t *testing.T, pool *pgxpool.Pool, ids ...pgtype.UUID) { } func TestForgetTracks_NotFound(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := seedAdmin(t, pool, "alice") var bogus pgtype.UUID bogus.Bytes = [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} @@ -123,7 +98,7 @@ func TestForgetTracks_NotFound(t *testing.T) { // A track that has its file plays, and is not forgotten; nor is the waiting // track asked about with it. func TestForgetTracks_RefusesATrackThatHasItsFile(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := seedAdmin(t, pool, "alice") dir := t.TempDir() _, _, present := seedArtistAlbumTrack(t, pool, "Present", "", filepath.Join(dir, "p.mp3")) @@ -145,7 +120,7 @@ func TestForgetTracks_RefusesATrackThatHasItsFile(t *testing.T) { // Forget deletes the waiting tracks, tidies away the album and artist they // leave empty, and names each in the audit log. func TestForgetTracks_DeletesWaitingTracksAndAudits(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := seedAdmin(t, pool, "alice") if _, err := pool.Exec(context.Background(), `DELETE FROM audit_log`); err != nil { t.Fatalf("reset audit_log: %v", err) @@ -185,7 +160,7 @@ func TestForgetTracks_DeletesWaitingTracksAndAudits(t *testing.T) { // An album that keeps another track is left alone. func TestForgetTracks_KeepsAnAlbumThatStillHasTracks(t *testing.T) { - pool := newPool(t) + pool := dbtest.Pool(t) admin := seedAdmin(t, pool, "alice") q := dbq.New(pool) ctx := context.Background()