// Package testenv starts disposable PostgreSQL and Valkey containers for tests // that exercise the real stores. Only _test files import it, so it never // reaches the server binary. The images match compose.yaml. package testenv import ( "context" "fmt" "os" "runtime" "sync" "testing" "time" "github.com/jackc/pgx/v5/pgxpool" "github.com/redis/go-redis/v9" "github.com/testcontainers/testcontainers-go" tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres" tcvalkey "github.com/testcontainers/testcontainers-go/modules/valkey" "messenger/internal/platform/postgres" "messenger/internal/platform/valkey" ) const ( PostgresImage = "postgres:18.6-alpine3.24@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873" ValkeyImage = "valkey/valkey:9.1.2-alpine3.24@sha256:48332870af354a799964c0012ae1194a0bf2bf894eb508f945810596dc2d8d11" ) // useDockerDesktopPipe names the Docker Desktop engine pipe explicitly on // Windows. Without DOCKER_HOST, testcontainers probes the pipe with a file // stat, which fails while the pipe is busy; with several test packages // starting containers at once that probe fails spuriously and the run panics. // Dialling the named host instead waits for a free pipe instance. var useDockerDesktopPipe = sync.OnceFunc(func() { if runtime.GOOS == "windows" && os.Getenv("DOCKER_HOST") == "" { _ = os.Setenv("DOCKER_HOST", "npipe:////./pipe/docker_engine") } }) // DB is a migrated PostgreSQL instance. type DB struct { Pool *pgxpool.Pool DSN string container *tcpostgres.PostgresContainer } func StartPostgres(ctx context.Context) (*DB, error) { useDockerDesktopPipe() c, err := tcpostgres.Run(ctx, PostgresImage, tcpostgres.WithDatabase("messenger"), tcpostgres.WithUsername("messenger"), tcpostgres.WithPassword("messenger"), tcpostgres.BasicWaitStrategies(), ) if err != nil { return nil, fmt.Errorf("start postgres: %w", err) } db := &DB{container: c} db.DSN, err = c.ConnectionString(ctx, "sslmode=disable") if err != nil { db.Close() return nil, fmt.Errorf("postgres address: %w", err) } db.Pool, err = postgres.NewPool(ctx, db.DSN, 10) if err != nil { db.Close() return nil, err } if _, err := postgres.Migrate(ctx, db.Pool); err != nil { db.Close() return nil, err } return db, nil } // Reset empties every application table, so each test starts from an empty // schema. The table list comes from the catalog: a table added by a later // migration cannot be forgotten here. func (d *DB) Reset(t testing.TB) { t.Helper() ctx := context.Background() var tables string err := d.Pool.QueryRow(ctx, ` SELECT coalesce(string_agg(format('%I.%I', schemaname, tablename), ', '), '') FROM pg_tables WHERE schemaname = 'public' AND tablename <> 'goose_db_version'`).Scan(&tables) if err != nil { t.Fatalf("list tables: %v", err) } if tables == "" { return } if _, err := d.Pool.Exec(ctx, "TRUNCATE "+tables+" CASCADE"); err != nil { t.Fatalf("truncate: %v", err) } } // Stop stops the container, as when the database goes down. func (d *DB) Stop(ctx context.Context) error { timeout := 5 * time.Second return d.container.Stop(ctx, &timeout) } // Pause freezes the server: connections stay open but nothing answers, as // with a hung database. func (d *DB) Pause(ctx context.Context) error { return withDocker(ctx, func(cli *testcontainers.DockerClient) error { return cli.ContainerPause(ctx, d.container.GetContainerID()) }) } func (d *DB) Unpause(ctx context.Context) error { return withDocker(ctx, func(cli *testcontainers.DockerClient) error { return cli.ContainerUnpause(ctx, d.container.GetContainerID()) }) } func withDocker(ctx context.Context, fn func(cli *testcontainers.DockerClient) error) error { cli, err := testcontainers.NewDockerClientWithOpts(ctx) if err != nil { return err } defer cli.Close() return fn(cli) } func (d *DB) Close() { if d.Pool != nil { d.Pool.Close() } _ = testcontainers.TerminateContainer(d.container) } // KV is a Valkey instance without persistence or password. type KV struct { Client *redis.Client URL string container *tcvalkey.ValkeyContainer } func StartValkey(ctx context.Context) (*KV, error) { useDockerDesktopPipe() c, err := tcvalkey.Run(ctx, ValkeyImage) if err != nil { return nil, fmt.Errorf("start valkey: %w", err) } kv := &KV{container: c} kv.URL, err = c.ConnectionString(ctx) if err != nil { kv.Close() return nil, fmt.Errorf("valkey address: %w", err) } // The production client, so outage tests see its fail-fast settings. kv.Client, err = valkey.NewClient(ctx, kv.URL) if err != nil { kv.Close() return nil, err } return kv, nil } func (k *KV) Reset(t testing.TB) { t.Helper() if err := k.Client.FlushDB(context.Background()).Err(); err != nil { t.Fatalf("flushdb: %v", err) } } // Stop stops the container, as when the session store goes down. func (k *KV) Stop(ctx context.Context) error { timeout := 5 * time.Second return k.container.Stop(ctx, &timeout) } func (k *KV) Close() { if k.Client != nil { _ = k.Client.Close() } _ = testcontainers.TerminateContainer(k.container) }