forked from dhui/dktest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
87 lines (79 loc) · 2.07 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package dktest_test
import (
"context"
"database/sql"
"fmt"
"net/http"
"net/url"
"testing"
)
import (
"github.com/dhui/dktest"
_ "github.com/lib/pq"
)
func Example_nginx() {
dockerImageName := "nginx:alpine"
readyFunc := func(ctx context.Context, c dktest.ContainerInfo) bool {
ip, port, err := c.FirstPort()
if err != nil {
return false
}
u := url.URL{Scheme: "http", Host: ip + ":" + port}
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
fmt.Println(err)
return false
}
req = req.WithContext(ctx)
if resp, err := http.DefaultClient.Do(req); err != nil {
return false
} else if resp.StatusCode != 200 {
return false
}
return true
}
// dktest.Run() should be used within a test
dktest.Run(&testing.T{}, dockerImageName, dktest.Options{PortRequired: true, ReadyFunc: readyFunc},
func(t *testing.T, c dktest.ContainerInfo) {
// test code here
})
// Output:
}
func Example_postgres() {
dockerImageName := "postgres:alpine"
readyFunc := func(ctx context.Context, c dktest.ContainerInfo) bool {
ip, port, err := c.FirstPort()
if err != nil {
return false
}
connStr := fmt.Sprintf("host=%s port=%s user=postgres password=password dbname=postgres sslmode=disable", ip, port)
db, err := sql.Open("postgres", connStr)
if err != nil {
return false
}
defer db.Close() // nolint:errcheck
return db.PingContext(ctx) == nil
}
// dktest.Run() should be used within a test
dktest.Run(&testing.T{}, dockerImageName, dktest.Options{
PortRequired: true,
ReadyFunc: readyFunc,
Env: map[string]string{"POSTGRES_PASSWORD": "password"}},
func(t *testing.T, c dktest.ContainerInfo) {
ip, port, err := c.FirstPort()
if err != nil {
t.Fatal(err)
}
connStr := fmt.Sprintf("host=%s port=%s user=postgres password=password dbname=postgres sslmode=disable", ip, port)
db, err := sql.Open("postgres", connStr)
if err != nil {
t.Fatal(err)
}
defer db.Close() // nolint:errcheck
if err := db.Ping(); err != nil {
t.Fatal(err)
}
// Test using db
})
// Output:
}