Skip to content

Commit 0f61c88

Browse files
test: add delay proxy for ping test
1 parent c1c74da commit 0f61c88

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

pgxpool/helper_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package pgxpool_test
2+
3+
import (
4+
"context"
5+
"net"
6+
"time"
7+
8+
"github.com/jackc/pgx/v5/pgconn"
9+
)
10+
11+
// delayProxy is a that introduces a configurable delay on reads from the database connection.
12+
type delayProxy struct {
13+
net.Conn
14+
readDelay time.Duration
15+
}
16+
17+
func newDelayProxy(conn net.Conn, readDelay time.Duration) *delayProxy {
18+
p := &delayProxy{
19+
Conn: conn,
20+
readDelay: readDelay,
21+
}
22+
23+
return p
24+
}
25+
26+
func (dp *delayProxy) Read(b []byte) (int, error) {
27+
if dp.readDelay > 0 {
28+
time.Sleep(dp.readDelay)
29+
}
30+
31+
return dp.Conn.Read(b)
32+
}
33+
34+
func newDelayProxyDialFunc(readDelay time.Duration) pgconn.DialFunc {
35+
return func(ctx context.Context, network, addr string) (net.Conn, error) {
36+
conn, err := net.Dial(network, addr)
37+
return newDelayProxy(conn, readDelay), err
38+
}
39+
}

pgxpool/pool_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1291,18 +1291,18 @@ func TestPoolAcquirePingTimeout(t *testing.T) {
12911291
config, err := pgxpool.ParseConfig(os.Getenv("PGX_TEST_DATABASE"))
12921292
require.NoError(t, err)
12931293

1294-
// Set a very short ping timeout to force timeout during ping and destruction of the connection
1295-
config.PingTimeout = 1 * time.Nanosecond
1294+
config.PingTimeout = 200 * time.Millisecond
1295+
config.ConnConfig.DialFunc = newDelayProxyDialFunc(500 * time.Millisecond)
12961296

12971297
var conID *uint32
12981298
// Only ping the connection with the original PID to force creation of a new connection
12991299
config.ShouldPing = func(_ context.Context, params pgxpool.ShouldPingParams) bool {
13001300
if conID != nil && params.Conn.PgConn().PID() == *conID {
13011301
return true
13021302
}
1303-
13041303
return false
13051304
}
1305+
13061306
// Limit to a single connection to ensure the same connection is reused
13071307
config.MinConns = 1
13081308
config.MaxConns = 1

0 commit comments

Comments
 (0)