backend/pkg/permission/repository/testhelper_test.go

55 lines
1.1 KiB
Go

package repository
import (
"context"
"fmt"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
const (
mongoHost = "127.0.0.1"
mongoPort = "27017"
mongoSchema = "mongodb"
)
// startMongoContainer 啟動 MongoDB 測試容器
func startMongoContainer() (string, string, func(), error) {
ctx := context.Background()
req := testcontainers.ContainerRequest{
Image: "mongo:latest",
ExposedPorts: []string{"27017/tcp"},
WaitingFor: wait.ForListeningPort("27017/tcp"),
}
mongoC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
return "", "", nil, err
}
port, err := mongoC.MappedPort(ctx, mongoPort)
if err != nil {
return "", "", nil, err
}
host, err := mongoC.Host(ctx)
if err != nil {
return "", "", nil, err
}
uri := fmt.Sprintf("mongodb://%s:%s", host, port.Port())
tearDown := func() {
mongoC.Terminate(ctx)
}
fmt.Printf("MongoDB test container started: %s\n", uri)
return host, port.Port(), tearDown, nil
}