2020-01-16 22:51:10 +00:00
|
|
|
package mysqlhelper
|
|
|
|
|
|
|
|
import (
|
2020-09-15 14:01:26 +00:00
|
|
|
"context"
|
2020-01-16 22:51:10 +00:00
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/hashicorp/vault/helper/testhelpers/docker"
|
|
|
|
)
|
|
|
|
|
2020-09-15 14:01:26 +00:00
|
|
|
type Config struct {
|
|
|
|
docker.ServiceHostPort
|
|
|
|
ConnString string
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ docker.ServiceConfig = &Config{}
|
|
|
|
|
|
|
|
func PrepareTestContainer(t *testing.T, legacy bool, pw string) (func(), string) {
|
2020-01-16 22:51:10 +00:00
|
|
|
if os.Getenv("MYSQL_URL") != "" {
|
|
|
|
return func() {}, os.Getenv("MYSQL_URL")
|
|
|
|
}
|
|
|
|
|
|
|
|
imageVersion := "5.7"
|
|
|
|
if legacy {
|
|
|
|
imageVersion = "5.6"
|
|
|
|
}
|
|
|
|
|
2020-09-15 14:01:26 +00:00
|
|
|
runner, err := docker.NewServiceRunner(docker.RunOptions{
|
|
|
|
ImageRepo: "mysql",
|
|
|
|
ImageTag: imageVersion,
|
|
|
|
Ports: []string{"3306/tcp"},
|
|
|
|
Env: []string{"MYSQL_ROOT_PASSWORD=" + pw},
|
|
|
|
})
|
2020-01-16 22:51:10 +00:00
|
|
|
if err != nil {
|
2020-09-15 14:01:26 +00:00
|
|
|
t.Fatalf("could not start docker mysql: %s", err)
|
2020-01-16 22:51:10 +00:00
|
|
|
}
|
|
|
|
|
2020-09-15 14:01:26 +00:00
|
|
|
svc, err := runner.StartService(context.Background(), func(ctx context.Context, host string, port int) (docker.ServiceConfig, error) {
|
|
|
|
hostIP := docker.NewServiceHostPort(host, port)
|
|
|
|
connString := fmt.Sprintf("root:%s@(%s)/mysql?parseTime=true", pw, hostIP.Address())
|
|
|
|
db, err := sql.Open("mysql", connString)
|
2020-01-16 22:51:10 +00:00
|
|
|
if err != nil {
|
2020-09-15 14:01:26 +00:00
|
|
|
return nil, err
|
2020-01-16 22:51:10 +00:00
|
|
|
}
|
|
|
|
defer db.Close()
|
2020-09-15 14:01:26 +00:00
|
|
|
err = db.Ping()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &Config{ServiceHostPort: *hostIP, ConnString: connString}, nil
|
|
|
|
})
|
2020-01-16 22:51:10 +00:00
|
|
|
|
2020-09-15 14:01:26 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("could not start docker mysql: %s", err)
|
|
|
|
}
|
|
|
|
return svc.Cleanup, svc.Config.(*Config).ConnString
|
2020-01-16 22:51:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestCredsExist(t testing.TB, connURL, username, password string) error {
|
|
|
|
// Log in with the new creds
|
|
|
|
connURL = strings.Replace(connURL, "root:secret", fmt.Sprintf("%s:%s", username, password), 1)
|
|
|
|
db, err := sql.Open("mysql", connURL)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer db.Close()
|
|
|
|
return db.Ping()
|
|
|
|
}
|