Created
July 15, 2024 19:07
-
-
Save BK1031/b6555983b09c961215f44788c368dc33 to your computer and use it in GitHub Desktop.
singlestore-go-bookstore service testmain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package service | |
import ( | |
"bookstore/config" | |
"bookstore/database" | |
"context" | |
"log" | |
"os" | |
"testing" | |
"github.com/testcontainers/testcontainers-go/modules/mysql" | |
) | |
func TestMain(m *testing.M) { | |
ctx := context.Background() | |
// set database config | |
config.Database.Host = "localhost" | |
config.Database.Username = "root" | |
config.Database.Password = "password" | |
config.Database.Database = "bookstore" | |
// start mysql testcontainer | |
mysqlContainer, err := mysql.Run(ctx, | |
"mysql:9.0", | |
mysql.WithDatabase(config.Database.Database), | |
mysql.WithUsername(config.Database.Username), | |
mysql.WithPassword(config.Database.Password), | |
) | |
if err != nil { | |
log.Fatalf("failed to start container: %s", err) | |
} | |
// get mapped port | |
p, err := mysqlContainer.MappedPort(ctx, "3306") | |
if err != nil { | |
log.Fatalf("failed to get mapped port: %s", err) | |
} | |
config.Database.Port = p.Port() | |
// initialize database | |
database.InitializeDB() | |
// Clean up the container | |
defer func() { | |
if err := mysqlContainer.Terminate(ctx); err != nil { | |
log.Fatalf("failed to terminate container: %s", err) | |
} | |
}() | |
// run tests | |
exitVal := m.Run() | |
os.Exit(exitVal) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment