Skip to content

Commit

Permalink
add docker test
Browse files Browse the repository at this point in the history
  • Loading branch information
betty200744 committed Dec 29, 2022
1 parent 382d4b2 commit 7c15930
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions awesome-go/dockertest/dockertestpsql_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package dockertestpsql_test

import (
"database/sql"
"fmt"
"github.com/ory/dockertest/v3"
"os"
"testing"
"time"

_ "github.com/lib/pq"
"github.com/ory/dockertest/v3/docker"
log "github.com/sirupsen/logrus"
)

var db *sql.DB

func TestMain(m *testing.M) {
// uses a sensible default on windows (tcp/http) and linux/osx (socket)
pool, err := dockertest.NewPool("unix:///Users/yuanli.zhao/Library/Containers/com.docker.docker/Data/docker.raw.sock")
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: "postgres",
Tag: "11",
Env: []string{
"POSTGRES_PASSWORD=postgres",
"POSTGRES_USER=postgres",
"POSTGRES_DB=test",
"listen_addresses = '*'",
},
}, 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("5432/tcp")
databaseUrl := fmt.Sprintf("postgres://postgres:postgres@%s/test?sslmode=disable", hostAndPort)

log.Println("Connecting to database on url: ", databaseUrl)

resource.Expire(120) // Tell docker to hard kill the container in 120 seconds

// exponential backoff-retry, because the application in the container might not be ready to accept connections yet
pool.MaxWait = 120 * time.Second
if err = pool.Retry(func() error {
db, err = sql.Open("postgres", databaseUrl)
if err != nil {
return err
}
return db.Ping()
}); err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
//Run tests
code := m.Run()

// You can't defer this because os.Exit doesn't care for defer
if err := pool.Purge(resource); err != nil {
log.Fatalf("Could not purge resource: %s", err)
}

os.Exit(code)
}

func TestRealbob(t *testing.T) {
// all tests
res, err := db.Exec("SELECT * FROM public.people")
if err != nil {
log.Error(err)
}
fmt.Println(res)
}

0 comments on commit 7c15930

Please sign in to comment.