-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
test_helper.go
496 lines (416 loc) · 13.8 KB
/
test_helper.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package dockertest
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
"sync"
"testing"
"time"
"github.com/gobuffalo/pop/v6"
"github.com/ory/dockertest/v3"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
dc "github.com/ory/dockertest/v3/docker"
"github.com/ory/x/logrusx"
"github.com/ory/x/resilience"
"github.com/ory/x/stringsx"
)
// atexit := atexit.NewOnExit()
// atexit.Add(func() {
// dockertest.KillAll()
// })
// atexit.Exit(testMain(m))
// func WrapCleanup
type dockerPool interface {
Purge(r *dockertest.Resource) error
Run(repository, tag string, env []string) (*dockertest.Resource, error)
RunWithOptions(opts *dockertest.RunOptions, hcOpts ...func(*dc.HostConfig)) (*dockertest.Resource, error)
}
var resources = []*dockertest.Resource{}
var pool dockerPool
func getPool() (dockerPool, error) {
if pool != nil {
return pool, nil
}
var err error
pool, err = dockertest.NewPool("")
return pool, err
}
// KillAllTestDatabases deletes all test databases.
func KillAllTestDatabases() {
pool, err := getPool()
if err != nil {
panic(err)
}
for _, r := range resources {
if err := pool.Purge(r); err != nil {
log.Printf("Failed to purge resource: %s", err)
}
}
resources = []*dockertest.Resource{}
}
// Register sets up OnExit.
func Register() *OnExit {
onexit := NewOnExit()
onexit.Add(func() {
KillAllTestDatabases()
})
return onexit
}
// Parallel runs tasks in parallel.
func Parallel(fs []func()) {
wg := sync.WaitGroup{}
wg.Add(len(fs))
for _, f := range fs {
go func(ff func()) {
defer wg.Done()
ff()
}(f)
}
wg.Wait()
}
func connect(dialect, driver, dsn string) (db *sqlx.DB, err error) {
if scheme := strings.Split(dsn, "://")[0]; scheme == "mysql" {
dsn = strings.Replace(dsn, "mysql://", "", -1)
} else if scheme == "cockroach" {
dsn = strings.Replace(dsn, "cockroach://", "postgres://", 1)
}
err = resilience.Retry(
logrusx.New("", ""),
time.Second*5,
time.Minute*5,
func() (err error) {
db, err = sqlx.Open(dialect, dsn)
if err != nil {
log.Printf("Connecting to database %s failed: %s", driver, err)
return err
}
if err := db.Ping(); err != nil {
log.Printf("Pinging database %s failed: %s", driver, err)
return err
}
return nil
},
)
if err != nil {
return nil, errors.Errorf("Unable to connect to %s (%s): %s", driver, dsn, err)
}
log.Printf("Connected to database %s", driver)
return db, nil
}
func ConnectPop(t require.TestingT, url string) (c *pop.Connection) {
require.NoError(t, resilience.Retry(logrusx.New("", ""), time.Second*5, time.Minute*5, func() error {
var err error
c, err = pop.NewConnection(&pop.ConnectionDetails{
URL: url,
})
if err != nil {
log.Printf("could not create pop connection")
return err
}
if err := c.Open(); err != nil {
// an Open error probably means we have a problem with the connections config
log.Printf("could not open pop connection: %+v", err)
return err
}
return c.RawQuery("select version()").Exec()
}))
return
}
// ## PostgreSQL ##
func startPostgreSQL(version string) (*dockertest.Resource, error) {
pool, err := getPool()
if err != nil {
return nil, errors.Wrap(err, "Could not connect to docker")
}
resource, err := pool.Run("postgres", stringsx.Coalesce(version, "11.8"), []string{"POSTGRES_PASSWORD=secret", "POSTGRES_DB=postgres"})
if err == nil {
resources = append(resources, resource)
}
return resource, err
}
// RunTestPostgreSQL runs a PostgreSQL database and returns the URL to it.
// If a docker container is started for the database, the container be removed
// at the end of the test.
func RunTestPostgreSQL(t testing.TB) string {
if dsn := os.Getenv("TEST_DATABASE_POSTGRESQL"); dsn != "" {
t.Logf("Skipping Docker setup because environment variable TEST_DATABASE_POSTGRESQL is set to: %s", dsn)
return dsn
}
u, cleanup, err := runPosgreSQLCleanup("")
require.NoError(t, err)
t.Cleanup(cleanup)
return u
}
// RunPostgreSQL runs a PostgreSQL database and returns the URL to it.
func RunPostgreSQL() (string, error) {
dsn, _, err := runPosgreSQLCleanup("")
return dsn, err
}
func runPosgreSQLCleanup(version string) (string, func(), error) {
resource, err := startPostgreSQL(version)
if err != nil {
return "", func() {}, err
}
return fmt.Sprintf("postgres://postgres:secret@127.0.0.1:%s/postgres?sslmode=disable", resource.GetPort("5432/tcp")),
func() { _ = pool.Purge(resource) }, nil
}
// ConnectToTestPostgreSQL connects to a PostgreSQL database.
func ConnectToTestPostgreSQL() (*sqlx.DB, error) {
if dsn := os.Getenv("TEST_DATABASE_POSTGRESQL"); dsn != "" {
return connect("pgx", "postgres", dsn)
}
resource, err := startPostgreSQL("")
if err != nil {
return nil, errors.Wrap(err, "Could not start resource")
}
db := bootstrap("postgres://postgres:secret@localhost:%s/postgres?sslmode=disable", "5432/tcp", "pgx", pool, resource)
return db, nil
}
// RunTestPostgreSQLWithVersion connects to a PostgreSQL database .
func RunTestPostgreSQLWithVersion(t testing.TB, version string) string {
if dsn := os.Getenv("TEST_DATABASE_POSTGRESQL"); dsn != "" {
return dsn
}
resource, err := startPostgreSQL("")
require.NoError(t, err)
return fmt.Sprintf("postgres://postgres:secret@127.0.0.1:%s/postgres?sslmode=disable", resource.GetPort("5432/tcp"))
}
// ConnectToTestPostgreSQLPop connects to a test PostgreSQL database.
// If a docker container is started for the database, the container be removed
// at the end of the test.
func ConnectToTestPostgreSQLPop(t testing.TB) *pop.Connection {
url := RunTestPostgreSQL(t)
return ConnectPop(t, url)
}
// ## MySQL ##
func startMySQL(version string) (*dockertest.Resource, error) {
pool, err := getPool()
if err != nil {
return nil, errors.Wrap(err, "Could not connect to docker")
}
resource, err := pool.RunWithOptions(&dockertest.RunOptions{
Platform: "linux/amd64",
Repository: "mysql",
Tag: stringsx.Coalesce(version, "8.0.26"),
Env: []string{
"MYSQL_ROOT_PASSWORD=secret",
"MYSQL_ROOT_HOST=%",
},
})
if err != nil {
return nil, err
}
resources = append(resources, resource)
return resource, nil
}
// RunMySQL runs a RunMySQL database and returns the URL to it.
func RunMySQL() (string, error) {
dsn, _, err := runMySQLCleanup("")
return dsn, err
}
func runMySQLCleanup(version string) (string, func(), error) {
resource, err := startMySQL(version)
if err != nil {
return "", func() {}, err
}
return fmt.Sprintf("mysql://root:secret@(localhost:%s)/mysql?parseTime=true&multiStatements=true", resource.GetPort("3306/tcp")),
func() { _ = pool.Purge(resource) }, nil
}
// RunTestMySQL runs a MySQL database and returns the URL to it.
// If a docker container is started for the database, the container be removed
// at the end of the test.
func RunTestMySQL(t testing.TB) string {
if dsn := os.Getenv("TEST_DATABASE_MYSQL"); dsn != "" {
t.Logf("Skipping Docker setup because environment variable TEST_DATABASE_MYSQL is set to: %s", dsn)
return dsn
}
u, cleanup, err := runMySQLCleanup("")
require.NoError(t, err)
t.Cleanup(cleanup)
return u
}
// RunTestMySQLWithVersion runs a MySQL database in the specified version and returns the URL to it.
// If a docker container is started for the database, the container be removed
// at the end of the test.
func RunTestMySQLWithVersion(t testing.TB, version string) string {
if dsn := os.Getenv("TEST_DATABASE_MYSQL"); dsn != "" {
t.Logf("Skipping Docker setup because environment variable TEST_DATABASE_MYSQL is set to: %s", dsn)
return dsn
}
u, cleanup, err := runMySQLCleanup(version)
require.NoError(t, err)
t.Cleanup(cleanup)
return u
}
// ConnectToTestMySQL connects to a MySQL database.
func ConnectToTestMySQL() (*sqlx.DB, error) {
if dsn := os.Getenv("TEST_DATABASE_MYSQL"); dsn != "" {
log.Println("Found mysql test database config, skipping dockertest...")
return connect("mysql", "mysql", dsn)
}
resource, err := startMySQL("")
if err != nil {
return nil, errors.Wrap(err, "Could not start resource")
}
db := bootstrap("root:secret@(localhost:%s)/mysql?parseTime=true", "3306/tcp", "mysql", pool, resource)
return db, nil
}
func ConnectToTestMySQLPop(t testing.TB) *pop.Connection {
url := RunTestMySQL(t)
return ConnectPop(t, url)
}
// ## CockroachDB
func startCockroachDB(version string) (*dockertest.Resource, error) {
pool, err := getPool()
if err != nil {
return nil, errors.Wrap(err, "Could not connect to docker")
}
resource, err := pool.RunWithOptions(&dockertest.RunOptions{
Repository: "cockroachdb/cockroach",
Tag: stringsx.Coalesce(version, "v20.2.5"),
Cmd: []string{"start-single-node", "--insecure"},
})
if err == nil {
resources = append(resources, resource)
}
return resource, err
}
// RunCockroachDB runs a CockroachDB database and returns the URL to it.
func RunCockroachDB() (string, error) {
return RunCockroachDBWithVersion("")
}
// RunCockroachDB runs a CockroachDB database and returns the URL to it.
func RunCockroachDBWithVersion(version string) (string, error) {
resource, err := startCockroachDB(version)
if err != nil {
return "", err
}
return fmt.Sprintf("cockroach://root@localhost:%s/defaultdb?sslmode=disable", resource.GetPort("26257/tcp")), nil
}
func runCockroachDBWithVersionCleanup(version string) (string, func(), error) {
resource, err := startCockroachDB(version)
if err != nil {
return "", func() {}, err
}
return fmt.Sprintf("cockroach://root@localhost:%s/defaultdb?sslmode=disable", resource.GetPort("26257/tcp")),
func() { _ = pool.Purge(resource) },
nil
}
// RunTestCockroachDB runs a CockroachDB database and returns the URL to it.
// If a docker container is started for the database, the container be removed
// at the end of the test.
func RunTestCockroachDB(t testing.TB) string {
return RunTestCockroachDBWithVersion(t, "")
}
// RunTestCockroachDB runs a CockroachDB database and returns the URL to it.
// If a docker container is started for the database, the container be removed
// at the end of the test.
func RunTestCockroachDBWithVersion(t testing.TB, version string) string {
if dsn := os.Getenv("TEST_DATABASE_COCKROACHDB"); dsn != "" {
t.Logf("Skipping Docker setup because environment variable TEST_DATABASE_COCKROACHDB is set to: %s", dsn)
return dsn
}
u, cleanup, err := runCockroachDBWithVersionCleanup(version)
require.NoError(t, err)
t.Cleanup(cleanup)
return u
}
// ConnectToTestCockroachDB connects to a CockroachDB database.
func ConnectToTestCockroachDB() (*sqlx.DB, error) {
if dsn := os.Getenv("TEST_DATABASE_COCKROACHDB"); dsn != "" {
log.Println("Found cockroachdb test database config, skipping dockertest...")
return connect("pgx", "cockroach", dsn)
}
resource, err := startCockroachDB("")
if err != nil {
return nil, errors.Wrap(err, "Could not start resource")
}
db := bootstrap("postgres://root@localhost:%s/defaultdb?sslmode=disable", "26257/tcp", "pgx", pool, resource)
return db, nil
}
// ConnectToTestCockroachDBPop connects to a test CockroachDB database.
// If a docker container is started for the database, the container be removed
// at the end of the test.
func ConnectToTestCockroachDBPop(t testing.TB) *pop.Connection {
url := RunTestCockroachDB(t)
return ConnectPop(t, url)
}
func bootstrap(u, port, d string, pool dockerPool, resource *dockertest.Resource) (db *sqlx.DB) {
if err := resilience.Retry(logrusx.New("", ""), time.Second*5, time.Minute*5, func() error {
var err error
db, err = sqlx.Open(d, fmt.Sprintf(u, resource.GetPort(port)))
if err != nil {
return err
}
return db.Ping()
}); err != nil {
if pErr := pool.Purge(resource); pErr != nil {
log.Fatalf("Could not connect to docker and unable to remove image: %s - %s", err, pErr)
}
log.Fatalf("Could not connect to docker: %s", err)
}
return
}
var comments = regexp.MustCompile("(--[^\n]*\n)|(?s:/\\*.+\\*/)")
func StripDump(d string) string {
d = comments.ReplaceAllLiteralString(d, "")
d = strings.TrimPrefix(d, "Command \"dump\" is deprecated, cockroach dump will be removed in a subsequent release.\r\nFor details, see: https://github.com/cockroachdb/cockroach/issues/54040\r\n")
d = strings.ReplaceAll(d, "\r\n", "")
d = strings.ReplaceAll(d, "\t", " ")
d = strings.ReplaceAll(d, "\n", " ")
return d
}
func DumpSchema(ctx context.Context, t *testing.T, db string) string {
var containerPort string
var cmd []string
switch c := stringsx.SwitchExact(db); {
case c.AddCase("postgres"):
containerPort = "5432"
cmd = []string{"pg_dump", "-U", "postgres", "-s", "-T", "hydra_*_migration", "-T", "schema_migration"}
case c.AddCase("mysql"):
containerPort = "3306"
cmd = []string{"/usr/bin/mysqldump", "-u", "root", "--password=secret", "mysql"}
case c.AddCase("cockroach"):
containerPort = "26257"
cmd = []string{"./cockroach", "dump", "defaultdb", "--insecure", "--dump-mode=schema"}
default:
t.Log(c.ToUnknownCaseErr())
t.FailNow()
return ""
}
cli, err := client.NewClientWithOpts(client.FromEnv)
require.NoError(t, err)
containers, err := cli.ContainerList(ctx, types.ContainerListOptions{
Quiet: true,
Filters: filters.NewArgs(filters.Arg("expose", containerPort)),
})
require.NoError(t, err)
if len(containers) != 1 {
t.Logf("Ambiguous amount of %s containers: %d", db, len(containers))
t.FailNow()
}
process, err := cli.ContainerExecCreate(ctx, containers[0].ID, types.ExecConfig{
Tty: true,
AttachStdout: true,
Cmd: cmd,
})
require.NoError(t, err)
resp, err := cli.ContainerExecAttach(ctx, process.ID, types.ExecStartCheck{
Tty: true,
})
require.NoError(t, err)
dump, err := ioutil.ReadAll(resp.Reader)
require.NoError(t, err, "%s", dump)
return StripDump(string(dump))
}