app-cloudep-comment-server/pkg/repository/start_mongo_container_test.go

53 lines
1.0 KiB
Go
Raw Permalink Normal View History

2025-01-15 05:17:30 +00:00
package repository
import (
"context"
"fmt"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
const (
Host = "127.0.0.1"
Port = "27017"
Schema = "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, Port)
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("Connecting to %s\n", uri)
return host, port.Port(), tearDown, nil
}