-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtransaction_integration_test.go
105 lines (78 loc) · 2.22 KB
/
transaction_integration_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
//go:build with_real_db
// +build with_real_db
package pgxv4_test
import (
"context"
"fmt"
"sync/atomic"
"testing"
"time"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/stretchr/testify/require"
"github.com/avito-tech/go-transaction-manager/drivers/pgxv4/v2"
"github.com/avito-tech/go-transaction-manager/trm/v2/settings"
)
func db(ctx context.Context) (*pgxpool.Pool, error) {
uri := fmt.Sprintf("postgres://%s:%s@%s:%d/%s",
"user", "pass", "localhost", 5432, "db",
)
pool, err := pgxpool.Connect(ctx, uri)
if err != nil {
return nil, err
}
sqlStmt := `CREATE TABLE IF NOT EXISTS users_v4 (user_id SERIAL, username TEXT)`
_, err = pool.Exec(ctx, sqlStmt)
return pool, err
}
func TestTransaction_WithRealDB(t *testing.T) {
ctx := context.Background()
pool, err := db(ctx)
require.NoError(t, err)
defer pool.Close()
f := pgxv4.NewDefaultFactory(pool)
_, tr, err := f(ctx, settings.Must())
require.NoError(t, err)
require.NoError(t, tr.Rollback(ctx))
require.False(t, tr.IsActive())
require.ErrorIs(t, tr.Commit(ctx), pgx.ErrTxClosed)
require.ErrorIs(t, tr.Rollback(ctx), pgx.ErrTxClosed)
}
// transaction should release all resources if context is cancelled
// otherwise pool.Close() is blocked forever
func TestTransaction_WithRealDB_RollbackOnContextCancel(t *testing.T) {
ctx := context.Background()
pool, err := db(ctx)
require.NoError(t, err)
defer func() {
waitPoolIsClosed(t, pool)
}()
f := pgxv4.NewDefaultFactory(pool)
ctx, cancel := context.WithCancel(ctx)
_, tr, err := f(ctx, settings.Must())
require.NoError(t, err)
require.True(t, tr.IsActive())
cancel()
}
func waitPoolIsClosed(t *testing.T, pool *pgxpool.Pool) {
const checkTick = 50 * time.Millisecond
const waitDurationDeadline = 30 * time.Second
var poolClosed atomic.Bool
poolClosed.Store(false)
go func() {
pool.Close()
poolClosed.Store(true)
}()
require.Eventually(
t,
func() bool {
return poolClosed.Load()
},
waitDurationDeadline,
checkTick)
// https://github.com/jackc/pgx/issues/1641
// pool triggerHealthCheck leaves stranded goroutines for 500ms
// otherwise goleak error is triggered
const waitPoolHealthCheck = 500 * time.Millisecond
time.Sleep(waitPoolHealthCheck)
}