feat(db): add pgxpool with health check and integration test

This commit is contained in:
2026-04-28 14:32:37 +08:00
parent d491a7047a
commit 903d872e3f
4 changed files with 252 additions and 28 deletions
+41
View File
@@ -0,0 +1,41 @@
//go:build integration
package db_test
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
tcpg "github.com/testcontainers/testcontainers-go/modules/postgres"
mydb "github.com/yan1h/agent-coding-workflow/internal/infra/db"
)
// TestNewPool_ConnectsAndPings 用 testcontainers 起一个真实的 Postgres,
// 验证 NewPool 能连上、HealthCheck 能 Ping 通。
// 仅在 integration build tag 下编译/运行;本地 `go test ./...` 会跳过。
func TestNewPool_ConnectsAndPings(t *testing.T) {
ctx := context.Background()
// v0.42.0 起 RunContainer 已 Deprecated,统一用 Run(ctx, image, opts...)。
container, err := tcpg.Run(ctx, "postgres:16-alpine",
tcpg.WithDatabase("acw"),
tcpg.WithUsername("acw"),
tcpg.WithPassword("acw"),
)
require.NoError(t, err)
t.Cleanup(func() { _ = container.Terminate(ctx) })
dsn, err := container.ConnectionString(ctx, "sslmode=disable")
require.NoError(t, err)
pool, err := mydb.NewPool(ctx, dsn)
require.NoError(t, err)
t.Cleanup(pool.Close)
hctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
require.NoError(t, mydb.HealthCheck(hctx, pool))
}