-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain_test.go
More file actions
77 lines (61 loc) · 1.82 KB
/
Copy pathmain_test.go
File metadata and controls
77 lines (61 loc) · 1.82 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
package gosmig
import (
"context"
"database/sql"
"fmt"
"testing"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/jmoiron/sqlx"
"github.com/stretchr/testify/assert"
)
const testDBURL = "postgres://gosmig:gosmig@localhost:5432/gosmig?sslmode=disable&search_path=public"
func TestMain(m *testing.M) {
m.Run()
}
func connectToDB_StdLibSQL(url string, timeout time.Duration) (*sql.DB, error) {
db, err := sql.Open("pgx", url)
if err != nil {
return nil, fmt.Errorf("failed to open a database connection: %w", err)
}
ctxPing, cancelPing := context.WithTimeout(context.Background(), timeout)
defer cancelPing()
if err := db.PingContext(ctxPing); err != nil {
return nil, fmt.Errorf("failed to ping the database: %w", err)
}
return db, nil
}
func connectToDB_SQLX(url string, timeout time.Duration) (*sqlx.DB, error) {
db, err := sqlx.Open("pgx", url)
if err != nil {
return nil, fmt.Errorf("failed to open a database connection: %w", err)
}
ctxPing, cancelPing := context.WithTimeout(context.Background(), timeout)
defer cancelPing()
if err := db.PingContext(ctxPing); err != nil {
return nil, fmt.Errorf("failed to ping the database: %w", err)
}
return db, nil
}
func dropTables[TDBRow DBRow, TDBResult DBResult, TDBOrTX DBOrTX[TDBRow, TDBResult]](
t *testing.T,
tables []string,
db TDBOrTX,
timeout time.Duration) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
for _, table := range tables {
_, err := db.ExecContext(ctx, fmt.Sprintf(`DROP TABLE IF EXISTS %s`, table))
assert.NoError(t, err, fmt.Sprintf("failed to drop table %q", table))
}
}
func cleanup[
TDBRow DBRow,
TDBResult DBResult,
TTX TX[TDBRow, TDBResult],
TXO TXOptions,
TDB DB[TDBRow, TDBResult, TTX, TXO]](
t *testing.T, tables []string, db TDB,
) {
dropTables(t, tables, db, defaultTimeout)
}