packagemysqlimport("context""github.com/testcontainers/testcontainers-go""github.com/testcontainers/testcontainers-go/wait")// mysqlContainer represents the mysql container type used in the moduletypemysqlContainerstruct{testcontainers.Container}// setupMysql creates an instance of the mysql container typefuncsetupMysql(ctxcontext.Context)(*mysqlContainer,error){req:=testcontainers.ContainerRequest{Image:"mysql:8",ExposedPorts:[]string{"3306/tcp","33060/tcp"},Env:map[string]string{"MYSQL_ROOT_PASSWORD":"password","MYSQL_DATABASE":"database",},WaitingFor:wait.ForAll(wait.ForLog("port: 3306 MySQL Community Server - GPL"),wait.ForListeningPort("3306/tcp"),),}container,err:=testcontainers.GenericContainer(ctx,testcontainers.GenericContainerRequest{ContainerRequest:req,Started:true,})iferr!=nil{returnnil,err}return&mysqlContainer{Container:container},nil}
packagemysqlimport("context""database/sql""fmt""testing"// Import mysql into the scope of this package (required)_"github.com/go-sql-driver/mysql")funcTestMysql(t*testing.T){ctx:=context.Background()container,err:=setupMysql(ctx)iferr!=nil{t.Fatal(err)}// Clean up the container after the test is completet.Cleanup(func(){iferr:=container.Terminate(ctx);err!=nil{t.Fatalf("failed to terminate container: %s",err)}})// perform assertionshost,_:=container.Host(ctx)p,_:=container.MappedPort(ctx,"3306/tcp")port:=p.Int()connectionString:=fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?tls=skip-verify","root","password",host,port,"database")db,err:=sql.Open("mysql",connectionString)iferr!=nil{t.Fatal(err)}deferdb.Close()iferr=db.Ping();err!=nil{t.Errorf("error pinging db: %+v\n",err)}_,err=db.Exec("CREATE TABLE IF NOT EXISTS a_table ( \n"+" `col_1` VARCHAR(128) NOT NULL, \n"+" `col_2` VARCHAR(128) NOT NULL, \n"+" PRIMARY KEY (`col_1`, `col_2`) \n"+")")iferr!=nil{t.Errorf("error creating table: %+v\n",err)}}