app-cloudep-wallet-service/pkg/repository/mysql_init_test.go

66 lines
1.4 KiB
Go
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package repository
import (
"context"
"fmt"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
const (
MySQLUser = "root"
MySQLPassword = "password"
MySQLDatabase = "testdb"
MySQLPort = "3306"
)
// 啟動 MySQL container
func startMySQLContainer() (host string, port string, dsn string, tearDown func(), err error) {
ctx := context.Background()
req := testcontainers.ContainerRequest{
Image: "mysql:8.0",
Env: map[string]string{
"MYSQL_ROOT_PASSWORD": MySQLPassword,
"MYSQL_DATABASE": MySQLDatabase,
},
ExposedPorts: []string{"3306/tcp"},
WaitingFor: wait.ForListeningPort("3306/tcp"),
}
mysqlC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
return "", "", "", nil, err
}
mappedPort, err := mysqlC.MappedPort(ctx, "3306")
if err != nil {
return "", "", "", nil, err
}
containerHost, err := mysqlC.Host(ctx)
if err != nil {
return "", "", "", nil, err
}
// 組成 DSNData Source Name
dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",
MySQLUser,
MySQLPassword,
containerHost,
mappedPort.Port(),
MySQLDatabase,
)
tearDown = func() {
_ = mysqlC.Terminate(ctx)
}
fmt.Printf("MySQL ready at: %s\n", dsn)
return containerHost, mappedPort.Port(), dsn, tearDown, nil
}