Dockertest 极速搭建集成测试环境神器
GoCN
共 7630字,需浏览 16分钟
·
2022-05-15 14:12
1 推荐背景
2 怎么使用
第一步:安装
go get -u github.com/ory/dockertest/v3
第二步:使用
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"testing"
"time"
"my-go-api/model"
"github.com/jinzhu/gorm"
"github.com/kataras/iris"
"github.com/kataras/iris/httptest"
"github.com/ory/dockertest"
"github.com/ory/dockertest/docker"
"github.com/stretchr/testify/assert"
)
var db *gorm.DB
var app *iris.Application
func TestMain(m *testing.M) {
// Create a new pool for docker containers
pool, err := dockertest.NewPool("")
if err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
// Pull an image, create a container based on it and set all necessary parameters
opts := dockertest.RunOptions{
Repository: "mdillon/postgis",
Tag: "latest",
Env: []string{"POSTGRES_PASSWORD=123456"},
ExposedPorts: []string{"5432"},
PortBindings: map[docker.Port][]docker.PortBinding{
"5432": {
{HostIP: "0.0.0.0", HostPort: "5477"},
},
},
}
// Run the docker container
resource, err := pool.RunWithOptions(&opts)
if err != nil {
log.Fatalf("Could not start resource: %s", err)
}
// Exponential retry to connect to database while it is booting
if err := pool.Retry(func() error {
databaseConnStr := fmt.Sprintf("host=localhost port=5477 user=postgres dbname=postgres password=123456 sslmode=disable")
db, err = gorm.Open("postgres", databaseConnStr)
if err != nil {
log.Println("Database not ready yet (it is booting up, wait for a few tries)...")
return err
}
// Tests if database is reachable
return db.DB().Ping()
}); err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
log.Println("Initialize test database...")
initTestDatabase()
log.Println("Create new iris app...")
app = newApp(db)
// Run the actual test cases (functions that start with Test...)
code := m.Run()
// Delete the docker container
if err := pool.Purge(resource); err != nil {
log.Fatalf("Could not purge resource: %s", err)
}
os.Exit(code)
}
func TestName(t *testing.T) {
// Request an endpoint of the app
e := httptest.New(t, app, httptest.URL("http://localhost"))
t1 := e.GET("/bill").Expect().Status(iris.StatusOK)
// Compare the actual result with an expected result
assert.Equal(t, "Hello bill", t1.Body().Raw())
}
func TestOrders(t *testing.T) {
e := httptest.New(t, app, httptest.URL("http://localhost"))
t1 := e.GET("/orders").Expect().Status(iris.StatusOK)
expected, _ := json.Marshal(sampleOrders)
assert.Equal(t, string(expected), t1.Body().Raw())
}
func initTestDatabase() {
db.AutoMigrate(&model.Order{})
db.Save(&sampleOrders[0])
db.Save(&sampleOrders[1])
}
var sampleOrders = []model.Order{
{
ID: 1,
Description: "An old glove",
Ts: time.Now().Unix() * 1000,
},
{
ID: 2,
Description: "Something you don't need",
Ts: time.Now().Unix() * 1000,
},
}
第三步:运行测试示例
go test -v
2022/05/08 10:10:43 Database not ready yet (it is booting up, wait for a few tries)...
2022/05/08 10:10:49 Database not ready yet (it is booting up, wait for a few tries)...
2022/05/08 10:10:55 Initialize test database...
2022/05/08 10:10:55 Create new iris app...
=== RUN TestName
--- PASS: TestName (0.00s)
=== RUN TestOrders
--- PASS: TestOrders (0.00s)
PASS
ok my-go-api 25.706s
3 总结
参考资料
https://github.com/ory/dockertest
https://pkg.go.dev/github.com/ory/dockertest#section-readme
https://jonnylangefeld.com/blog/how-to-write-a-go-api-part-3-testing-with-dockertest
https://medium.com/easyread/integration-test-database-in-golang-using-dockertest-59ed3b35240e
评论