-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestcontainers_postgres.go
178 lines (155 loc) · 6.31 KB
/
testcontainers_postgres.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
// The MIT License (MIT)
//
// Copyright (c) 2017-2019 Gianluca Arbezzano
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package testcontainers_postgres
import (
"context"
"fmt"
"net"
"path/filepath"
"strings"
"github.com/testcontainers/testcontainers-go"
)
const (
defaultUser = "postgres"
defaultPassword = "postgres"
defaultPostgresImage = "docker.io/postgres:11-alpine"
)
// PostgresContainer represents the postgres container type used in the module
type PostgresContainer struct {
testcontainers.Container
dbName string
user string
password string
}
// ConnectionString returns the connection string for the postgres container, using the default 5432 port, and
// obtaining the host and exposed port from the container. It also accepts a variadic list of extra arguments
// which will be appended to the connection string. The format of the extra arguments is the same as the
// connection string format, e.g. "connect_timeout=10" or "application_name=myapp"
func (c *PostgresContainer) ConnectionString(ctx context.Context, args ...string) (string, error) {
containerPort, err := c.MappedPort(ctx, "5432/tcp")
if err != nil {
return "", err
}
host, err := c.Host(ctx)
if err != nil {
return "", err
}
extraArgs := strings.Join(args, "&")
connStr := fmt.Sprintf("postgres://%s:%s@%s/%s?%s", c.user, c.password, net.JoinHostPort(host, containerPort.Port()), c.dbName, extraArgs)
return connStr, nil
}
// WithConfigFile sets the config file to be used for the postgres container
// It will also set the "config_file" parameter to the path of the config file
// as a command line argument to the container
func WithConfigFile(cfg string) testcontainers.CustomizeRequestOption {
return func(req *testcontainers.GenericContainerRequest) {
cfgFile := testcontainers.ContainerFile{
HostFilePath: cfg,
ContainerFilePath: "/etc/postgresql.conf",
FileMode: 0o755,
}
req.Files = append(req.Files, cfgFile)
req.Cmd = append(req.Cmd, "-c", "config_file=/etc/postgresql.conf")
}
}
// WithDatabase sets the initial database to be created when the container starts
// It can be used to define a different name for the default database that is created when the image is first started.
// If it is not specified, then the value of WithUser will be used.
func WithDatabase(dbName string) testcontainers.CustomizeRequestOption {
return func(req *testcontainers.GenericContainerRequest) {
req.Env["POSTGRES_DB"] = dbName
}
}
// WithInitScripts sets the init scripts to be run when the container starts
func WithInitScripts(scripts ...string) testcontainers.CustomizeRequestOption {
return func(req *testcontainers.GenericContainerRequest) {
initScripts := []testcontainers.ContainerFile{}
for _, script := range scripts {
cf := testcontainers.ContainerFile{
HostFilePath: script,
ContainerFilePath: "/docker-entrypoint-initdb.d/" + filepath.Base(script),
FileMode: 0o755,
}
initScripts = append(initScripts, cf)
}
req.Files = append(req.Files, initScripts...)
}
}
// WithPassword sets the initial password of the user to be created when the container starts
// It is required for you to use the PostgreSQL image. It must not be empty or undefined.
// This environment variable sets the superuser password for PostgreSQL.
func WithPassword(password string) testcontainers.CustomizeRequestOption {
return func(req *testcontainers.GenericContainerRequest) {
req.Env["POSTGRES_PASSWORD"] = password
}
}
// WithUsername sets the initial username to be created when the container starts
// It is used in conjunction with WithPassword to set a user and its password.
// It will create the specified user with superuser power and a database with the same name.
// If it is not specified, then the default user of postgres will be used.
func WithUsername(user string) testcontainers.CustomizeRequestOption {
return func(req *testcontainers.GenericContainerRequest) {
if user == "" {
user = defaultUser
}
req.Env["POSTGRES_USER"] = user
}
}
// RunContainer creates an instance of the postgres container type
// apk add gcompat
func RunContainer(ctx context.Context, dirShare map[string]string, opts ...testcontainers.ContainerCustomizer) (*PostgresContainer, error) {
req := testcontainers.ContainerRequest{
Image: defaultPostgresImage,
Env: map[string]string{
"POSTGRES_USER": defaultUser,
"POSTGRES_PASSWORD": defaultPassword,
"POSTGRES_DB": defaultUser, // defaults to the user name
},
ExposedPorts: []string{"5432/tcp"},
Cmd: []string{"postgres", "-c", "fsync=off"},
}
if len(dirShare) > 0 {
req.Files = []testcontainers.ContainerFile{
{
HostFilePath: dirShare["host"],
ContainerFilePath: dirShare["container"],
FileMode: 0o777,
},
}
}
genericContainerReq := testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
}
for _, opt := range opts {
opt.Customize(&genericContainerReq)
}
container, err := testcontainers.GenericContainer(ctx, genericContainerReq)
if err != nil {
return nil, err
}
user := req.Env["POSTGRES_USER"]
password := req.Env["POSTGRES_PASSWORD"]
dbName := req.Env["POSTGRES_DB"]
container.Exec(ctx, []string{"apk", "add", "gcompat"})
return &PostgresContainer{Container: container, dbName: dbName, password: password, user: user}, nil
}