Skip to content

Commit 5534a2f

Browse files
committed
Add WithFixtures & WithSQLs methods to load fixtures. Add posibility to skip database tests if uri is not specified.
1 parent bed384b commit 5534a2f

File tree

1 file changed

+52
-2
lines changed

1 file changed

+52
-2
lines changed

database.go

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,12 @@ type Fixture struct {
2626
}
2727

2828
type Pgpool interface {
29-
//WithFixtures(t testing.TB, fixtures []Fixture)
30-
//WithSQLs(t testing.TB, sqls []string)
29+
// WithFixtures creates database from template database, and initializes it
30+
// with fixtures from `fixtures` array
31+
WithFixtures(t testing.TB, fixtures []Fixture) (*pgxpool.Pool, func())
32+
// WithSQLs creates database from template database, and initializes it
33+
// with fixtures from `sqls` array
34+
WithSQLs(t testing.TB, sqls []string) (*pgxpool.Pool, func())
3135
// WithEmpty creates empty database from template database, that was
3236
// created from `schema` file.
3337
WithEmpty(t testing.TB) (*pgxpool.Pool, func())
@@ -43,7 +47,45 @@ type pgpool struct {
4347
rnd *rand.Rand
4448
}
4549

50+
func (p *pgpool) WithFixtures(
51+
t testing.TB,
52+
fixtures []Fixture,
53+
) (*pgxpool.Pool, func()) {
54+
pool, clean := p.WithEmpty(t)
55+
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
56+
defer cancel()
57+
for i, f := range fixtures {
58+
if _, err := pool.Exec(ctx, f.Query, f.Params...); err != nil {
59+
clean()
60+
t.Fatalf(
61+
"can't load fixture at idx %v: %+v",
62+
i, errors.WithStack(err),
63+
)
64+
}
65+
}
66+
return pool, clean
67+
}
68+
69+
func (p *pgpool) WithSQLs(t testing.TB, sqls []string) (*pgxpool.Pool, func()) {
70+
pool, clean := p.WithEmpty(t)
71+
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
72+
defer cancel()
73+
for i, s := range sqls {
74+
if _, err := pool.Exec(ctx, s); err != nil {
75+
clean()
76+
t.Fatalf(
77+
"can't load fixture at idx %v: %+v",
78+
i, errors.WithStack(err),
79+
)
80+
}
81+
}
82+
return pool, clean
83+
}
84+
4685
func (p *pgpool) getTmpl(t testing.TB) string {
86+
if p.uri == "" {
87+
t.Skip("database uri is not set")
88+
}
4789
t.Helper()
4890
p.m.RLock()
4991
err := p.err
@@ -234,6 +276,14 @@ func quote(name string) string {
234276
// NewPool create new Pgpool interface. It won't connect to database
235277
// until first reuse. `schema` file must exists and be valid SQL script.
236278
func NewPool(dbUri, schema, baseName string) Pgpool {
279+
if dbUri != "" {
280+
if baseName == "" {
281+
panic("baseName is required if database uri is set")
282+
}
283+
if schema == "" {
284+
panic("schema file name is required if database uri is set")
285+
}
286+
}
237287
return &pgpool{
238288
uri: dbUri,
239289
baseName: baseName,

0 commit comments

Comments
 (0)