//go:build integration package postgres_test import ( "context" "database/sql" "fmt" "os" "strconv" "strings" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" "github.com/pressly/goose/v3" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "mtusi-messenger/internal/config" "mtusi-messenger/internal/domain" "mtusi-messenger/internal/platform/password" "mtusi-messenger/internal/storage/postgres" "mtusi-messenger/internal/storage/postgres/migrations" _ "github.com/jackc/pgx/v5/stdlib" ) const templateDB = "messenger_template" var adminPool *pgxpool.Pool func envOr(key, fallback string) string { if value := os.Getenv(key); value != "" { return value } return fallback } func envInt(key string, fallback int) int { value := os.Getenv(key) if value == "" { return fallback } parsed, err := strconv.Atoi(value) if err != nil { return fallback } return parsed } func testConfig() config.Postgres { return config.Postgres{ Host: envOr("TEST_POSTGRES_HOST", "localhost"), Port: envInt("TEST_POSTGRES_PORT", 5432), Database: envOr("TEST_POSTGRES_DATABASE", "messenger"), User: envOr("TEST_POSTGRES_USER", "messenger"), Password: envOr("TEST_POSTGRES_PASSWORD", "messenger"), SSLMode: envOr("TEST_POSTGRES_SSL_MODE", "disable"), MaxConns: 5, MinConns: 1, MaxConnLifetime: time.Hour, MaxConnIdleTime: 30 * time.Minute, ConnectTimeout: 5 * time.Second, QueryTimeout: 5 * time.Second, } } func dsnFor(database string) string { cfg := testConfig() cfg.Database = database return cfg.DSN() } func TestMain(m *testing.M) { ctx := context.Background() var err error adminPool, err = pgxpool.New(ctx, dsnFor(testConfig().Database)) if err != nil { fmt.Fprintln(os.Stderr, "admin pool:", err) os.Exit(1) } if err := waitForDatabase(ctx, adminPool); err != nil { fmt.Fprintln(os.Stderr, "database is not ready:", err) os.Exit(1) } if err := recreateTemplate(ctx); err != nil { fmt.Fprintln(os.Stderr, "create template:", err) os.Exit(1) } code := m.Run() adminPool.Close() os.Exit(code) } func waitForDatabase(ctx context.Context, pool *pgxpool.Pool) error { var lastErr error for range 60 { err := pool.Ping(ctx) if err == nil { return nil } lastErr = err time.Sleep(500 * time.Millisecond) } return lastErr } func adminExec(ctx context.Context, query string) error { conn, err := adminPool.Acquire(ctx) if err != nil { return err } defer conn.Release() _, err = conn.Conn().PgConn().Exec(ctx, query).ReadAll() return err } const templateLockKey int64 = 0x6d657373656e6765 func withAdvisoryLock(ctx context.Context, shared bool, fn func() error) error { conn, err := adminPool.Acquire(ctx) if err != nil { return err } defer conn.Release() lock, unlock := "pg_advisory_lock", "pg_advisory_unlock" if shared { lock, unlock = "pg_advisory_lock_shared", "pg_advisory_unlock_shared" } if _, err := conn.Exec(ctx, "SELECT "+lock+"($1)", templateLockKey); err != nil { return err } defer func() { _, _ = conn.Exec(context.WithoutCancel(ctx), "SELECT "+unlock+"($1)", templateLockKey) }() return fn() } func recreateTemplate(ctx context.Context) error { return withAdvisoryLock(ctx, false, func() error { if err := adminExec(ctx, "DROP DATABASE IF EXISTS "+templateDB+" WITH (FORCE)"); err != nil { return err } if err := adminExec(ctx, "CREATE DATABASE "+templateDB); err != nil { return err } db, err := sql.Open("pgx", dsnFor(templateDB)) if err != nil { return err } defer func() { _ = db.Close() }() if err := db.PingContext(ctx); err != nil { return err } goose.SetBaseFS(migrations.FS) if err := goose.SetDialect("postgres"); err != nil { return err } return goose.Up(db, ".") }) } type BaseSuite struct { suite.Suite store *postgres.Store pool *pgxpool.Pool db string } func (s *BaseSuite) SetupTest() { ctx := s.T().Context() s.db = "test_" + strings.ReplaceAll(uuid.NewString(), "-", "") s.Require().NoError(withAdvisoryLock(ctx, true, func() error { return adminExec(ctx, "CREATE DATABASE "+s.db+" TEMPLATE "+templateDB) })) var err error s.pool, err = pgxpool.New(ctx, dsnFor(s.db)) s.Require().NoError(err) s.store = openStore(s.T(), s.db, nil) } func (s *BaseSuite) TearDownTest() { if s.store != nil { s.store.Close() } if s.pool != nil { s.pool.Close() } if s.db != "" { s.Require().NoError(adminExec(s.T().Context(), "DROP DATABASE "+s.db+" WITH (FORCE)")) } } const testIdempotencyTTL = 24 * time.Hour func openStore(t *testing.T, database string, override func(*config.Postgres)) *postgres.Store { t.Helper() return openStoreWithTTL(t, database, testIdempotencyTTL, override) } func openStoreWithTTL( t *testing.T, database string, idempotencyTTL time.Duration, override func(*config.Postgres), ) *postgres.Store { t.Helper() cfg := testConfig() cfg.Database = database if override != nil { override(&cfg) } store, err := postgres.New(t.Context(), cfg, idempotencyTTL) require.NoError(t, err) return store } func (s *BaseSuite) createUser(username string) domain.User { s.T().Helper() hash, err := password.Hash("strong-test-password") s.Require().NoError(err) user, err := s.store.Users().Create(s.T().Context(), domain.NewUser{ Username: username, DisplayName: "Пользователь " + username, PasswordHash: hash, }) s.Require().NoError(err) return user } func (s *BaseSuite) createChat(owner domain.User, members ...domain.User) domain.Chat { s.T().Helper() ids := []uuid.UUID{owner.ID} for _, member := range members { ids = append(ids, member.ID) } chat, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{ Title: "Чат", MemberIDs: ids, CallerID: owner.ID, }) s.Require().NoError(err) return chat }