Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
perf(tests): share one Postgres across the backend (#21349)
Danny Xu3d12ecbb9bf6
diff --git a/AGENTS.md b/AGENTS.mdindex a3f99eb86d..f5eeb31991 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -47,11 +47,13 @@ boot only if it needs a background runner, a real rollout, or the audit trailthose live in `backend/tests`, the only package that may start one; everythingelse asserts in `backend/api/v1` or `backend/store`.-Only `backend/store` and `backend/tests` may run a real metadata Postgres.-Everywhere else, extract the decide-and-convert half of a handler as functions-over plain data, and where state is genuinely read declare an interface beside-the handler and fake it, as `backend/api/mcp` does with `serverStore` — never-one interface over the whole store, which has 305 methods.+A package needing a real metadata Postgres shares one through+`testcontainer.MetadataMain` and `testcontainer.NewMetadataDB`, never its own+container. Prefer needing none: extract the+decide-and-convert half of a handler as functions over plain data, and where+state is genuinely read declare an interface beside the handler and fake it, as+`backend/api/mcp` does with `serverStore` — never one interface over the whole+store, which has 305 methods.Every fake needs a contract test run against the real store too, or it driftsinto testing itself.diff --git a/backend/api/auth/internal_interceptor_livestate_test.go b/backend/api/auth/internal_interceptor_livestate_test.goindex 4bfd1b9ca1..13efd44b16 100644--- a/backend/api/auth/internal_interceptor_livestate_test.go+++ b/backend/api/auth/internal_interceptor_livestate_test.go@@ -6,14 +6,14 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""google.golang.org/protobuf/types/known/emptypb""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store"_ "github.com/bytebase/bytebase/backend/plugin/db/pg"@@ -49,24 +49,14 @@ func newProcedureRequest(t *testing.T, bearer string) *procedureRequest {// resolvePrincipal has real state to re-resolve against.func newLiveStore(t *testing.T) *store.Store {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })+ db, st, _ := testcontainer.NewMetadataDB(t)- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))_, err := db.ExecContext(ctx, fmt.Sprintf(`INSERT INTO workspace (resource_id) VALUES ('%s');INSERT INTO principal (name, email, password_hash) VALUES ('live', '%s', 'unused');`, liveWorkspace, liveUserEmail))require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- st, err := store.New(ctx, pgURL, false)- require.NoError(t, err)-_, err = st.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{Workspace: liveWorkspace,Member: common.FormatUserEmail(liveUserEmail),diff --git a/backend/api/auth/main_test.go b/backend/api/auth/main_test.gonew file mode 100644index 0000000000..da5bfddf51--- /dev/null+++ b/backend/api/auth/main_test.go@@ -0,0 +1,9 @@+package auth++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/api/lsp/main_test.go b/backend/api/lsp/main_test.gonew file mode 100644index 0000000000..c7ff522aab--- /dev/null+++ b/backend/api/lsp/main_test.go@@ -0,0 +1,9 @@+package lsp++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/api/lsp/project_instance_metadata_test.go b/backend/api/lsp/project_instance_metadata_test.goindex 3574efc7bb..4ed93c8fea 100644--- a/backend/api/lsp/project_instance_metadata_test.go+++ b/backend/api/lsp/project_instance_metadata_test.go@@ -2,24 +2,20 @@ package lspimport ("context"- "fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")func TestMetadataProjectInstanceScope(t *testing.T) {ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO project (resource_id, workspace, name) VALUES@@ -28,11 +24,6 @@ func TestMetadataProjectInstanceScope(t *testing.T) {`)require.NoError(t, err)- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })-projectID := "project-a"instanceID := "project-instance"_, err = stores.CreateInstance(ctx, &store.InstanceMessage{diff --git a/backend/api/mcp/main_test.go b/backend/api/mcp/main_test.gonew file mode 100644index 0000000000..74d60b064c--- /dev/null+++ b/backend/api/mcp/main_test.go@@ -0,0 +1,9 @@+package mcp++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/api/mcp/server_killswitch_test.go b/backend/api/mcp/server_killswitch_test.goindex be8424d5b1..f467f89ec9 100644--- a/backend/api/mcp/server_killswitch_test.go+++ b/backend/api/mcp/server_killswitch_test.go@@ -2,23 +2,22 @@ package mcpimport ("context"- "fmt""net/http""net/http/httptest""strings""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/golang-jwt/jwt/v5""github.com/labstack/echo/v5""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store"_ "github.com/bytebase/bytebase/backend/plugin/db/pg"@@ -31,24 +30,13 @@ import (// blocks the disabled workspace.func TestMCPKillSwitchEndToEnd(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-disabled'), ('ws-open');`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- s, err := store.New(ctx, pgURL, false)- require.NoError(t, err)-// Both workspaces have the metadata row required after migration._, err = s.UpsertSetting(ctx, &store.SettingMessage{Name: storepb.SettingName_MCP,@@ -99,24 +87,13 @@ func TestMCPKillSwitchEndToEnd(t *testing.T) {// truth on the next request.func TestMCPKillSwitchBypassesSettingCache(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, s, _ := testcontainer.NewMetadataDBWithCache(t, true)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-cached');`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- s, err := store.New(ctx, pgURL, true /* enableCache */)- require.NoError(t, err)-// The explicit default row has to exist for the out-of-band flip below to// have something to write into._, err = s.UpsertSetting(ctx, &store.SettingMessage{@@ -196,11 +173,7 @@ func tokenForWorkspace(t *testing.T, secret, workspaceID string) string {// value no Bytebase write produces.func TestMCPCeilingStoredValueFailsClosed(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, _, pgURL := testcontainer.NewMetadataDB(t)rows := []struct {workspace string@@ -251,12 +224,9 @@ func TestMCPCeilingStoredValueFailsClosed(t *testing.T) {}}- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )s, err := store.New(ctx, pgURL, false)require.NoError(t, err)+ t.Cleanup(func() { require.NoError(t, s.Close()) })secret := "test-secret-key"profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}diff --git a/backend/api/mcp/tool_reauthorize_test.go b/backend/api/mcp/tool_reauthorize_test.goindex 7c31580d6c..93060bacbf 100644--- a/backend/api/mcp/tool_reauthorize_test.go+++ b/backend/api/mcp/tool_reauthorize_test.go@@ -2,23 +2,22 @@ package mcpimport ("context"- "fmt""net/http""net/http/httptest""strings""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/labstack/echo/v5""github.com/modelcontextprotocol/go-sdk/mcp""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store"_ "github.com/bytebase/bytebase/backend/plugin/db/pg"@@ -29,11 +28,8 @@ import (// tool operates on.func newReauthorizeTestServer(ctx context.Context, t *testing.T) (*Server, *store.Store, string) {t.Helper()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })+ db, st, _ := testcontainer.NewMetadataDB(t)- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-test');INSERT INTO setting (name, workspace, value)@@ -44,13 +40,6 @@ func newReauthorizeTestServer(ctx context.Context, t *testing.T) (*Server, *stor`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- st, err := store.New(ctx, pgURL, false)- require.NoError(t, err)-refreshToken := "refresh-token"_, err = st.CreateOAuth2RefreshToken(ctx, &store.OAuth2RefreshTokenMessage{TokenHash: auth.HashToken(refreshToken),diff --git a/backend/api/oauth2/consent_ceiling_test.go b/backend/api/oauth2/consent_ceiling_test.goindex b12cdfdea8..91affa1a13 100644--- a/backend/api/oauth2/consent_ceiling_test.go+++ b/backend/api/oauth2/consent_ceiling_test.go@@ -4,7 +4,6 @@ import ("context""crypto/sha256""encoding/base64"- "fmt""net/http""net/http/httptest""net/url"@@ -12,14 +11,14 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/labstack/echo/v5""github.com/pkg/errors""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/api/auth"- "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store"_ "github.com/bytebase/bytebase/backend/plugin/db/pg"@@ -39,11 +38,7 @@ import (// refusal assertion below green and fails only the row assertions.func TestConsentCeiling(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, st, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES@@ -60,13 +55,6 @@ func TestConsentCeiling(t *testing.T) {`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- st, err := store.New(ctx, pgURL, false)- require.NoError(t, err)-s := newTestService(st, "https://bb.example.com")auditRows := func(t *testing.T, workspace string) []*store.AuditLog {@@ -158,11 +146,8 @@ func TestConsentCeiling(t *testing.T) {// any grant is issued at all, before the requested mode is considered.func TestConsentCeilingRefusalIsNotAWideningPath(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })+ db, st, _ := testcontainer.NewMetadataDB(t)- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-disabled');INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');@@ -172,12 +157,6 @@ func TestConsentCeilingRefusalIsNotAWideningPath(t *testing.T) {`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- st, err := store.New(ctx, pgURL, false)- require.NoError(t, err)s := newTestService(st, "https://bb.example.com")for _, scope := range []string{"mcp:read-only", "mcp:read-write", ""} {@@ -237,11 +216,8 @@ func consentTo(t *testing.T, s *Service, workspaceID string, extra ...url.Values// nothing to fix.func TestConsentCeilingOutageIsNotARefusal(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })+ db, st, _ := testcontainer.NewMetadataDB(t)- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-outage');INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');@@ -250,13 +226,6 @@ func TestConsentCeilingOutageIsNotARefusal(t *testing.T) {`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- st, err := store.New(ctx, pgURL, false)- require.NoError(t, err)-s := newTestService(st, "https://bb.example.com")s.mcpCeiling = failingCeilingReader{err: errors.New("connection refused")}@@ -295,11 +264,8 @@ func (f failingCeilingReader) GetMCPSettingsUncached(context.Context, string) (*// this endpoint exists for the same reason, and says so in its own comment.func TestTokenIssuanceRechecksTheCeiling(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })+ db, st, _ := testcontainer.NewMetadataDB(t)- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-test');INSERT INTO principal (name, email, password_hash) VALUES ('demo', '[email protected]', 'unused');@@ -309,12 +275,6 @@ func TestTokenIssuanceRechecksTheCeiling(t *testing.T) {`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- st, err := store.New(ctx, pgURL, false)- require.NoError(t, err)s := newTestService(st, "https://bb.example.com")// Consent while MCP is on, so the grant is genuine and only the ceilingdiff --git a/backend/api/oauth2/grant_test.go b/backend/api/oauth2/grant_test.goindex 36e75eedb4..254eb52914 100644--- a/backend/api/oauth2/grant_test.go+++ b/backend/api/oauth2/grant_test.go@@ -5,7 +5,6 @@ import ("crypto/sha256""encoding/base64""encoding/json"- "fmt""html""net/http""net/http/httptest"@@ -15,16 +14,16 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/labstack/echo/v5""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/api/mcp""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store"_ "github.com/bytebase/bytebase/backend/plugin/db/pg"@@ -58,11 +57,7 @@ func TestConsentWorkspaceRequiresSessionClaim(t *testing.T) {// grant rather than whatever the client asks for.func TestResourceScopeGrantLifecycle(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, st, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-test');@@ -73,13 +68,6 @@ func TestResourceScopeGrantLifecycle(t *testing.T) {`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- st, err := store.New(ctx, pgURL, false)- require.NoError(t, err)-configured := newTestService(st, "https://bb.example.com")t.Run("authorization starts without an existing browser session", func(t *testing.T) {diff --git a/backend/api/oauth2/main_test.go b/backend/api/oauth2/main_test.gonew file mode 100644index 0000000000..386ac75fe8--- /dev/null+++ b/backend/api/oauth2/main_test.go@@ -0,0 +1,9 @@+package oauth2++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/api/v1/actuator_service_test.go b/backend/api/v1/actuator_service_test.goindex 8c3c2fef49..230bcb8af9 100644--- a/backend/api/v1/actuator_service_test.go+++ b/backend/api/v1/actuator_service_test.go@@ -3,18 +3,18 @@ package v1import ("context""errors"- "fmt""slices""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""google.golang.org/protobuf/encoding/protojson""google.golang.org/protobuf/reflect/protoreflect""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/component/sample""github.com/bytebase/bytebase/backend/component/sample/saas"@@ -22,20 +22,12 @@ import ("github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))-- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })+ _, stores, pgURL := testcontainer.NewMetadataDB(t)licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")require.NoError(t, err)@@ -46,7 +38,7 @@ func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {}sampleManager, err := saas.NewManager(stores,- fmt.Sprintf("postgresql://postgres:root-password@%s:%s/postgres?sslmode=disable", container.GetHost(), container.GetPort()),+ pgURL,nil,sample.ManagerOptions{ReplicaID: "replica-a"},)diff --git a/backend/api/v1/audit_mcp_provenance_test.go b/backend/api/v1/audit_mcp_provenance_test.goindex 87d18420e6..58dbf69950 100644--- a/backend/api/v1/audit_mcp_provenance_test.go+++ b/backend/api/v1/audit_mcp_provenance_test.go@@ -5,15 +5,15 @@ import ("fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store"_ "github.com/bytebase/bytebase/backend/plugin/db/pg"@@ -36,21 +36,12 @@ func (r *specRequest) Spec() connect.Spec {// CreateAuditLog has a real parent row to write under.func newAuditLiveStore(t *testing.T) *store.Store {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })+ db, st, _ := testcontainer.NewMetadataDB(t)- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))_, err := db.ExecContext(ctx, fmt.Sprintf(`INSERT INTO workspace (resource_id) VALUES ('%s')`, auditTestWorkspace))require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- st, err := store.New(ctx, pgURL, false)- require.NoError(t, err)return st}diff --git a/backend/api/v1/auth_service_lockout_test.go b/backend/api/v1/auth_service_lockout_test.goindex 35b4e764d0..8d896e9934 100644--- a/backend/api/v1/auth_service_lockout_test.go+++ b/backend/api/v1/auth_service_lockout_test.go@@ -2,10 +2,11 @@ package v1import ("context"- "fmt""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/pquerna/otp/totp""github.com/stretchr/testify/require"@@ -13,12 +14,10 @@ import ("github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/runner/cleaner""github.com/bytebase/bytebase/backend/store")@@ -431,15 +430,7 @@ func TestLoginAttemptRetentionOutlivesLockouts(t *testing.T) {func newAuthTestStore(t *testing.T) *store.Store {t.Helper()- ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))-- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })+ _, stores, _ := testcontainer.NewMetadataDB(t)return stores}diff --git a/backend/api/v1/auth_service_test.go b/backend/api/v1/auth_service_test.goindex 91120ea4d6..73fe93d051 100644--- a/backend/api/v1/auth_service_test.go+++ b/backend/api/v1/auth_service_test.go@@ -2,23 +2,22 @@ package v1import ("context"- "fmt""net/http""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/golang-jwt/jwt/v5""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -26,18 +25,10 @@ const authTestEnterpriseLicense = "eyJhbGciOiJSUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSfunc TestLoginAnnouncesPreAuthenticationWorkspace(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-test')`)require.NoError(t, err)- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })-t.Run("self-hosted singleton", func(t *testing.T) {service := &AuthService{store: stores, profile: &config.Profile{}}var auditWorkspaceID stringdiff --git a/backend/api/v1/database_diff_schema_project_test.go b/backend/api/v1/database_diff_schema_project_test.goindex a545738ac3..b58c2b656d 100644--- a/backend/api/v1/database_diff_schema_project_test.go+++ b/backend/api/v1/database_diff_schema_project_test.go@@ -2,17 +2,16 @@ package v1import ("context"- "fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -104,10 +103,7 @@ func TestDiffSchemaTargetProject(t *testing.T) {func setupDiffSchemaProjectTest(t *testing.T) (context.Context, *store.Store, string, map[string]string) {t.Helper()ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO project (resource_id, workspace, name) VALUES@@ -116,11 +112,6 @@ func setupDiffSchemaProjectTest(t *testing.T) (context.Context, *store.Store, st`)require.NoError(t, err)- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })-// A workspace-level instance whose databases sit in different projects: the// shape that lets one name reach across a project boundary.instanceID := "shared-instance"diff --git a/backend/api/v1/instance_descendant_service_test.go b/backend/api/v1/instance_descendant_service_test.goindex c55940e3e6..7355b44525 100644--- a/backend/api/v1/instance_descendant_service_test.go+++ b/backend/api/v1/instance_descendant_service_test.go@@ -2,17 +2,16 @@ package v1import ("context"- "fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -113,21 +112,13 @@ func setupWorkspaceInstanceDescendantServiceTest(t *testing.T) (context.Context,func setupInstanceDescendantServiceTest(t *testing.T, instanceProjectID *string) (context.Context, *store.Store, string, string, string, string) {t.Helper()ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO project (resource_id, workspace, name) VALUES ('project-a', 'default', 'Project A'), ('project-b', 'default', 'Project B');`)require.NoError(t, err)- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })-instanceID := "project-instance"_, err = stores.CreateInstance(ctx, &store.InstanceMessage{ResourceID: instanceID,diff --git a/backend/api/v1/interactive_project_database_test.go b/backend/api/v1/interactive_project_database_test.goindex 8fe6366c5a..5af82936c9 100644--- a/backend/api/v1/interactive_project_database_test.go+++ b/backend/api/v1/interactive_project_database_test.go@@ -2,19 +2,18 @@ package v1import ("context"- "fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""google.golang.org/protobuf/types/known/fieldmaskpb""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -132,20 +131,13 @@ func setupBOT36ProjectDatabase(t *testing.T) (context.Context, *store.Store, strt.Helper()ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")ctx = context.WithValue(ctx, common.UserContextKey, &store.UserMessage{Email: "[email protected]"})- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))- _, err := container.GetDB().ExecContext(ctx, `+ db, stores, _ := testcontainer.NewMetadataDB(t)+ _, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO project (resource_id, workspace, name) VALUES ('project-a', 'default', 'Project A'), ('other-project', 'default', 'Other Project');`)require.NoError(t, err)- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })-projectID := "project-a"instanceID := "instance-a"_, err = stores.CreateInstance(ctx, &store.InstanceMessage{diff --git a/backend/api/v1/issue_service_test.go b/backend/api/v1/issue_service_test.goindex b31b92f1f1..1683ff4703 100644--- a/backend/api/v1/issue_service_test.go+++ b/backend/api/v1/issue_service_test.go@@ -6,6 +6,8 @@ import ("slices""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"@@ -13,14 +15,12 @@ import ("google.golang.org/protobuf/types/known/fieldmaskpb""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/bus""github.com/bytebase/bytebase/backend/component/iam""github.com/bytebase/bytebase/backend/component/review""github.com/bytebase/bytebase/backend/component/webhook"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store"_ "github.com/bytebase/bytebase/backend/plugin/db/pg"@@ -1064,11 +1064,7 @@ func issueNames(issues []*v1pb.Issue) []string {func setupIssueServiceTestStore(ctx context.Context, t *testing.T) *store.Store {t.Helper()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');@@ -1077,14 +1073,6 @@ func setupIssueServiceTestStore(ctx context.Context, t *testing.T) *store.Store`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })-// SearchIssues authorizes the caller itself (CUSTOM auth), so the test// principal needs a role carrying bb.issues.get._, err = stores.PatchWorkspaceIamPolicy(ctx, &store.PatchIamPolicyMessage{diff --git a/backend/api/v1/main_test.go b/backend/api/v1/main_test.gonew file mode 100644index 0000000000..d23326da80--- /dev/null+++ b/backend/api/v1/main_test.go@@ -0,0 +1,9 @@+package v1++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/api/v1/mcp_info_test.go b/backend/api/v1/mcp_info_test.goindex 401c20442b..186b2016b0 100644--- a/backend/api/v1/mcp_info_test.go+++ b/backend/api/v1/mcp_info_test.go@@ -2,19 +2,18 @@ package v1import ("context"- "fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -25,15 +24,7 @@ import (// this is the backend receipt for what the page may disclose.func TestGetMCPInfoHandler(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))-- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })+ db, stores, _ := testcontainer.NewMetadataDB(t)licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")require.NoError(t, err)@@ -58,7 +49,7 @@ func TestGetMCPInfoHandler(t *testing.T) {}setCeiling := func(t *testing.T, value string) {t.Helper()- _, err := container.GetDB().ExecContext(ctx, `+ _, err := db.ExecContext(ctx, `INSERT INTO setting (name, workspace, value) VALUES ('MCP', $1, $2)ON CONFLICT (workspace, name) DO UPDATE SET value = EXCLUDED.value`,workspaceID, value)diff --git a/backend/api/v1/plan_service_test.go b/backend/api/v1/plan_service_test.goindex 9feb3c9f4b..597973cebb 100644--- a/backend/api/v1/plan_service_test.go+++ b/backend/api/v1/plan_service_test.go@@ -5,16 +5,16 @@ import ("fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""google.golang.org/protobuf/types/known/fieldmaskpb""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/bus"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -350,11 +350,7 @@ func TestCreatePlanRejectsSpecsWithoutConfig(t *testing.T) {func setupPlanServiceTestStore(ctx context.Context, t *testing.T) *store.Store {t.Helper()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');@@ -363,12 +359,5 @@ func setupPlanServiceTestStore(ctx context.Context, t *testing.T) *store.Store {`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- s, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, s.Close()) })return s}diff --git a/backend/api/v1/project_instance_lifecycle_api_test.go b/backend/api/v1/project_instance_lifecycle_api_test.goindex 2156059d7b..7f0401a8df 100644--- a/backend/api/v1/project_instance_lifecycle_api_test.go+++ b/backend/api/v1/project_instance_lifecycle_api_test.go@@ -3,18 +3,18 @@ package v1import ("context""errors"- "fmt""os""path/filepath""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/component/sample""github.com/bytebase/bytebase/backend/component/sample/selfhost"@@ -22,7 +22,6 @@ import (storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1""github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -237,10 +236,7 @@ func newInstanceServiceTestLicenseService(t *testing.T, stores *store.Store) *enfunc setupProjectInstanceLifecycleAPITest(t *testing.T) (context.Context, *store.Store, string, string, string) {t.Helper()ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO project (resource_id, workspace, name) VALUES@@ -249,11 +245,6 @@ func setupProjectInstanceLifecycleAPITest(t *testing.T) (context.Context, *store`)require.NoError(t, err)- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })-projectID := "project-a"instanceID := "project-instance"_, err = stores.CreateInstance(ctx, &store.InstanceMessage{diff --git a/backend/api/v1/project_instance_release_check_test.go b/backend/api/v1/project_instance_release_check_test.goindex f921446fc8..0cbaa93561 100644--- a/backend/api/v1/project_instance_release_check_test.go+++ b/backend/api/v1/project_instance_release_check_test.go@@ -5,15 +5,15 @@ import ("fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/sheet"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -130,10 +130,7 @@ func declarativeReleaseWithDisallowedStatement() *v1pb.Release {func setupProjectInstanceReleaseCheckTest(t *testing.T) (context.Context, *store.Store, string, string) {t.Helper()ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, "default")- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO project (resource_id, workspace, name) VALUES@@ -142,11 +139,6 @@ func setupProjectInstanceReleaseCheckTest(t *testing.T) (context.Context, *store`)require.NoError(t, err)- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })-projectID := "project-a"instanceID := "project-instance"_, err = stores.CreateInstance(ctx, &store.InstanceMessage{diff --git a/backend/api/v1/sample_project_instance_integration_test.go b/backend/api/v1/sample_project_instance_integration_test.goindex 1073be1873..cd64cb6ad0 100644--- a/backend/api/v1/sample_project_instance_integration_test.go+++ b/backend/api/v1/sample_project_instance_integration_test.go@@ -14,6 +14,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/jackc/pgx/v5""github.com/stretchr/testify/require"@@ -21,7 +23,6 @@ import ("github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/permission"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/component/dbfactory""github.com/bytebase/bytebase/backend/component/iam"@@ -31,7 +32,6 @@ import (storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1""github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"- "github.com/bytebase/bytebase/backend/migrator"_ "github.com/bytebase/bytebase/backend/plugin/db/pg"samplerunner "github.com/bytebase/bytebase/backend/runner/sample""github.com/bytebase/bytebase/backend/runner/schemasync"@@ -334,22 +334,18 @@ func newSampleProjectInstanceFixture(t *testing.T, clock func() time.Time) (contctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)t.Cleanup(cancel)- metadata := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { metadata.Close(context.Background()) })+ // Only the target is a container: it is a TLS server Bytebase connects to,+ // not metadata.target := testcontainer.GetTestTLSPgContainer(ctx, t)t.Cleanup(func() { target.Close(context.Background()) })- require.NoError(t, migrator.MigrateSchema(ctx, metadata.GetDB()))- _, err := metadata.GetDB().ExecContext(ctx, `+ metadataDB, stores, _ := testcontainer.NewMetadataDB(t)+ _, err := metadataDB.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('sample-workspace');INSERT INTO project (resource_id, workspace, name) VALUES ('sample-project', 'sample-workspace', 'Sample Project');`)require.NoError(t, err)- metadataURL := postgresTestURL(metadata)- stores, err := store.New(ctx, metadataURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })setSampleProjectInstanceTestEnvironment(ctx, t, stores, "sample-workspace")licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")@@ -391,14 +387,6 @@ func tlsPostgresTestURL(container *testcontainer.Container) string {)}-func postgresTestURL(container *testcontainer.Container) string {- return fmt.Sprintf(- "postgres://postgres:root-password@%s:%s/postgres?sslmode=disable",- container.GetHost(),- container.GetPort(),- )-}-type sampleProjectInstanceRecord struct {workspace stringproject stringdiff --git a/backend/common/testcontainer/metadata.go b/backend/common/testcontainer/metadata.gonew file mode 100644index 0000000000..0af47604d9--- /dev/null+++ b/backend/common/testcontainer/metadata.go@@ -0,0 +1,120 @@+// Shared metadata Postgres: one container for a whole test package instead of+// one per test. A package opts in with three lines:+//+// func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }+//+// and each test calls NewMetadataDB for its own copy of a template database+// migrated once. A copy costs 44ms against a 4.3s container.++package testcontainer++import (+ "context"+ "database/sql"+ "fmt"+ "sync"+ "sync/atomic"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/migrator"+ "github.com/bytebase/bytebase/backend/store"+)++const metadataTemplateDatabase = "bbtest_template"++var (+ metaHost, metaPort string+ metaAdminDB *sql.DB+ metaDatabaseSeq atomic.Int64+ metaOnce sync.Once+ metaContainer *Container+ metaErr error+)++// MetadataMain runs the package's tests and takes the shared Postgres down+// afterwards. Call it from the package's TestMain. Nothing starts until a test+// actually asks for a database, so `go test -run` over tests that need none+// still costs nothing and still works without Docker.+func MetadataMain(m *testing.M) {+ defer func() {+ if metaContainer != nil {+ metaContainer.Close(context.Background())+ }+ }()+ m.Run()+}++// startMetadata brings up the container and template on first use.+func startMetadata(t *testing.T) {+ t.Helper()+ metaOnce.Do(func() {+ ctx := context.Background()+ container, err := GetPgContainer(ctx)+ if err != nil {+ metaErr = err+ return+ }+ metaContainer = container+ metaHost, metaPort = container.GetHost(), container.GetPort()+ metaAdminDB = container.GetDB()+ metaErr = migrateTemplate(ctx)+ })+ require.NoError(t, metaErr)+}++func migrateTemplate(ctx context.Context) error {+ if _, err := metaAdminDB.ExecContext(ctx, "CREATE DATABASE "+metadataTemplateDatabase); err != nil {+ return err+ }+ db, err := sql.Open("pgx", metadataURL(metadataTemplateDatabase))+ if err != nil {+ return err+ }+ if err := migrator.MigrateSchema(ctx, db); err != nil {+ _ = db.Close()+ return err+ }+ // TEMPLATE refuses to copy a database that still has a session attached.+ return db.Close()+}++// NewMetadataDB gives the test its own migrated database: a raw handle for seeding, a+// Store for the code under test, and the URL for tests that open their own+// connections. The copies are not dropped; the container takes them with it.+func NewMetadataDB(t *testing.T) (*sql.DB, *store.Store, string) {+ t.Helper()+ return NewMetadataDBWithCache(t, false)+}++// NewMetadataDBWithCache is NewMetadataDB with the Store's cache enabled, for the few tests whose+// subject is the cache itself.+func NewMetadataDBWithCache(t *testing.T, enableCache bool) (*sql.DB, *store.Store, string) {+ t.Helper()+ startMetadata(t)+ ctx := context.Background()+ name := fmt.Sprintf("bbtest_%d", metaDatabaseSeq.Add(1))+ _, err := metaAdminDB.ExecContext(ctx,+ fmt.Sprintf("CREATE DATABASE %s TEMPLATE %s", name, metadataTemplateDatabase))+ require.NoError(t, err)++ dsn := metadataURL(name)+ db, err := sql.Open("pgx", dsn)+ require.NoError(t, err)+ s, err := store.New(ctx, dsn, enableCache)+ require.NoError(t, err)++ t.Cleanup(func() {+ require.NoError(t, s.Close())+ require.NoError(t, db.Close())+ })+ return db, s, dsn+}++// metadataURL is the URI form, which pgx accepts and which tests that hand a metadata+// URL to production code (the sample manager, for one) need verbatim.+func metadataURL(database string) string {+ return fmt.Sprintf("postgresql://postgres:root-password@%s:%s/%s?sslmode=disable",+ metaHost, metaPort, database)+}diff --git a/backend/component/recovery/main_test.go b/backend/component/recovery/main_test.gonew file mode 100644index 0000000000..da9528e851--- /dev/null+++ b/backend/component/recovery/main_test.go@@ -0,0 +1,9 @@+package recovery_test++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/component/recovery/service_test.go b/backend/component/recovery/service_test.goindex 58f98f12e3..16aee72f34 100644--- a/backend/component/recovery/service_test.go+++ b/backend/component/recovery/service_test.go@@ -2,22 +2,21 @@ package recovery_testimport ("context"- "fmt""slices""strings""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""golang.org/x/crypto/bcrypt""google.golang.org/protobuf/encoding/protojson""google.golang.org/protobuf/proto""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/recovery"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -624,16 +623,10 @@ func TestAddUserToWorkspace(t *testing.T) {}}-func setupRecoveryStore(ctx context.Context, t *testing.T) *store.Store {+func setupRecoveryStore(_ context.Context, t *testing.T) *store.Store {t.Helper()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))+ _, stores, _ := testcontainer.NewMetadataDB(t)- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres", container.GetHost(), container.GetPort())- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })return stores}diff --git a/backend/component/review/evaluator_test.go b/backend/component/review/evaluator_test.goindex 7c769131b7..10b22a6cae 100644--- a/backend/component/review/evaluator_test.go+++ b/backend/component/review/evaluator_test.go@@ -3,19 +3,18 @@ package reviewimport ("context""errors"- "fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""google.golang.org/genproto/googleapis/type/expr""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/bus""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator"// Registers the BigQuery parser handlers the same way backend/server// ultimate.go does for the server binary; statementTypesFromParser resolves@@ -882,11 +881,7 @@ func setupApprovalRunnerStore(ctx context.Context, t *testing.T) *store.Store {func setupApprovalRunnerStoreInWorkspace(ctx context.Context, t *testing.T, workspaceID string) *store.Store {t.Helper()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, "INSERT INTO workspace (resource_id) VALUES ($1)", workspaceID)require.NoError(t, err)@@ -895,13 +890,6 @@ func setupApprovalRunnerStoreInWorkspace(ctx context.Context, t *testing.T, work_, err = db.ExecContext(ctx, "INSERT INTO project (resource_id, workspace, name) VALUES ('project-a', $1, 'Project A')", workspaceID)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- s, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, s.Close()) })return s}diff --git a/backend/component/review/main_test.go b/backend/component/review/main_test.gonew file mode 100644index 0000000000..71d4b3dddf--- /dev/null+++ b/backend/component/review/main_test.go@@ -0,0 +1,9 @@+package review++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/component/review/workflow_test.go b/backend/component/review/workflow_test.goindex 04ad26d375..db8b85ed7d 100644--- a/backend/component/review/workflow_test.go+++ b/backend/component/review/workflow_test.go@@ -3,19 +3,18 @@ package reviewimport ("context""errors"- "fmt""sync""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""google.golang.org/protobuf/encoding/protojson""google.golang.org/protobuf/proto""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -1284,11 +1283,8 @@ func TestPlanMutationMakesPendingApprovalFindingStale(t *testing.T) {func setupWorkflowStore(ctx context.Context, t *testing.T) *store.Store {t.Helper()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })+ db, stores, _ := testcontainer.NewMetadataDB(t)- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO principal (name, email, password_hash) VALUES@@ -1300,13 +1296,6 @@ func setupWorkflowStore(ctx context.Context, t *testing.T) *store.Store {`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- stores, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })return stores}diff --git a/backend/enterprise/license_test.go b/backend/enterprise/license_test.goindex c37c3e4095..743262de71 100644--- a/backend/enterprise/license_test.go+++ b/backend/enterprise/license_test.go@@ -6,20 +6,19 @@ import ("crypto/rsa""crypto/x509""encoding/pem"- "fmt""math""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/golang-jwt/jwt/v5""github.com/hashicorp/golang-lru/v2/expirable""github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -161,16 +160,8 @@ func TestParseLicenseExpiredIsInvalid(t *testing.T) {func TestGetUserLimitUncached(t *testing.T) {ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })+ _, s, _ := testcontainer.NewMetadataDB(t)- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))-- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort())- s, err := store.New(ctx, pgURL, false)- require.NoError(t, err)t.Cleanup(func() { s.Close() })// Sign licenses with a test-only keypair so finite and expired licenses candiff --git a/backend/enterprise/main_test.go b/backend/enterprise/main_test.gonew file mode 100644index 0000000000..f9224c3090--- /dev/null+++ b/backend/enterprise/main_test.go@@ -0,0 +1,9 @@+package enterprise++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/runner/plancheck/database_group_test.go b/backend/runner/plancheck/database_group_test.goindex a1bdd9297a..7fc5ed4b93 100644--- a/backend/runner/plancheck/database_group_test.go+++ b/backend/runner/plancheck/database_group_test.go@@ -2,17 +2,16 @@ package plancheckimport ("context"- "fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""google.golang.org/genproto/googleapis/type/expr""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -123,11 +122,7 @@ func TestGetDatabaseGroupForPlanUsesDatabaseResourceName(t *testing.T) {func setupPlancheckStore(ctx context.Context, t *testing.T) *store.Store {t.Helper()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');@@ -135,13 +130,6 @@ func setupPlancheckStore(ctx context.Context, t *testing.T) *store.Store {`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- s, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, s.Close()) })return s}diff --git a/backend/runner/plancheck/main_test.go b/backend/runner/plancheck/main_test.gonew file mode 100644index 0000000000..b449e74fd2--- /dev/null+++ b/backend/runner/plancheck/main_test.go@@ -0,0 +1,9 @@+package plancheck++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/runner/schemasync/main_test.go b/backend/runner/schemasync/main_test.gonew file mode 100644index 0000000000..3df9c1015e--- /dev/null+++ b/backend/runner/schemasync/main_test.go@@ -0,0 +1,9 @@+package schemasync++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/runner/schemasync/syncer_test.go b/backend/runner/schemasync/syncer_test.goindex 488ae14baa..698085ea01 100644--- a/backend/runner/schemasync/syncer_test.go+++ b/backend/runner/schemasync/syncer_test.go@@ -2,20 +2,19 @@ package schemasyncimport ("context"- "fmt""testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/prometheus/client_golang/prometheus"dto "github.com/prometheus/client_model/go""github.com/stretchr/testify/require""google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/timestamppb"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/productmetrics"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -362,22 +361,12 @@ func TestSyncQueuedDatabasesProjectLookupFailureRecordsFailure(t *testing.T) {func setupSyncerStore(ctx context.Context, t *testing.T) *store.Store {t.Helper()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO project (resource_id, workspace, name) VALUES ('project-a', 'default', 'Project A');`)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- s, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, s.Close()) })return s}diff --git a/backend/runner/taskrun/main_test.go b/backend/runner/taskrun/main_test.gonew file mode 100644index 0000000000..3988cbbe54--- /dev/null+++ b/backend/runner/taskrun/main_test.go@@ -0,0 +1,9 @@+package taskrun++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/runner/taskrun/rollout_creator_test.go b/backend/runner/taskrun/rollout_creator_test.goindex 2cf26bd5ff..73608da8b9 100644--- a/backend/runner/taskrun/rollout_creator_test.go+++ b/backend/runner/taskrun/rollout_creator_test.go@@ -2,15 +2,14 @@ package taskrunimport ("context"- "fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/bus"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -382,11 +381,7 @@ func setupRolloutCreatorStoreInWorkspace(ctx context.Context, t *testing.T, workfunc setupRolloutCreatorStoreInWorkspaceWithCache(ctx context.Context, t *testing.T, workspaceID string, enableCache bool) *store.Store {t.Helper()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))+ db, s, _ := testcontainer.NewMetadataDBWithCache(t, enableCache)_, err := db.ExecContext(ctx, "INSERT INTO workspace (resource_id) VALUES ($1)", workspaceID)require.NoError(t, err)@@ -395,12 +390,5 @@ func setupRolloutCreatorStoreInWorkspaceWithCache(ctx context.Context, t *testin_, err = db.ExecContext(ctx, "INSERT INTO project (resource_id, workspace, name) VALUES ('project-a', $1, 'Project A')", workspaceID)require.NoError(t, err)- pgURL := fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- )- s, err := store.New(ctx, pgURL, enableCache)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, s.Close()) })return s}diff --git a/backend/server/main_test.go b/backend/server/main_test.gonew file mode 100644index 0000000000..4a1c42c9b2--- /dev/null+++ b/backend/server/main_test.go@@ -0,0 +1,9 @@+package server++import (+ "testing"++ "github.com/bytebase/bytebase/backend/common/testcontainer"+)++func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/server/metrics_test.go b/backend/server/metrics_test.goindex cc0d074d5c..f8042c7a3d 100644--- a/backend/server/metrics_test.go+++ b/backend/server/metrics_test.go@@ -2,7 +2,6 @@ package serverimport ("context"- "fmt""io""net/http""net/http/httptest"@@ -11,6 +10,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/labstack/echo/v5"metricpb "github.com/prometheus/client_model/go""github.com/prometheus/common/expfmt"@@ -18,12 +19,10 @@ import ("google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common"- "github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/component/productmetrics""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/migrator""github.com/bytebase/bytebase/backend/store")@@ -41,18 +40,7 @@ func newMetricsTestEcho(t *testing.T) (*echo.Echo, *store.Store, *enterprise.Licfunc newMetricsTestEchoWithCollector(t *testing.T) (*echo.Echo, *store.Store, *enterprise.LicenseService, *productmetrics.ProductMetrics) {t.Helper()- ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })-- db := container.GetDB()- require.NoError(t, migrator.MigrateSchema(ctx, db))-- pgURL := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort())- st, err := store.New(ctx, pgURL, false)- require.NoError(t, err)- t.Cleanup(func() { st.Close() })+ _, st, _ := testcontainer.NewMetadataDB(t)licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, st, false, "")require.NoError(t, err)diff --git a/backend/store/advisory_lock_test.go b/backend/store/advisory_lock_test.goindex ae6e4bd49b..c67ea0e900 100644--- a/backend/store/advisory_lock_test.go+++ b/backend/store/advisory_lock_test.go@@ -4,6 +4,8 @@ import ("context""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/store"@@ -11,7 +13,7 @@ import (func TestTryAdvisoryXactLockWithStringKeyScopesByKey(t *testing.T) {ctx := context.Background()- db, _, _ := newTestDB(t)+ db, _, _ := testcontainer.NewMetadataDB(t)tx1, err := db.BeginTx(ctx, nil)require.NoError(t, err)defer tx1.Rollback()diff --git a/backend/store/audit_log_mcp_filter_test.go b/backend/store/audit_log_mcp_filter_test.goindex 123ec7b3e4..97c0d9d84c 100644--- a/backend/store/audit_log_mcp_filter_test.go+++ b/backend/store/audit_log_mcp_filter_test.go@@ -4,6 +4,8 @@ import ("context""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -25,7 +27,7 @@ import (// rather than a query.func TestSearchAuditLogsMCPFilters(t *testing.T) {ctx := context.Background()- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-test')`)require.NoError(t, err)diff --git a/backend/store/audit_log_retention_test.go b/backend/store/audit_log_retention_test.goindex 657d01c9ae..d4ce2ea7a8 100644--- a/backend/store/audit_log_retention_test.go+++ b/backend/store/audit_log_retention_test.go@@ -10,6 +10,8 @@ import ("time""unsafe"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""google.golang.org/protobuf/encoding/protojson"@@ -118,7 +120,7 @@ func TestAuditLogRetentionFilterIncludesExactCutoffRow(t *testing.T) {func setupAuditLogRetentionTest(t *testing.T) (context.Context, *store.Store, *enterprise.LicenseService) {t.Helper()ctx := context.WithValue(context.Background(), common.WorkspaceIDContextKey, testAuditLogWorkspace)- _, stores, _ := newTestDB(t)+ _, stores, _ := testcontainer.NewMetadataDB(t)_, err := stores.GetDB().ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default')`)require.NoError(t, err)diff --git a/backend/store/instance_project_test.go b/backend/store/instance_project_test.goindex 615ad7778d..7c5d2b8c3d 100644--- a/backend/store/instance_project_test.go+++ b/backend/store/instance_project_test.go@@ -6,6 +6,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -16,7 +18,7 @@ func newInstanceProjectFixture(t *testing.T) (context.Context, *sql.DB, *store.St.Helper()ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)t.Cleanup(cancel)- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO project (resource_id, workspace, name, deleted) VALUESdiff --git a/backend/store/issue_comment_thread_test.go b/backend/store/issue_comment_thread_test.goindex 0f56785248..df9d95451a 100644--- a/backend/store/issue_comment_thread_test.go+++ b/backend/store/issue_comment_thread_test.go@@ -4,6 +4,8 @@ import ("context""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"@@ -27,7 +29,7 @@ func TestIssueCommentThreads(t *testing.T) {)ctx := context.Background()- db, stores, _ := newTestDB(t)+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx,`INSERT INTO workspace (resource_id) VALUES ($1)`, workspaceID)diff --git a/backend/store/issue_list_filter_integration_test.go b/backend/store/issue_list_filter_integration_test.goindex de7a7f75bc..fa135af176 100644--- a/backend/store/issue_list_filter_integration_test.go+++ b/backend/store/issue_list_filter_integration_test.go@@ -4,6 +4,8 @@ import ("context""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -22,7 +24,7 @@ import (// "<", excluding an issue at the exact boundary.func TestIssueListFilterEdgeCases(t *testing.T) {ctx := context.Background()- db, stores, _ := newTestDB(t)+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO principal (name, email, password_hash) VALUES ('c', '[email protected]', 'x');@@ -90,7 +92,7 @@ func TestIssueListFilterEdgeCases(t *testing.T) {// assertion in this file and fails this one.func TestIssueListNextApproverIsProjectScoped(t *testing.T) {ctx := context.Background()- db, stores, _ := newTestDB(t)+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO principal (name, email, password_hash) VALUES ('c', '[email protected]', 'x');diff --git a/backend/store/issue_service_concurrency_test.go b/backend/store/issue_service_concurrency_test.goindex a714ab3298..f9c34de267 100644--- a/backend/store/issue_service_concurrency_test.go+++ b/backend/store/issue_service_concurrency_test.go@@ -13,6 +13,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"connectrpc.com/connect""github.com/stretchr/testify/require""google.golang.org/protobuf/types/known/fieldmaskpb"@@ -506,7 +508,7 @@ func issueNames(issues []*v1pb.Issue) []string {func setupIssueServiceTestStore(ctx context.Context, t *testing.T) *store.Store {t.Helper()- db, stores, _ := newTestDB(t)+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO principal (name, email, password_hash) VALUES ('creator', '[email protected]', 'unused');diff --git a/backend/store/lock_order_test.go b/backend/store/lock_order_test.goindex ba0da02e89..8d5521b47e 100644--- a/backend/store/lock_order_test.go+++ b/backend/store/lock_order_test.go@@ -7,6 +7,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/store"@@ -25,7 +27,7 @@ func newStorePostgresFixture(t *testing.T, seedSQL string) *storePostgresFixturet.Helper()ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)t.Cleanup(cancel)- db, s, url := newTestDB(t)+ db, s, url := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');diff --git a/backend/store/login_attempt_test.go b/backend/store/login_attempt_test.goindex de19935a9b..cc06904b5a 100644--- a/backend/store/login_attempt_test.go+++ b/backend/store/login_attempt_test.go@@ -7,6 +7,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -21,7 +23,7 @@ import (// forgets after D of quiet, and success deletes the row.func TestLoginAttemptClaim(t *testing.T) {ctx := context.Background()- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)const window = 10 * time.Minute@@ -193,7 +195,7 @@ func TestLoginAttemptClaim(t *testing.T) {// the lockout, under the window rule EMAIL_CODE_SEND selects.func TestSendBudgetClaim(t *testing.T) {ctx := context.Background()- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)const window = time.Hourconst kind = storepb.LoginAttemptKind_EMAIL_CODE_SENDdiff --git a/backend/store/main_test.go b/backend/store/main_test.goindex 85ff485a0a..44e7949164 100644--- a/backend/store/main_test.go+++ b/backend/store/main_test.go@@ -1,85 +1,9 @@package store_testimport (- "context"- "database/sql"- "fmt"- "sync/atomic""testing"- "github.com/stretchr/testify/require"-"github.com/bytebase/bytebase/backend/common/testcontainer"- "github.com/bytebase/bytebase/backend/migrator"- "github.com/bytebase/bytebase/backend/store")-const templateDatabase = "bbtest_template"--var (- pgHost, pgPort string- adminDB *sql.DB- databaseSeq atomic.Int64-)--// TestMain starts one Postgres for the package and migrates a template-// database once. Tests copy the template instead of starting a container:-// a copy costs 44ms against 4.3s.-func TestMain(m *testing.M) {- ctx := context.Background()- container, err := testcontainer.GetPgContainer(ctx)- if err != nil {- panic(err)- }- defer container.Close(ctx)-- pgHost, pgPort = container.GetHost(), container.GetPort()- adminDB = container.GetDB()- if err := migrateTemplate(ctx); err != nil {- panic(err)- }- m.Run()-}--func migrateTemplate(ctx context.Context) error {- if _, err := adminDB.ExecContext(ctx, "CREATE DATABASE "+templateDatabase); err != nil {- return err- }- db, err := sql.Open("pgx", fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=%s",- pgHost, pgPort, templateDatabase))- if err != nil {- return err- }- if err := migrator.MigrateSchema(ctx, db); err != nil {- _ = db.Close()- return err- }- // TEMPLATE refuses to copy a database that still has a session attached.- return db.Close()-}--// newTestDB gives the test its own migrated database: a raw handle for seeding,-// a Store for the code under test, and the URL for tests that open their own-// connections. The copies are not dropped; the container takes them with it.-func newTestDB(t *testing.T) (*sql.DB, *store.Store, string) {- t.Helper()- ctx := context.Background()- name := fmt.Sprintf("bbtest_%d", databaseSeq.Add(1))- _, err := adminDB.ExecContext(ctx,- fmt.Sprintf("CREATE DATABASE %s TEMPLATE %s", name, templateDatabase))- require.NoError(t, err)-- url := fmt.Sprintf("host=%s port=%s user=postgres password=root-password database=%s",- pgHost, pgPort, name)- db, err := sql.Open("pgx", url)- require.NoError(t, err)- s, err := store.New(ctx, url, false)- require.NoError(t, err)-- t.Cleanup(func() {- require.NoError(t, s.Close())- require.NoError(t, db.Close())- })- return db, s, url-}+func TestMain(m *testing.M) { testcontainer.MetadataMain(m) }diff --git a/backend/store/oauth2_consume_test.go b/backend/store/oauth2_consume_test.goindex 4018f0e348..8c20f258db 100644--- a/backend/store/oauth2_consume_test.go+++ b/backend/store/oauth2_consume_test.go@@ -6,6 +6,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -21,7 +23,7 @@ import (// and a second sequential redemption must observe consumed=false.func TestOAuth2AtomicConsume(t *testing.T) {ctx := context.Background()- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-test');diff --git a/backend/store/oauth2_workspace_test.go b/backend/store/oauth2_workspace_test.goindex d824d7b5e0..7236dbb6ba 100644--- a/backend/store/oauth2_workspace_test.go+++ b/backend/store/oauth2_workspace_test.go@@ -5,6 +5,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -29,7 +31,7 @@ import (// singleton can take over.func TestOAuth2WorkspaceBinding(t *testing.T) {ctx := context.Background()- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)// Seed the minimal fixtures needed by the FK constraints on the OAuth2// tables: a workspace and a principal.diff --git a/backend/store/pagination_integration_test.go b/backend/store/pagination_integration_test.goindex bd4bda2970..dd1c76630f 100644--- a/backend/store/pagination_integration_test.go+++ b/backend/store/pagination_integration_test.go@@ -6,6 +6,8 @@ import ("fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -31,7 +33,7 @@ func TestPaginationStabilityAcrossProjects(t *testing.T) {)ctx := context.Background()- db, stores, _ := newTestDB(t)+ db, stores, _ := testcontainer.NewMetadataDB(t)projectIDs := make([]string, 0, projectCount)for i := range projectCount {@@ -109,7 +111,7 @@ func seedTiedIssues(ctx context.Context, t *testing.T, db *sql.DB, workspaceID s// changed", permanently, for that issue.func TestIssueCommentBatchKeepsInsertionOrder(t *testing.T) {ctx := context.Background()- db, stores, _ := newTestDB(t)+ db, stores, _ := testcontainer.NewMetadataDB(t)const (workspaceID = "comment-ws"diff --git a/backend/store/plan_check_run_test.go b/backend/store/plan_check_run_test.goindex 2573e51824..57bc755bd4 100644--- a/backend/store/plan_check_run_test.go+++ b/backend/store/plan_check_run_test.go@@ -4,6 +4,8 @@ import ("context""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -641,7 +643,7 @@ func TestFailStalePlanCheckRunsPreservesApprovalInputVersion(t *testing.T) {func setupPlanCheckRunVersionStore(ctx context.Context, t *testing.T) *store.Store {t.Helper()- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');diff --git a/backend/store/policy_project_iam_test.go b/backend/store/policy_project_iam_test.goindex f2403da4dc..77c1ec9fb2 100644--- a/backend/store/policy_project_iam_test.go+++ b/backend/store/policy_project_iam_test.go@@ -5,6 +5,8 @@ import ("fmt""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"@@ -22,7 +24,7 @@ import (// policy type, whose payload would then be unmarshalled as an IamPolicy.func TestListProjectIamPoliciesIsScoped(t *testing.T) {ctx := context.Background()- db, stores, _ := newTestDB(t)+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('ws-a'), ('ws-b');INSERT INTO project (resource_id, workspace, name) VALUESdiff --git a/backend/store/project_purge_cache_test.go b/backend/store/project_purge_cache_test.goindex 069521709f..7f5be1703f 100644--- a/backend/store/project_purge_cache_test.go+++ b/backend/store/project_purge_cache_test.go@@ -6,6 +6,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/store"@@ -18,7 +20,7 @@ func newProjectPurgeCacheFixture(t *testing.T) (context.Context, *sql.DB, *storet.Helper()ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)t.Cleanup(cancel)- db, _, url := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDBWithCache(t, true)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');INSERT INTO project (resource_id, workspace, name, deleted) VALUES@@ -28,9 +30,6 @@ func newProjectPurgeCacheFixture(t *testing.T) (context.Context, *sql.DB, *store`)require.NoError(t, err)- s, err := store.New(ctx, url, true)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, s.Close()) })return ctx, db, s}diff --git a/backend/store/sample_instance_test.go b/backend/store/sample_instance_test.goindex 18acf70c1b..ff2e24d63c 100644--- a/backend/store/sample_instance_test.go+++ b/backend/store/sample_instance_test.go@@ -6,6 +6,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/store"@@ -15,7 +17,7 @@ func newSampleInstanceFixture(t *testing.T) (context.Context, *store.Store) {t.Helper()ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)t.Cleanup(cancel)- db, stores, _ := newTestDB(t)+ db, stores, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES('workspace-a'), ('workspace-b'), ('workspace-c'), ('workspace-d');diff --git a/backend/store/setting_atomic_test.go b/backend/store/setting_atomic_test.goindex 4fd45b11f1..3633c4e4b4 100644--- a/backend/store/setting_atomic_test.go+++ b/backend/store/setting_atomic_test.go@@ -8,6 +8,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/pkg/errors""github.com/stretchr/testify/require""google.golang.org/protobuf/proto"@@ -29,13 +31,10 @@ func newSettingAtomicFixtureWithCache(t *testing.T, enableCache bool) (context.Ct.Helper()ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)t.Cleanup(cancel)- db, _, url := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDBWithCache(t, enableCache)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');`)require.NoError(t, err)- s, err := store.New(ctx, url, enableCache)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, s.Close()) })_, err = s.UpsertSetting(ctx, &store.SettingMessage{Name: storepb.SettingName_WORKSPACE_PROFILE,diff --git a/backend/store/task_run_batch_test.go b/backend/store/task_run_batch_test.goindex 30c1d62100..3e70f037e1 100644--- a/backend/store/task_run_batch_test.go+++ b/backend/store/task_run_batch_test.go@@ -5,6 +5,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/common"@@ -15,7 +17,7 @@ func TestCreatePendingTaskRunsRejectsMultipleProjects(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');diff --git a/backend/store/task_run_claim_test.go b/backend/store/task_run_claim_test.goindex ec7a5593cf..06f71c2ffd 100644--- a/backend/store/task_run_claim_test.go+++ b/backend/store/task_run_claim_test.go@@ -6,6 +6,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require")@@ -95,7 +97,7 @@ func newTaskRunClaimFixture(t *testing.T, seedSQL string) *storePostgresFixturet.Helper()ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)t.Cleanup(cancel)- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');diff --git a/backend/store/task_run_pagination_test.go b/backend/store/task_run_pagination_test.goindex bb831185f8..d136a7c493 100644--- a/backend/store/task_run_pagination_test.go+++ b/backend/store/task_run_pagination_test.go@@ -6,6 +6,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""github.com/bytebase/bytebase/backend/store"@@ -19,7 +21,7 @@ func TestListTaskRunsPagination(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)defer cancel()- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default');diff --git a/backend/store/vcs_provider_user_test.go b/backend/store/vcs_provider_user_test.goindex 35806073eb..40c49cf69e 100644--- a/backend/store/vcs_provider_user_test.go+++ b/backend/store/vcs_provider_user_test.go@@ -6,6 +6,8 @@ import ("testing""time"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -242,7 +244,7 @@ func TestDeleteExpiredVCSProviderUsers(t *testing.T) {func setupVCSProviderUserStore(ctx context.Context, t *testing.T) (*store.Store, *sql.DB) {t.Helper()- db, s, _ := newTestDB(t)+ db, s, _ := testcontainer.NewMetadataDB(t)_, err := db.ExecContext(ctx, `INSERT INTO workspace (resource_id) VALUES ('default')`)require.NoError(t, err)diff --git a/backend/store/workspace_test.go b/backend/store/workspace_test.goindex c1d06555dc..1a1a5cd35c 100644--- a/backend/store/workspace_test.go+++ b/backend/store/workspace_test.go@@ -5,6 +5,8 @@ import ("slices""testing"+ "github.com/bytebase/bytebase/backend/common/testcontainer"+"github.com/stretchr/testify/require""google.golang.org/genproto/googleapis/type/expr""google.golang.org/protobuf/encoding/protojson"@@ -18,7 +20,7 @@ import (func TestCreateWorkspaceInitializesDefaults(t *testing.T) {ctx := context.Background()- _, stores, _ := newTestDB(t)+ _, stores, _ := testcontainer.NewMetadataDB(t)const workspaceID = "workspace-defaults"_, err := stores.CreateWorkspace(ctx, &store.WorkspaceMessage{@@ -72,7 +74,7 @@ func TestCreateWorkspaceInitializesDefaults(t *testing.T) {func TestListWorkspacesByEmailEvaluatesBindingConditions(t *testing.T) {ctx := context.Background()- db, stores, _ := newTestDB(t)+ db, stores, _ := testcontainer.NewMetadataDB(t)const email = "[email protected]"activeCondition := `request.time < timestamp("2099-01-01T00:00:00Z")`