forked from peterldowns/pgtestdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestdb_test.go
439 lines (400 loc) · 12.2 KB
/
testdb_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
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
package pgtestdb_test
import (
"context"
"database/sql"
"fmt"
"testing"
pgx "github.com/jackc/pgx/v5" // "pgx" driver
_ "github.com/jackc/pgx/v5/stdlib" // "pgx" driver
_ "github.com/lib/pq" // "postgres"
"github.com/peterldowns/testy/assert"
"github.com/peterldowns/testy/check"
"github.com/peterldowns/pgtestdb"
"github.com/peterldowns/pgtestdb/internal/sessionlock"
"github.com/peterldowns/pgtestdb/migrators/common"
)
// You should wrap pgtestdb.New inside your own helper, like this,
// which sets up the db configuration (based on your own environment/configs)
// and passes an instance of the Migrator interface.
func New(t *testing.T) *sql.DB {
t.Helper()
dbconf := pgtestdb.Config{
DriverName: "pgx",
User: "postgres",
Password: "password",
Host: "localhost",
Port: "5433",
Options: "sslmode=disable",
}
m := defaultMigrator()
return pgtestdb.New(t, dbconf, m)
}
// Checks to make sure that the testdb is created succesfully and that all
// migrations are applied.
func TestNew(t *testing.T) {
t.Parallel()
ctx := context.Background()
db := New(t)
rows, err := db.QueryContext(ctx, "SELECT name FROM cats ORDER BY name ASC")
assert.Nil(t, err)
defer rows.Close()
var names []string
for rows.Next() {
var name string
assert.Nil(t, rows.Scan(&name))
names = append(names, name)
}
check.Equal(t, []string{"daisy", "sunny"}, names)
}
func TestCustom(t *testing.T) {
t.Parallel()
ctx := context.Background()
dbconf := pgtestdb.Config{
DriverName: "pgx",
User: "postgres",
Password: "password",
Host: "localhost",
Port: "5433",
Options: "sslmode=disable",
}
m := defaultMigrator()
config := pgtestdb.Custom(t, dbconf, m)
check.NotEqual(t, dbconf, *config)
var conn *pgx.Conn
var err error
conn, err = pgx.Connect(ctx, config.URL())
assert.Nil(t, err)
defer func() {
err := conn.Close(ctx)
assert.Nil(t, err)
}()
var message string
err = conn.QueryRow(ctx, "select 'hello world'").Scan(&message)
assert.Nil(t, err)
}
// The Prepare() method of our dummy migrator should have enabled the `pg_trgm`
// and `pgcrypto` extensions. The `plpgsql` extension is always enabled by
// default. This test makes sure that these extensions are installed.
func TestExtensionsInstalled(t *testing.T) {
t.Parallel()
ctx := context.Background()
db := New(t)
rows, err := db.QueryContext(ctx, "SELECT extname FROM pg_extension ORDER BY extname ASC")
assert.Nil(t, err)
defer rows.Close()
var extnames []string
for rows.Next() {
var extname string
assert.Nil(t, rows.Scan(&extname))
extnames = append(extnames, extname)
}
check.Equal(t, []string{"pg_trgm", "pgcrypto", "plpgsql"}, extnames)
}
// These two tests should show that creating many different testdbs in parallel
// is quite fast. Each of the tests creates and destroys 10 databases.
func TestParallel1(t *testing.T) {
t.Parallel()
ctx := context.Background()
for i := 0; i < 10; i++ {
t.Run(fmt.Sprintf("subtest_%d", i), func(t *testing.T) {
t.Parallel()
db := New(t)
var count int
err := db.QueryRowContext(ctx, "SELECT COUNT(*) from cats").Scan(&count)
assert.Nil(t, err)
assert.Equal(t, 2, count)
})
}
}
// These two tests should show that creating many different testdbs in parallel
// is quite fast. Each of the tests creates and destroys 10 databases.
func TestParallel2(t *testing.T) {
t.Parallel()
ctx := context.Background()
for i := 0; i < 10; i++ {
t.Run(fmt.Sprintf("subtest_%d", i), func(t *testing.T) {
t.Parallel()
db := New(t)
var count int
err := db.QueryRowContext(ctx, "SELECT COUNT(*) from cats").Scan(&count)
assert.Nil(t, err)
check.Equal(t, 2, count)
})
}
}
func TestDifferentHashesAlwaysResultInDifferentDatabases(t *testing.T) {
t.Parallel()
ctx := context.Background()
dbconf := pgtestdb.Config{
DriverName: "pgx",
User: "postgres",
Password: "password",
Host: "localhost",
Port: "5433",
Options: "sslmode=disable",
}
// These two migrators have different hashes and they create databases with different schemas.
// The xxx schema contains a table xxx, the yyy schema contains a table yyy.
xxxm := &sqlMigrator{
migrations: []string{
"CREATE TABLE xxx (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY)",
},
}
yyym := &sqlMigrator{
migrations: []string{
"CREATE TABLE yyy (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY)",
},
}
// These two migrators should have different hashes.
yyyh, err := yyym.Hash()
assert.Nil(t, err)
xxxh, err := xxxm.Hash()
assert.Nil(t, err)
assert.NotEqual(t, yyyh, xxxh)
// Create two databases. They _should_ have different schemas.
xxxdb := pgtestdb.New(t, dbconf, xxxm)
yyydb := pgtestdb.New(t, dbconf, yyym)
// But, the bug is that due to use of t.Once(), they will actually have the
// same schema. One of these two statements will always fail! Due to
// ordering in this test, the xxx database gets created first, and the yyy
// database will re-use that template (mistakenly!).
//
// In the case where we're writing a package and have multiple tests in
// parallel, the order is dependent on whichever test runs first, which is
// really annoying to debug.
var countXXX int
err = xxxdb.QueryRowContext(ctx, "select count(*) from xxx").Scan(&countXXX)
if check.Nil(t, err) {
check.Equal(t, 0, countXXX)
}
var countYYY int
err = yyydb.QueryRowContext(ctx, "select count(*) from yyy").Scan(&countYYY)
if check.Nil(t, err) {
check.Equal(t, 0, countXXX)
}
}
// This test confirms that due to testdb's locking strategy, even a migrator
// that uses advisory locks and runs a migration with "CREATE INDEX CONCURRENTLY"
// will succeed. pgtestdb will take an advisory lock on the primary database
// that it is connected to, NOT on the template database. This means that there
// is only ever one migrator running on the template database at a time, and there
// will never be any other migrators waiting or potentially contending an advisory
// lock on that database.
//
// Normally, if you have two connections to a database (c1 and c2), and they are
// contending an advisory lock, attempting to CREATE INDEX CONCCURENTLY will
// cause a deadlock error:
//
// C1: SELECT pg_advisory_locK(1111) -- returns OK
// C2: SELECT pg_advisory_locK(1111) -- hangs indefinitely, waiting on C1
// C1: CREATE INDEX CONCURRENTLY ... -- fails with warning about deadlock, waiting on
// -- the C2 virtual transaction!
//
// Here, that's not an issue because template creation happens at most once, so
// C2, which is a second connection to the template database, will never exist.
func TestMigrationWithConcurrentCreate(t *testing.T) {
t.Parallel()
config := pgtestdb.Config{
DriverName: "pgx",
User: "postgres",
Password: "password",
Host: "localhost",
Port: "5433",
Options: "sslmode=disable",
}
migrator := &sqlMigrator{
migrations: []string{
"CREATE TABLE users (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY)",
"CREATE INDEX CONCURRENTLY example_concurrent_index ON users (id)",
},
}
for i := 0; i < 10; i++ {
t.Run(fmt.Sprintf("subtest_%d", i), func(t *testing.T) {
t.Parallel()
_ = pgtestdb.New(t, config, migrator)
})
}
}
func TestDefaultRolePreventsPostgis(t *testing.T) {
t.Parallel()
config := pgtestdb.Config{
DriverName: "pgx",
User: "postgres",
Password: "password",
Host: "localhost",
Port: "5433",
Options: "sslmode=disable",
}
migrator := &sqlMigrator{
migrations: []string{
// This requires SUPERUSER permissions, but by default they're
// not enabled, so it should fail.
"CREATE EXTENSION postgis;",
},
}
tt := &MockT{}
_ = pgtestdb.New(tt, config, migrator)
tt.DoCleanup()
assert.True(t, tt.Failed())
}
func TestCustomRoleAllowsPostgis(t *testing.T) {
t.Parallel()
config := pgtestdb.Config{
DriverName: "pgx",
User: "postgres",
Password: "password",
Host: "localhost",
Port: "5433",
Options: "sslmode=disable",
TestRole: &pgtestdb.Role{
// Must use a distinct name or it will collide with other tests that
// use the default username, but have non-SUPERUSER capabilities.
// TODO: figure out some way to detect a difference in capabilities
// and fail + warn the user about the collision.
// Or, TODO: figure out a way to include a hash of the capabilities
// on to the basename if there are custom capabilities? But then
// it's a pain and confusing. Blargh.
Username: "pgtestdb-superuser",
Password: pgtestdb.DefaultRolePassword,
Capabilities: "SUPERUSER",
},
}
migrator := &sqlMigrator{
migrations: []string{
// This will work since the migrations will be run with a role that
// has SUPERUSER permissions.
"CREATE EXTENSION postgis;",
},
}
_ = pgtestdb.New(t, config, migrator)
}
// pgtestdb.New should be able to connect with either lib/pq or pgx/stdlib.
func TestWithLibPqAndPgxStdlibDrivers(t *testing.T) {
t.Parallel()
baseConfig := pgtestdb.Config{
User: "postgres",
Password: "password",
Host: "localhost",
Port: "5433",
Options: "sslmode=disable",
}
pgxConfig := baseConfig
pgxConfig.DriverName = "pgx"
pqConfig := baseConfig
pqConfig.DriverName = "postgres"
migrator := defaultMigrator()
for i := 0; i < 10; i++ {
t.Run(fmt.Sprintf("subtest_pgx_%d", i), func(t *testing.T) {
t.Parallel()
_ = pgtestdb.New(t, pgxConfig, migrator)
})
}
for i := 0; i < 10; i++ {
t.Run(fmt.Sprintf("subtest_pq_%d", i), func(t *testing.T) {
t.Parallel()
_ = pgtestdb.New(t, pqConfig, migrator)
})
}
}
// defaultMigrator is an implementation of the Migrator interface, and will
// create a `migrations` table and a `cats` table, with some data.
func defaultMigrator() pgtestdb.Migrator {
return &sqlMigrator{
preparations: []string{`
CREATE EXTENSION pgcrypto;
CREATE EXTENSION pg_trgm;
`},
migrations: []string{`
-- as if this were a real migrations tool that kept track of migrations
CREATE TABLE migrations (
id TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- the "migration"
CREATE TABLE cats (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text
);
INSERT INTO cats (name)
VALUES ('daisy'), ('sunny');
-- recordkeeping
INSERT INTO migrations (id)
VALUES ('cats_0001');
`},
// These queries will fail if the tables don't exist.
verifications: []string{
"SELECT COUNT(*) from cats;",
"SELECT COUNT(*) from migrations;",
},
}
}
// sqlMigrator is a test helper that satisfies the pgtestdb.Migrator interface.
type sqlMigrator struct {
preparations []string
migrations []string
verifications []string
}
func (s *sqlMigrator) Hash() (string, error) {
hash := common.NewRecursiveHash()
for _, preparation := range s.preparations {
hash.Add([]byte(preparation))
}
for _, migration := range s.migrations {
hash.Add([]byte(migration))
}
return hash.String(), nil
}
func (s *sqlMigrator) Migrate(ctx context.Context, db *sql.DB, _ pgtestdb.Config) error {
return sessionlock.With(ctx, db, "test-sql-migrator", func(conn *sql.Conn) error {
for _, migration := range s.migrations {
if _, err := conn.ExecContext(ctx, migration); err != nil {
return err
}
}
return nil
})
}
func (s *sqlMigrator) Prepare(ctx context.Context, db *sql.DB, _ pgtestdb.Config) error {
return sessionlock.With(ctx, db, "test-sql-migrator", func(conn *sql.Conn) error {
for _, migration := range s.preparations {
if _, err := conn.ExecContext(ctx, migration); err != nil {
return err
}
}
return nil
})
}
func (s *sqlMigrator) Verify(ctx context.Context, db *sql.DB, _ pgtestdb.Config) error {
for _, verification := range s.verifications {
if _, err := db.ExecContext(ctx, verification); err != nil {
return err
}
}
return nil
}
// MockT implements the `TB“ interface so that we can check to see if a test
// "would have failed".
type MockT struct {
failed bool
cleanups []func()
}
func (t *MockT) Fatalf(string, ...any) {
t.failed = true
}
func (*MockT) Logf(string, ...any) {
// no-op
}
func (*MockT) Helper() {
// no-op
}
func (t *MockT) Cleanup(f func()) {
t.cleanups = append(t.cleanups, f)
}
func (t *MockT) DoCleanup() {
for _, f := range t.cleanups {
f()
}
}
func (t *MockT) Failed() bool {
return t.failed
}