From 914c351bcc4595b7b15dbdde6043aed556171ba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Wed, 15 Dec 2021 00:14:29 -0300 Subject: [PATCH] Add docker-test support for SQLServer This commit adds the last step for running all integration tests with zero database setup =] --- main_test.go | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/main_test.go b/main_test.go index 346ce8c..85cef01 100644 --- a/main_test.go +++ b/main_test.go @@ -30,6 +30,8 @@ func TestMain(m *testing.M) { connectionString["postgres"] = postgresURL mysqlURL, closeMySQL := startMySQLDB("ksql") connectionString["mysql"] = mysqlURL + sqlServerURL, closeSQLServer := startSQLServerDB("ksql") + connectionString["sqlserver"] = sqlServerURL exitCode := m.Run() @@ -37,6 +39,7 @@ func TestMain(m *testing.M) { // of the os.Exit call below: closePostgres() closeMySQL() + closeSQLServer() os.Exit(exitCode) } @@ -155,6 +158,62 @@ func startMySQLDB(dbName string) (databaseURL string, closer func()) { } } +func startSQLServerDB(dbName string) (databaseURL string, closer func()) { + // uses a sensible default on windows (tcp/http) and linux/osx (socket) + pool, err := dockertest.NewPool("") + if err != nil { + log.Fatalf("Could not connect to docker: %s", err) + } + + // pulls an image, creates a container based on it and runs it + resource, err := pool.RunWithOptions( + &dockertest.RunOptions{ + Repository: "mcr.microsoft.com/mssql/server", + Tag: "2017-latest", + Env: []string{ + "SA_PASSWORD=Sqls3rv3r", + "ACCEPT_EULA=Y", + }, + }, + func(config *docker.HostConfig) { + // set AutoRemove to true so that stopped container goes away by itself + config.AutoRemove = true + config.RestartPolicy = docker.RestartPolicy{Name: "no"} + }, + ) + if err != nil { + log.Fatalf("Could not start resource: %s", err) + } + + hostAndPort := resource.GetHostPort("1433/tcp") + databaseUrl := fmt.Sprintf("sqlserver://sa:Sqls3rv3r@%s?databaseName=%s", hostAndPort, dbName) + + fmt.Println("Connecting to sqlserver on url: ", databaseUrl) + + resource.Expire(40) // Tell docker to hard kill the container in 20 seconds + + var sqlDB *sql.DB + // exponential backoff-retry, because the application in the container might not be ready to accept connections yet + pool.MaxWait = 10 * time.Second + pool.Retry(func() error { + sqlDB, err = sql.Open("sqlserver", databaseUrl) + if err != nil { + return err + } + return sqlDB.Ping() + }) + if err != nil { + log.Fatalf("Could not connect to docker: %s", err) + } + sqlDB.Close() + + return databaseUrl, func() { + if err := pool.Purge(resource); err != nil { + log.Fatalf("Could not purge resource: %s", err) + } + } +} + func toJSON(i interface{}) []byte { rawJSON, err := json.Marshal(i) if err != nil {