-
Notifications
You must be signed in to change notification settings - Fork 0
/
testenv.go
83 lines (70 loc) · 1.42 KB
/
testenv.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
package testenv
import (
"cmp"
"context"
"errors"
"sync/atomic"
"testing"
"golang.org/x/sync/errgroup"
"gorm.io/gorm"
)
type TestEnvBuilder struct {
ctx context.Context
dbEnable bool
dbUser, dbPass, dbName string
}
func New() *TestEnvBuilder {
return &TestEnvBuilder{}
}
func (b *TestEnvBuilder) Context(ctx context.Context) *TestEnvBuilder {
b.ctx = ctx
return b
}
type TestEnv struct {
DB *gorm.DB
tearDown func() error
tornDown atomic.Bool
}
func (env *TestEnv) TearDown() error {
if !env.tornDown.CompareAndSwap(false, true) {
return errors.New("torn down")
}
return env.tearDown()
}
func (b *TestEnvBuilder) SetUp() (*TestEnv, error) {
ctx := cmp.Or(b.ctx, context.Background())
env := &TestEnv{}
closers := []func() error{}
if b.dbEnable {
db, dbCloser, err := setupDatabase(ctx,
cmp.Or(b.dbUser, "test_user"),
cmp.Or(b.dbPass, "test_pass"),
cmp.Or(b.dbName, "test_db"),
)
if err != nil {
return nil, err
}
env.DB = db
closers = append(closers, dbCloser)
}
env.tearDown = func() error {
var errG errgroup.Group
for _, f := range closers {
errG.Go(f)
}
return errG.Wait()
}
return env, nil
}
func (b *TestEnvBuilder) SetUpWithT(t *testing.T) (*TestEnv, error) {
env, err := b.SetUp()
if err != nil {
return nil, err
}
t.Cleanup(func() {
if err := env.TearDown(); err != nil {
t.Logf("fail to tear down: %v", err)
}
})
return env, nil
}