setupPostgresContainer 启动 PostgreSQL 容器用于测试
(t *testing.T)
| 24 | |
| 25 | // setupPostgresContainer 启动 PostgreSQL 容器用于测试 |
| 26 | func setupPostgresContainer(t *testing.T) (service *Service, cleanup func()) { |
| 27 | t.Helper() |
| 28 | |
| 29 | // 检查是否在 CI 环境或需要跳过集成测试 |
| 30 | if testing.Short() { |
| 31 | t.Skip("Skipping PostgreSQL integration test in short mode") |
| 32 | } |
| 33 | if os.Getenv("SKIP_INTEGRATION_TESTS") != "" { |
| 34 | t.Skip("Skipping PostgreSQL integration test (SKIP_INTEGRATION_TESTS is set)") |
| 35 | } |
| 36 | |
| 37 | // 捕获 Docker 不可用时的 panic |
| 38 | defer func() { |
| 39 | if r := recover(); r != nil { |
| 40 | t.Skipf("Docker not available, skipping PostgreSQL integration test: %v", r) |
| 41 | } |
| 42 | }() |
| 43 | |
| 44 | ctx := context.Background() |
| 45 | |
| 46 | // 创建 PostgreSQL 容器 |
| 47 | req := testcontainers.ContainerRequest{ |
| 48 | Image: "postgres:16-alpine", |
| 49 | ExposedPorts: []string{"5432/tcp"}, |
| 50 | Env: map[string]string{ |
| 51 | "POSTGRES_USER": "test", |
| 52 | "POSTGRES_PASSWORD": "test", |
| 53 | "POSTGRES_DB": "testdb", |
| 54 | }, |
| 55 | WaitingFor: wait.ForLog("database system is ready to accept connections"). |
| 56 | WithOccurrence(2). |
| 57 | WithStartupTimeout(60 * time.Second), |
| 58 | } |
| 59 | |
| 60 | container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ |
| 61 | ContainerRequest: req, |
| 62 | Started: true, |
| 63 | }) |
| 64 | if err != nil { |
| 65 | t.Skipf("Failed to start PostgreSQL container (Docker may not be available): %v", err) |
| 66 | } |
| 67 | |
| 68 | // 获取容器端口 |
| 69 | host, err := container.Host(ctx) |
| 70 | if err != nil { |
| 71 | t.Skipf("Failed to get container host: %v", err) |
| 72 | } |
| 73 | |
| 74 | port, err := container.MappedPort(ctx, "5432") |
| 75 | if err != nil { |
| 76 | t.Skipf("Failed to get container port: %v", err) |
| 77 | } |
| 78 | |
| 79 | // 构建 DSN |
| 80 | dsn := fmt.Sprintf("host=%s port=%s user=test password=test dbname=testdb sslmode=disable", |
| 81 | host, port.Port()) |
| 82 | |
| 83 | // 创建服务 |
no test coverage detected