Skip to content

Instantly share code, notes, and snippets.

@BK1031
Last active July 16, 2024 17:27
Show Gist options
  • Save BK1031/85f65d31316f5ab2331902a90166f100 to your computer and use it in GitHub Desktop.
Save BK1031/85f65d31316f5ab2331902a90166f100 to your computer and use it in GitHub Desktop.
singlestore-go-bookstore api test setup
package api
import (
"bookstore/config"
"bookstore/database"
"context"
"log"
"os"
"testing"
"github.com/gin-gonic/gin"
"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)
}
}()
gin.SetMode(gin.TestMode)
r := gin.Default()
RegisterRoutes(r)
Router = r
// 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