Repository navigation
Expand file tree
/
Copy pathexample_test.go
More file actions
748 lines (613 loc) · 18.6 KB
/
Copy pathexample_test.go
File metadata and controls
748 lines (613 loc) · 18.6 KB
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
package postgres_test
import (
"context"
"database/sql"
"fmt"
"strings"
"testing"
"github.com/bashhack/testdb"
"github.com/bashhack/testdb/postgres"
"github.com/jackc/pgx/v5/pgxpool"
gormpostgres "gorm.io/driver/postgres"
"gorm.io/gorm"
)
// Example_setup demonstrates basic usage of postgres.Setup for creating
// isolated test databases with automatic cleanup.
func Example_setup() {
t := newExampleT()
defer t.done()
// Create isolated test database with the schema applied
// Cleanup is automatic via t.Cleanup()
pool := postgres.Setup(t,
testdb.WithMigrator(postgres.SQLFiles("../testdata/postgres/schema")))
_, err := pool.Exec(context.Background(),
"INSERT INTO test_table (name) VALUES ($1)", "test")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("Database setup complete")
fmt.Println("Data inserted successfully")
// Output:
// Database setup complete
// Data inserted successfully
}
// Example_parallel shows running tests in parallel with isolated databases.
func Example_parallel() {
t := &testing.T{}
t.Run("create user", func(t *testing.T) {
t.Parallel()
pool := postgres.Setup(t,
testdb.WithMigrator(postgres.SQLFiles("../testdata/postgres/schema")))
_, err := pool.Exec(context.Background(),
"INSERT INTO users (email) VALUES ($1)", "user1@example.com")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("User 1 created")
})
t.Run("delete user", func(t *testing.T) {
t.Parallel()
pool := postgres.Setup(t,
testdb.WithMigrator(postgres.SQLFiles("../testdata/postgres/schema")))
_, err := pool.Exec(context.Background(),
"INSERT INTO users (email) VALUES ($1)", "user2@example.com")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("User 2 created")
})
// Note: This example demonstrates the API but cannot be executed as a runnable
// example because it uses t.Run() which requires a real testing.T instance.
}
// Example_configuration demonstrates configuration options.
func Example_configuration() {
t := newExampleT()
defer t.done()
pool := postgres.Setup(t,
testdb.WithMigrator(postgres.SQLFiles("../testdata/postgres/schema")),
testdb.WithDBPrefix("myapp_test"),
)
if err := pool.Ping(context.Background()); err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("Database configured successfully")
fmt.Println("Custom prefix and migrations applied")
// Output:
// Database configured successfully
// Custom prefix and migrations applied
}
// Example_helperFunction demonstrates the helper function pattern for
// consistent test setup.
func Example_helperFunction() {
setupDB := func(t testing.TB) *pgxpool.Pool {
t.Helper()
return postgres.Setup(t,
testdb.WithMigrator(postgres.SQLFiles("../testdata/postgres/schema")),
testdb.WithDBPrefix("myapp_test"),
)
}
t := newExampleT()
defer t.done()
pool := setupDB(t)
if err := pool.Ping(context.Background()); err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("Helper function setup complete")
// Output:
// Helper function setup complete
}
// GormExampleInitializer is a GORM initializer for examples
type GormExampleInitializer struct{}
func (g *GormExampleInitializer) InitializeTestDatabase(ctx context.Context, dsn string) (any, error) {
return gorm.Open(gormpostgres.Open(dsn), &gorm.Config{})
}
// Example_gorm demonstrates using postgres.New() with GORM for custom database initialization.
func Example_gorm() {
t := newExampleT()
defer t.done()
// Create test database with GORM initializer
// postgres.New() is used instead of postgres.Setup() when you need custom initialization
db := postgres.New(t, &GormExampleInitializer{})
// Get GORM DB instance
gormDB := db.Entity().(*gorm.DB)
// Define a model
type Article struct {
ID uint `gorm:"primaryKey"`
Title string `gorm:"not null"`
Content string
}
// Auto-migrate schema
if err := gormDB.AutoMigrate(&Article{}); err != nil {
fmt.Printf("Error: %v\n", err)
return
}
// Create a record
article := Article{Title: "Getting Started", Content: "Introduction to testdb"}
if err := gormDB.Create(&article).Error; err != nil {
fmt.Printf("Error: %v\n", err)
return
}
// Query the record
var found Article
if err := gormDB.First(&found, "title = ?", "Getting Started").Error; err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("GORM setup complete")
fmt.Printf("Article created: %s\n", found.Title)
// Output:
// GORM setup complete
// Article created: Getting Started
}
// Example_setupVsNew demonstrates when to use Setup() vs New().
func Example_setupVsNew() {
t := newExampleT()
defer t.done()
// Use Setup() when working with pgx/pgxpool directly
// Returns *pgxpool.Pool - simplest API
pool := postgres.Setup(t)
var result int
err := pool.QueryRow(context.Background(), "SELECT 1").Scan(&result)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Setup() returns pool, result: %d\n", result)
// Use New() when you need custom initialization (GORM, sqlx, etc.)
// Returns *testdb.TestDatabase with more flexibility
db := postgres.New(t, &postgres.PoolInitializer{})
pool2 := db.Entity().(*pgxpool.Pool)
var result2 int
err = pool2.QueryRow(context.Background(), "SELECT 2").Scan(&result2)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("New() returns TestDatabase, result: %d\n", result2)
fmt.Printf("Database name starts with: %s\n", db.Name()[:5]) // Show prefix only
// Output:
// Setup() returns pool, result: 1
// New() returns TestDatabase, result: 2
// Database name starts with: test_
}
// Example_sqlDB demonstrates using postgres.New() with SqlDbInitializer for database/sql compatibility.
//
// Use SqlDbInitializer when:
// - Your application uses database/sql interfaces
// - You need compatibility with existing sql.DB-based code
// - You're working with libraries that expect *sql.DB
//
// For PostgreSQL-specific features, use PoolInitializer or Setup() instead.
func Example_sqlDB() {
t := newExampleT()
defer t.done()
// Create test database with sql.DB
db := postgres.New(t, &postgres.SqlDbInitializer{})
// Get the *sql.DB instance
sqlDB := db.Entity().(*sql.DB)
// Create table
_, err := sqlDB.Exec(`
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
)
`)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
// Insert data
_, err = sqlDB.Exec(
`INSERT INTO users (name, email) VALUES ($1, $2)`,
"Alice", "alice@example.com",
)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
// Query data
var name string
err = sqlDB.QueryRow(
`SELECT name FROM users WHERE email = $1`,
"alice@example.com",
).Scan(&name)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("sql.DB setup complete")
fmt.Printf("Found user: %s\n", name)
// Cleanup happens automatically via t.Cleanup()
// Output:
// sql.DB setup complete
// Found user: Alice
}
// Example_basicUsage demonstrates creating an isolated test database.
func Example_basicUsage() {
t := newExampleT()
defer t.done()
// Create isolated test database
pool := postgres.Setup(t)
// Use the database - it's completely isolated
// Cleanup is automatic via t.Cleanup()
var result int
err := pool.QueryRow(context.Background(), "SELECT 1").Scan(&result)
if err != nil {
fmt.Printf("Query failed: %v\n", err)
return
}
fmt.Printf("Query result: %d\n", result)
// Output:
// Query result: 1
}
// Example_customPrefix demonstrates using a custom database name prefix.
func Example_customPrefix() {
t := newExampleT()
defer t.done()
pool := postgres.Setup(t,
testdb.WithDBPrefix("myapp"),
)
// Database name will be like "myapp_1699564231_a1b2c3d4"
var dbname string
err := pool.QueryRow(context.Background(), "SELECT current_database()").Scan(&dbname)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
// Verify prefix is used
if len(dbname) < 6 || dbname[:6] != "myapp_" {
fmt.Printf("Expected database name to start with 'myapp_', got: %s\n", dbname)
return
}
fmt.Println("Custom prefix applied successfully")
fmt.Printf("Database name starts with: %s\n", strings.Split(dbname, "_")[0])
// Output:
// Custom prefix applied successfully
// Database name starts with: myapp
}
// Example_multipleOptions demonstrates combining multiple configuration options.
func Example_multipleOptions() {
t := newExampleT()
defer t.done()
pool := postgres.Setup(t,
testdb.WithDBPrefix("test"),
testdb.WithMigrator(postgres.SQLFiles("../testdata/postgres/schema")),
)
// Verify database exists and migrations ran
var dbname string
err := pool.QueryRow(context.Background(), "SELECT current_database()").Scan(&dbname)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
// Check migration ran
var exists bool
err = pool.QueryRow(context.Background(), `
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'test_table'
)
`).Scan(&exists)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
if !exists {
fmt.Println("Expected test_table to exist")
return
}
fmt.Println("Multiple options configured successfully")
fmt.Println("Database created with custom prefix")
fmt.Println("Migrations ran and tables exist")
// Output:
// Multiple options configured successfully
// Database created with custom prefix
// Migrations ran and tables exist
}
// Example_sqlFiles applies a directory of plain .sql files to each test
// database, no migration tool required. For goose, tern or golang-migrate,
// use the adapter modules under github.com/bashhack/testdb/migrate.
func Example_sqlFiles() {
t := newExampleT()
defer t.done()
pool := postgres.Setup(t,
testdb.WithMigrator(postgres.SQLFiles("../testdata/postgres/schema")),
)
// Verify the schema is in place
var exists bool
err := pool.QueryRow(context.Background(), `
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'test_table'
)
`).Scan(&exists)
if err != nil {
fmt.Printf("Failed to check table: %v\n", err)
return
}
if !exists {
fmt.Println("Expected test_table to exist after migrations")
return
}
// Insert data to verify table works
_, err = pool.Exec(context.Background(),
"INSERT INTO test_table (name) VALUES ($1)", "test")
if err != nil {
fmt.Printf("Failed to insert: %v\n", err)
return
}
fmt.Println("Schema applied from SQL files")
fmt.Println("Table exists and data inserted")
// Output:
// Schema applied from SQL files
// Table exists and data inserted
}
// Example_customMigrator shows that any function taking a context and a DSN
// can prepare the database: here, a few statements run directly.
func Example_customMigrator() {
t := newExampleT()
defer t.done()
createSchema := func(ctx context.Context, dsn string) error {
conn, err := pgxpool.New(ctx, dsn)
if err != nil {
return err
}
defer conn.Close()
_, err = conn.Exec(ctx, "CREATE TABLE notes (id SERIAL PRIMARY KEY, body TEXT NOT NULL)")
return err
}
pool := postgres.Setup(t,
testdb.WithMigrator(testdb.MigratorFunc(createSchema)),
)
if _, err := pool.Exec(context.Background(),
"INSERT INTO notes (body) VALUES ($1)", "hello"); err != nil {
fmt.Printf("Failed to insert: %v\n", err)
return
}
fmt.Println("Custom migrator prepared the database")
// Output:
// Custom migrator prepared the database
}
// Example_parallelExecution demonstrates running tests in parallel with isolated databases.
func Example_parallelExecution() {
t := &testing.T{}
t.Run("test1", func(t *testing.T) {
t.Parallel()
pool := postgres.Setup(t)
// Each test gets its own database
var dbname string
err := pool.QueryRow(context.Background(), "SELECT current_database()").Scan(&dbname)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Test1 using database: %s\n", dbname)
})
t.Run("test2", func(t *testing.T) {
t.Parallel()
pool := postgres.Setup(t)
// This database is different from test1
var dbname string
err := pool.QueryRow(context.Background(), "SELECT current_database()").Scan(&dbname)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Test2 using database: %s\n", dbname)
})
t.Run("test3", func(t *testing.T) {
t.Parallel()
pool := postgres.Setup(t)
// And this is yet another isolated database
var dbname string
err := pool.QueryRow(context.Background(), "SELECT current_database()").Scan(&dbname)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Test3 using database: %s\n", dbname)
})
// Note: This example demonstrates the API but cannot be executed as a runnable
// example because it uses t.Run() which requires a real testing.T instance.
}
// Example_templateWithMigrations demonstrates using templates to avoid running
// migrations for every test.
func Example_templateWithMigrations() {
ctx := context.Background()
// In TestMain: ensure the template once, with the schema applied.
// A migration-tool adapter's Migrate method works here too, for
// example goose.Dir("./migrations").Migrate.
tpl, err := postgres.EnsureTemplate(ctx, "with_schema",
postgres.SQLFiles("../testdata/postgres/schema"))
if err != nil {
fmt.Printf("Error creating template: %v\n", err)
return
}
defer func() {
if err := tpl.Release(ctx); err != nil {
fmt.Printf("Error releasing template: %v\n", err)
}
}()
// In your test: Clone from template (fast!)
t := &testing.T{}
db := postgres.New(t, &postgres.PoolInitializer{},
testdb.WithTemplate("with_schema"))
pool := db.Entity().(*pgxpool.Pool)
// Schema already applied from template - start testing immediately
var exists bool
err = pool.QueryRow(context.Background(), `
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'products'
)
`).Scan(&exists)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
if exists {
fmt.Println("Products table exists from migrations")
}
// Note: This example demonstrates the API but cannot be executed as a runnable
// example because it uses testing.T.
}
// Example_templateComposite demonstrates combining migrations with fixtures.
func Example_templateComposite() {
ctx := context.Background()
// In TestMain: ensure a template with both migrations and fixtures
setupFunc := func(ctx context.Context, dsn string) error {
// First apply the schema (or run your migration tool's adapter)
if err := postgres.SQLFiles("../testdata/postgres/schema")(ctx, dsn); err != nil {
return err
}
// Then load fixture data
// return postgres.LoadSQLFile("fixtures/products.sql")(ctx, dsn)
return nil
}
tpl, err := postgres.EnsureTemplate(ctx, "ecommerce_full", setupFunc)
if err != nil {
fmt.Printf("Error creating template: %v\n", err)
return
}
defer func() {
if err := tpl.Release(ctx); err != nil {
fmt.Printf("Error releasing template: %v\n", err)
}
}()
// In your test: Get fully populated database instantly
t := &testing.T{}
db := postgres.New(t, &postgres.PoolInitializer{},
testdb.WithTemplate("ecommerce_full"))
pool := db.Entity().(*pgxpool.Pool)
var exists bool
err = pool.QueryRow(context.Background(), `
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'products'
)
`).Scan(&exists)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
if exists {
fmt.Println("Schema and data ready")
}
// Note: This example demonstrates the API but cannot be executed as a runnable
// example because it uses testing.T.
}
// Example_multipleTemplates demonstrates using multiple templates for different
// test scenarios.
func Example_multipleTemplates() {
ctx := context.Background()
// In TestMain: ensure one template per scenario
us, err := postgres.EnsureTemplate(ctx, "us_region", nil)
if err != nil {
fmt.Printf("Error creating template: %v\n", err)
return
}
defer func() {
if err := us.Release(ctx); err != nil {
fmt.Printf("Error releasing template: %v\n", err)
}
}()
eu, err := postgres.EnsureTemplate(ctx, "eu_region", nil)
if err != nil {
fmt.Printf("Error creating template: %v\n", err)
return
}
defer func() {
if err := eu.Release(ctx); err != nil {
fmt.Printf("Error releasing template: %v\n", err)
}
}()
t := &testing.T{}
// US checkout test uses US data
dbUS := postgres.New(t, &postgres.PoolInitializer{},
testdb.WithTemplate("us_region"))
poolUS := dbUS.Entity().(*pgxpool.Pool)
// EU VAT test uses EU data
dbEU := postgres.New(t, &postgres.PoolInitializer{},
testdb.WithTemplate("eu_region"))
poolEU := dbEU.Entity().(*pgxpool.Pool)
// Each test has isolated regional data
var usDB, euDB string
if err := poolUS.QueryRow(ctx, "SELECT current_database()").Scan(&usDB); err != nil {
fmt.Printf("Error: %v\n", err)
return
}
if err := poolEU.QueryRow(ctx, "SELECT current_database()").Scan(&euDB); err != nil {
fmt.Printf("Error: %v\n", err)
return
}
if usDB != euDB {
fmt.Println("Each template has isolated database")
}
// Note: This example demonstrates the API but cannot be executed as a runnable
// example because it uses testing.T.
}
// Example_templateCustomSetup demonstrates using a custom setup function for
// programmatic data generation.
func Example_templateCustomSetup() {
ctx := context.Background()
// In TestMain: ensure a template with custom Go setup logic
setupFunc := func(ctx context.Context, dsn string) error {
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
return err
}
defer pool.Close()
// Create schema
_, err = pool.Exec(ctx, `
CREATE TABLE test_data (
id SERIAL PRIMARY KEY,
value INTEGER NOT NULL
)
`)
if err != nil {
return err
}
// Programmatically generate dataset
for i := range 100 {
_, err = pool.Exec(ctx,
"INSERT INTO test_data (value) VALUES ($1)", i)
if err != nil {
return err
}
}
return nil
}
tpl, err := postgres.EnsureTemplate(ctx, "large_dataset", setupFunc)
if err != nil {
fmt.Printf("Error creating template: %v\n", err)
return
}
defer func() {
if err := tpl.Release(ctx); err != nil {
fmt.Printf("Error releasing template: %v\n", err)
}
}()
// In your test: Dataset already generated
t := &testing.T{}
db := postgres.New(t, &postgres.PoolInitializer{},
testdb.WithTemplate("large_dataset"))
pool := db.Entity().(*pgxpool.Pool)
var count int
err = pool.QueryRow(context.Background(),
"SELECT COUNT(*) FROM test_data").Scan(&count)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
if count > 0 {
fmt.Println("Dataset loaded from template")
}
// Note: This example demonstrates the API but cannot be executed as a runnable
// example because it uses testing.T.
}