Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
test(lark): isolate legacy receipt backfill databases (#9776)
沙雕的小鱼儿 boyfeiyub90696903ded
diff --git a/server/internal/integrations/lark/inbound_verification_backfill_test.go b/server/internal/integrations/lark/inbound_verification_backfill_test.goindex e3c494a3fd..ffa5dc7ef2 100644--- a/server/internal/integrations/lark/inbound_verification_backfill_test.go+++ b/server/internal/integrations/lark/inbound_verification_backfill_test.go@@ -18,10 +18,44 @@ func legacyReceiptFixture(t *testing.T) (*pgxpool.Pool, *testutil.Fixture) {if os.Getenv("DATABASE_URL") == "" {t.Skip("explicit disposable DATABASE_URL required")}- pool := channelScopeTestDB(t)+ // The backfill intentionally scans every workspace. A workspace fixture+ // on the shared test DB would also pick up other packages' active rows.+ pool := testutil.IsolatedDB(t, os.Getenv("DATABASE_URL"))return pool, testutil.New(pool, uuid.NewString(), uuid.NewString())}+func TestLegacyReceiptBackfillIsolatedFromSharedDatabase(t *testing.T) {+ if os.Getenv("DATABASE_URL") == "" {+ t.Skip("explicit disposable DATABASE_URL required")+ }+ shared, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(shared.Close)+ outside := testutil.New(shared, uuid.NewString(), uuid.NewString())+ installed := time.Date(2026, 10, 30, 0, 0, 0, 0, time.UTC)+ id := receiptInstallation(t, outside, "active", "feishu", installed, map[string]any{"app_id": "cli_" + uuid.NewString()})+ receiptHistory(t, outside, id, "feishu", installed)+ before := receiptConfig(t, shared, id)++ pool, fx := legacyReceiptFixture(t)+ local := receiptInstallation(t, fx, "active", "feishu", installed, map[string]any{"app_id": "cli_" + uuid.NewString()})+ receiptHistory(t, fx, local, "feishu", installed)+ n, err := db.New(pool).BackfillLegacyFeishuInboundReceipts(context.Background(), 100)+ if err != nil || n != 1 {+ t.Fatalf("updated=%d want 1 err=%v", n, err)+ }+ if receiptConfig(t, pool, local)["first_message_received_at"] == nil {+ t.Fatal("local history was not backfilled")+ }+ beforeJSON, _ := json.Marshal(before)+ afterJSON, _ := json.Marshal(receiptConfig(t, shared, id))+ if string(beforeJSON) != string(afterJSON) {+ t.Fatalf("backfill changed shared database fixture: %s want %s", afterJSON, beforeJSON)+ }+}+func receiptInstallation(t *testing.T, fx *testutil.Fixture, status, channel string, installed time.Time, config map[string]any) string {t.Helper()raw, err := json.Marshal(config)diff --git a/server/internal/testutil/isolated_db.go b/server/internal/testutil/isolated_db.gonew file mode 100644index 0000000000..21902175b5--- /dev/null+++ b/server/internal/testutil/isolated_db.go@@ -0,0 +1,122 @@+package testutil++import (+ "context"+ "net/url"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool"+)++// IsolatedDB creates an empty database on the explicitly supplied test server+// and applies the normal migration command, including its hooks and conditions.+// The role must have CREATEDB. Call from within the server source tree; cleanup+// closes the pool before dropping the database, after callers' fixture cleanups.+// Unlike workspace fixtures, this also isolates queries that scan all workspaces.+func IsolatedDB(t *testing.T, dsn string) *pgxpool.Pool {+ t.Helper()+ if dsn == "" {+ t.Fatal("isolated database requires an explicit disposable test DSN")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ admin, err := pgx.Connect(ctx, dsn)+ if err != nil {+ t.Fatalf("connect to test database server: %v", err)+ }+ t.Cleanup(func() {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := admin.Close(ctx); err != nil {+ t.Errorf("close test database admin connection: %v", err)+ }+ })++ name := "multica_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")+ ident := pgx.Identifier{name}.Sanitize()+ // template0 is empty even when the shared test database contains active+ // fixtures from other packages. Never clone those rows into this test.+ if _, err := admin.Exec(ctx, "CREATE DATABASE "+ident+" TEMPLATE template0"); err != nil {+ t.Fatalf("create isolated test database: %v", err)+ }+ t.Cleanup(func() {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if _, err := admin.Exec(ctx, "DROP DATABASE "+ident+" WITH (FORCE)"); err != nil {+ t.Errorf("drop isolated test database %s: %v", name, err)+ }+ })++ targetDSN := isolatedDatabaseDSN(t, dsn, name)+ root, err := os.Getwd()+ if err != nil {+ t.Fatal(err)+ }+ for {+ if _, err := os.Stat(filepath.Join(root, "cmd", "migrate", "main.go")); err == nil {+ break+ }+ parent := filepath.Dir(root)+ if parent == root {+ t.Fatal("server source directory not found for test database migrations")+ }+ root = parent+ }+ // Only the child receives the new DSN. Changing the process environment+ // would redirect other tests that are still using the shared database.+ migrateCtx, migrateCancel := context.WithTimeout(context.Background(), 2*time.Minute)+ defer migrateCancel()+ // Execute the migrator directly so cancellation terminates it, rather+ // than just the parent go-run process while the migrator keeps running.+ binary := filepath.Join(t.TempDir(), "migrate.exe")+ build := exec.CommandContext(migrateCtx, "go", "build", "-o", binary, "./cmd/migrate")+ build.Dir = root+ if output, err := build.CombinedOutput(); err != nil {+ t.Fatalf("build test database migrator: %v\n%s", err, output)+ }+ cmd := exec.CommandContext(migrateCtx, binary, "up")+ cmd.Dir = root+ cmd.Env = append(os.Environ(), "DATABASE_URL="+targetDSN)+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("migrate isolated test database: %v\n%s", err, output)+ }++ poolCtx, poolCancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer poolCancel()+ pool, err := pgxpool.New(poolCtx, targetDSN)+ if err != nil {+ t.Fatalf("open isolated test database: %v", err)+ }+ t.Cleanup(pool.Close)+ if err := pool.Ping(poolCtx); err != nil {+ t.Fatalf("ping isolated test database: %v", err)+ }+ return pool+}++func isolatedDatabaseDSN(t *testing.T, dsn, name string) string {+ t.Helper()+ if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {+ u, err := url.Parse(dsn)+ if err != nil {+ t.Fatal(err)+ }+ u.Path, u.RawPath = "/"+name, ""+ q := u.Query()+ // Both spellings override the URL path in pgx.+ q.Del("database")+ q.Del("dbname")+ u.RawQuery = q.Encode()+ return u.String()+ }+ // In keyword/value DSNs the last database setting wins. name contains+ // only the generated prefix and hex digits, so needs no value escaping.+ return dsn + " dbname=" + name+}diff --git a/server/internal/testutil/isolated_db_test.go b/server/internal/testutil/isolated_db_test.gonew file mode 100644index 0000000000..acb34b438e--- /dev/null+++ b/server/internal/testutil/isolated_db_test.go@@ -0,0 +1,64 @@+package testutil++import (+ "context"+ "os"+ "testing"++ "github.com/jackc/pgx/v5"+)++func TestIsolatedDatabaseDSN(t *testing.T) {+ for _, dsn := range []string{+ "postgres://tester:p%40ss@localhost:5432/original?sslmode=disable",+ "postgresql://tester:p%40ss@localhost:5432/original?database=override&dbname=other&sslmode=disable",+ "host=localhost port=5432 user=tester password='p@ss' dbname=original sslmode=disable",+ "host=localhost port=5432 user=tester password='p@ss' database=original dbname=override sslmode=disable",+ } {+ config, err := pgx.ParseConfig(isolatedDatabaseDSN(t, dsn, "multica_test_target"))+ if err != nil {+ t.Fatal(err)+ }+ if config.Database != "multica_test_target" || config.User != "tester" || config.Password != "p@ss" || config.TLSConfig != nil {+ t.Fatal("database override did not preserve the other connection settings")+ }+ }+}++func TestIsolatedDBCleanup(t *testing.T) {+ dsn := os.Getenv("DATABASE_URL")+ if dsn == "" {+ t.Skip("explicit disposable DATABASE_URL required")+ }+ var name string+ t.Run("migrated database", func(t *testing.T) {+ pool := IsolatedDB(t, dsn)+ var migrated bool+ if err := pool.QueryRow(context.Background(), `SELECT current_database(),+ to_regclass('public.channel_installation') IS NOT NULL AND+ to_regclass('public.channel_chat_session_binding') IS NOT NULL`).Scan(&name, &migrated); err != nil {+ t.Fatal(err)+ }+ if !migrated {+ t.Fatal("isolated database is missing migrated channel tables")+ }+ if os.Getenv("DATABASE_URL") != dsn {+ t.Fatal("isolated database changed process DATABASE_URL")+ }+ })+ if name == "" {+ t.Fatal("isolated database was not created")+ }+ admin, err := pgx.Connect(context.Background(), dsn)+ if err != nil {+ t.Fatal(err)+ }+ defer admin.Close(context.Background())+ var exists bool+ if err := admin.QueryRow(context.Background(), "SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname=$1)", name).Scan(&exists); err != nil {+ t.Fatal(err)+ }+ if exists {+ t.Fatal("isolated database survived test cleanup")+ }+}