Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,22 @@ Options for a `*sql.DB` are chained after `With()`:
db := s.With().ReadOnly().Timeout(5 * time.Second).DB()
```

`Connector` is given the connector pgsandpit made for the `*sql.DB` and returns the connector to open it with, as `sql.OpenDB` takes one. For example, a connector that wraps it can hook into the queries:
`Connector` is given the test the session was opened for and the connector pgsandpit made for the `*sql.DB`, and returns the connector to open it with, as `sql.OpenDB` takes one. For example, a connector that wraps it can hook into the queries:

```go
db := s.With().Connector(func(c driver.Connector) driver.Connector {
db := s.With().Connector(func(t *testing.T, c driver.Connector) driver.Connector {
return &MyConnector{c}
}).DB()
```

`Conn` is called once, when `DB` makes the `*sql.DB`, with the session's `*pgx.Conn`, for example to use pgx's API:
`Conn` is called once, when `DB` makes the `*sql.DB`, with the test the session was opened for and the session's `*pgx.Conn`, for example to use pgx's API:

```go
db := s.With().Conn(func(c *pgx.Conn) {
db := s.With().Conn(func(t *testing.T, c *pgx.Conn) {
_, err := c.CopyFrom(t.Context(), pgx.Identifier{"users"}, []string{"email"}, pgx.CopyFromRows(rows))
require.NoError(t, err)
if err != nil {
t.Fatal(err)
}
}).DB()
```

Expand All @@ -64,9 +66,9 @@ Options for a session are chained after `sandpit.With()`. A `SessionBuilder` can
```go
var base = sandpit.With().
Timeout(5 * time.Second).
Conn(func(c *pgx.Conn) {
if _, err := c.Exec(context.Background(), "SET TIME ZONE 'UTC'"); err != nil {
panic(err)
Conn(func(t *testing.T, c *pgx.Conn) {
if _, err := c.Exec(t.Context(), "SET TIME ZONE 'UTC'"); err != nil {
t.Fatal(err)
}
})

Expand All @@ -80,7 +82,7 @@ func TestFoo(t *testing.T) {
- `ReadOnly` makes every `*sql.DB` of the session read-only. `Conn` is not affected by it, so it can insert the data the test reads.
- `Timeout` is the default of the session's `*sql.DB` values, which `s.With().Timeout(...)` replaces. It also bounds how long the end of the test waits for a session that is still in use.
- `Connector` is applied to every `*sql.DB` of the session, each time one is made. A `Connector` set with `s.With().Connector(...)` is given the connector the session's returned.
- `Conn` is called once, when `Session` makes the session, with the session's `*pgx.Conn`. A parameter it `SET`s applies to every `*sql.DB` of the session and is reset when the session is rolled back.
- `Conn` is called once, when `Session` makes the session, with the `t` given to `Session` and the session's `*pgx.Conn`. A parameter it `SET`s applies to every `*sql.DB` of the session and is reset when the session is rolled back.
- `Cache` makes `Session` return the session cached for `t` if there is one, and otherwise open one and cache it, so helpers can get the session from `t` alone. The options of the call that opened the session apply, and those of later calls are ignored. A subtest has its own `t`, so it gets its own session rather than its parent's.
- `Interleave` lets a statement, or a transaction, run while an application transaction is open, instead of waiting for it to end (see Interleave below).

Expand All @@ -105,10 +107,14 @@ func TestOrder(t *testing.T) {
```go
s := sandpit.Session(t)

err := svc.Transfer(ctx, s.DB(), from, to, 100)
require.Error(t, err)
if err := svc.Transfer(ctx, s.DB(), from, to, 100); err == nil {
t.Fatal("Transfer must fail")
}

assert.Equal(t, []pgsandpit.TxResult{pgsandpit.TxRolledBack}, s.TxResults())
want := []pgsandpit.TxResult{pgsandpit.TxRolledBack}
if got := s.TxResults(); !slices.Equal(got, want) {
t.Errorf("TxResults() = %v, want %v", got, want)
}
```

- `TxCommitted`: `Commit` succeeded.
Expand Down
2 changes: 1 addition & 1 deletion cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func TestCacheFirstOptionsApply(t *testing.T) {
t.Parallel()

var calls atomic.Int32
conn := func(*pgx.Conn) { calls.Add(1) }
conn := func(*testing.T, *pgx.Conn) { calls.Add(1) }

s := sandpit.With().Cache().ReadOnly().Conn(conn).Session(t)
assert.Same(t, s, sandpit.With().Cache().Conn(conn).Session(t))
Expand Down
10 changes: 5 additions & 5 deletions conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func TestDBBuilderConn(t *testing.T) {
t.Run("runs once on the session when the *sql.DB is made", func(t *testing.T) {
s := sandpit.Session(t)
calls := 0
b := s.With().Conn(func(c *pgx.Conn) {
b := s.With().Conn(func(t *testing.T, c *pgx.Conn) {
calls++
_, err := c.CopyFrom(t.Context(), pgx.Identifier{"users"}, []string{"email"},
pgx.CopyFromRows([][]any{{"copy1@example.com"}, {"copy2@example.com"}}))
Expand All @@ -37,7 +37,7 @@ func TestDBBuilderConn(t *testing.T) {
s := sandpit.Session(t)
b := s.With()
called := false
_ = b.Conn(func(*pgx.Conn) { called = true })
_ = b.Conn(func(*testing.T, *pgx.Conn) { called = true })

require.NoError(t, b.DB().Ping())
assert.False(t, called)
Expand All @@ -51,7 +51,7 @@ func TestDBBuilderConn(t *testing.T) {
done := make(chan struct{})
go func() {
defer close(done)
s.With().Conn(func(c *pgx.Conn) {
s.With().Conn(func(t *testing.T, c *pgx.Conn) {
var n int
assert.NoError(t, c.QueryRow(t.Context(), `SELECT count(*) FROM users WHERE email = 'waited@example.com'`).Scan(&n))
assert.Equal(t, 1, n)
Expand All @@ -71,7 +71,7 @@ func TestDBBuilderConnFailsTest(t *testing.T) {
case "":
case "assertion":
s := sandpit.Session(t)
s.With().Conn(func(*pgx.Conn) {
s.With().Conn(func(*testing.T, *pgx.Conn) {
require.Fail(t, "failed in the callback")
}).DB()
t.Log("DB returned")
Expand All @@ -81,7 +81,7 @@ func TestDBBuilderConnFailsTest(t *testing.T) {
tx, err := s.DB().Begin()
require.NoError(t, err)
defer tx.Rollback()
s.With().Timeout(100 * time.Millisecond).Conn(func(*pgx.Conn) {}).DB()
s.With().Timeout(100 * time.Millisecond).Conn(func(*testing.T, *pgx.Conn) {}).DB()
t.Log("DB returned")
return
}
Expand Down
6 changes: 3 additions & 3 deletions connector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func TestConnector(t *testing.T) {
t.Run("wrap the connector to hook into queries", func(t *testing.T) {
s := sandpit.Session(t)
hook := &hookConnector{}
db := s.With().Connector(func(c driver.Connector) driver.Connector {
db := s.With().Connector(func(_ *testing.T, c driver.Connector) driver.Connector {
hook.Connector = c
return hook
}).DB()
Expand All @@ -80,7 +80,7 @@ func TestConnector(t *testing.T) {

cfg, err := pgx.ParseConfig(dsn())
require.NoError(t, err)
db := s.With().Connector(func(driver.Connector) driver.Connector {
db := s.With().Connector(func(*testing.T, driver.Connector) driver.Connector {
return stdlib.GetConnector(*cfg)
}).DB()

Expand All @@ -92,7 +92,7 @@ func TestConnector(t *testing.T) {
s := sandpit.Session(t)
b := s.With()
called := false
_ = b.Connector(func(c driver.Connector) driver.Connector {
_ = b.Connector(func(_ *testing.T, c driver.Connector) driver.Connector {
called = true
return c
})
Expand Down
20 changes: 11 additions & 9 deletions db_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"database/sql"
"database/sql/driver"
"errors"
"testing"
"time"

"github.com/jackc/pgx/v5"
Expand All @@ -16,8 +17,8 @@ type DBBuilder struct {
s *Session
readOnly bool
timeout time.Duration
connector func(driver.Connector) driver.Connector
conn func(*pgx.Conn)
connector func(*testing.T, driver.Connector) driver.Connector
conn func(*testing.T, *pgx.Conn)
}

// ReadOnly makes the *sql.DB reject writes. It still sees what the other
Expand All @@ -43,21 +44,22 @@ func (b *DBBuilder) Timeout(d time.Duration) *DBBuilder {
// Connector sets a function that is given the connector pgsandpit made for the
// *sql.DB and returns the connector the *sql.DB is opened with, as by
// sql.OpenDB. If the session was built with SessionBuilder.Connector, f is
// given the connector that function returned.
func (b *DBBuilder) Connector(f func(driver.Connector) driver.Connector) *DBBuilder {
// given the connector that function returned. t is the test the session was
// opened for.
func (b *DBBuilder) Connector(f func(t *testing.T, c driver.Connector) driver.Connector) *DBBuilder {
c := *b
c.connector = f
return &c
}

// Conn sets a function that DB calls once, before it returns, with the
// session's *pgx.Conn. DB waits for the session as the *sql.DB's calls do, and
// holds it while f runs.
// test the session was opened for and the session's *pgx.Conn. DB waits for the
// session as the *sql.DB's calls do, and holds it while f runs.
//
// What f runs, runs in the session's transaction as it is: it is not read-only,
// and a statement that fails aborts the session's transaction. f must not
// begin, commit or roll back a transaction, nor use c after it returns.
func (b *DBBuilder) Conn(f func(c *pgx.Conn)) *DBBuilder {
func (b *DBBuilder) Conn(f func(t *testing.T, c *pgx.Conn)) *DBBuilder {
c := *b
c.conn = f
return &c
Expand All @@ -73,10 +75,10 @@ func (b *DBBuilder) DB() *sql.DB {
}
var c driver.Connector = &connector{b: *b}
if b.s.connector != nil {
c = b.s.connector(c)
c = b.s.connector(b.s.t, c)
}
if b.connector != nil {
c = b.connector(c)
c = b.connector(b.s.t, c)
}
db := sql.OpenDB(c)
// Registered after the session's cleanup, so it runs before it.
Expand Down
6 changes: 3 additions & 3 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ type Session struct {
// opened through, and whether statements interleave with transactions.
readOnly bool
timeout time.Duration
connector func(driver.Connector) driver.Connector
connector func(*testing.T, driver.Connector) driver.Connector
interleave bool

// sem is held while a statement runs. Without interleave, an application
Expand Down Expand Up @@ -203,7 +203,7 @@ func (s *Session) close() {
}

// withPgxConn runs f with the session's *pgx.Conn while it holds the session.
func (s *Session) withPgxConn(timeout time.Duration, f func(*pgx.Conn)) error {
func (s *Session) withPgxConn(timeout time.Duration, f func(*testing.T, *pgx.Conn)) error {
release, err := s.acquire(context.Background(), timeout)
if err != nil {
return err
Expand All @@ -221,7 +221,7 @@ func (s *Session) withPgxConn(timeout time.Duration, f func(*pgx.Conn)) error {
// does, Raw would take it for a panic and release the connection with
// driver.ErrBadConn, so that database/sql may discard it. Holding the session
// keeps c from being used by anything else meanwhile.
f(c)
f(s.t, c)
return nil
}

Expand Down
21 changes: 11 additions & 10 deletions session_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ type SessionBuilder struct {
sp *Sandpit
readOnly bool
timeout time.Duration
connector func(driver.Connector) driver.Connector
conn func(*pgx.Conn)
connector func(*testing.T, driver.Connector) driver.Connector
conn func(*testing.T, *pgx.Conn)
cache bool
interleave bool
}
Expand All @@ -50,23 +50,24 @@ func (b *SessionBuilder) Timeout(d time.Duration) *SessionBuilder {

// Connector sets a function that is given the connector pgsandpit made for each
// *sql.DB of the session and returns the connector the *sql.DB is opened with.
// It is called each time a *sql.DB is made. A function set with
// DBBuilder.Connector is given what f returns.
func (b *SessionBuilder) Connector(f func(driver.Connector) driver.Connector) *SessionBuilder {
// It is called each time a *sql.DB is made, with the test the session was opened
// for as t. A function set with DBBuilder.Connector is given what f returns.
func (b *SessionBuilder) Connector(f func(t *testing.T, c driver.Connector) driver.Connector) *SessionBuilder {
c := *b
c.connector = f
return &c
}

// Conn sets a function that Session calls once, before it returns, with the
// session's *pgx.Conn, for example to SET a parameter for the session or to
// insert data the test needs. A parameter SET this way applies to every *sql.DB
// of the session and is reset when the session's transaction is rolled back.
// Conn sets a function that Session calls once, before it returns, with the t
// given to Session and the session's *pgx.Conn, for example to SET a parameter
// for the session or to insert data the test needs. A parameter SET this way
// applies to every *sql.DB of the session and is reset when the session's
// transaction is rolled back.
//
// What f runs, runs in the session's transaction as it is: a statement that
// fails aborts the session's transaction. f must not begin, commit or roll back
// a transaction, nor use c after it returns.
func (b *SessionBuilder) Conn(f func(c *pgx.Conn)) *SessionBuilder {
func (b *SessionBuilder) Conn(f func(t *testing.T, c *pgx.Conn)) *SessionBuilder {
c := *b
c.conn = f
return &c
Expand Down
41 changes: 32 additions & 9 deletions session_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestSessionBuilderReadOnly(t *testing.T) {
})

t.Run("does not affect Conn", func(t *testing.T) {
s := sandpit.With().ReadOnly().Conn(func(c *pgx.Conn) {
s := sandpit.With().ReadOnly().Conn(func(t *testing.T, c *pgx.Conn) {
_, err := c.Exec(t.Context(), `INSERT INTO users (email) VALUES ('session-ro-conn@example.com')`)
require.NoError(t, err)
}).Session(t)
Expand Down Expand Up @@ -95,7 +95,7 @@ func TestSessionBuilderConnector(t *testing.T) {

t.Run("is applied to every *sql.DB", func(t *testing.T) {
var hooks []*hookConnector
s := sandpit.With().Connector(func(c driver.Connector) driver.Connector {
s := sandpit.With().Connector(func(_ *testing.T, c driver.Connector) driver.Connector {
h := &hookConnector{Connector: c}
hooks = append(hooks, h)
return h
Expand All @@ -113,13 +113,13 @@ func TestSessionBuilderConnector(t *testing.T) {

t.Run("is wrapped by DBBuilder.Connector", func(t *testing.T) {
sessionHook := &hookConnector{}
s := sandpit.With().Connector(func(c driver.Connector) driver.Connector {
s := sandpit.With().Connector(func(_ *testing.T, c driver.Connector) driver.Connector {
sessionHook.Connector = c
return sessionHook
}).Session(t)

dbHook := &hookConnector{}
_, err := s.With().Connector(func(c driver.Connector) driver.Connector {
_, err := s.With().Connector(func(t *testing.T, c driver.Connector) driver.Connector {
// Given what the session's function returned.
assert.Same(t, sessionHook, c)
dbHook.Connector = c
Expand All @@ -134,7 +134,7 @@ func TestSessionBuilderConnector(t *testing.T) {
t.Run("does not change the builder", func(t *testing.T) {
b := sandpit.With()
called := false
_ = b.Connector(func(c driver.Connector) driver.Connector {
_ = b.Connector(func(_ *testing.T, c driver.Connector) driver.Connector {
called = true
return c
})
Expand All @@ -149,7 +149,7 @@ func TestSessionBuilderConn(t *testing.T) {

t.Run("runs once when the session is made", func(t *testing.T) {
calls := 0
b := sandpit.With().Conn(func(c *pgx.Conn) {
b := sandpit.With().Conn(func(t *testing.T, c *pgx.Conn) {
calls++
_, err := c.Exec(t.Context(), `INSERT INTO users (email) VALUES ('session-conn@example.com')`)
require.NoError(t, err)
Expand All @@ -165,7 +165,7 @@ func TestSessionBuilderConn(t *testing.T) {
})

t.Run("sets a parameter for every *sql.DB of the session", func(t *testing.T) {
s := sandpit.With().Conn(func(c *pgx.Conn) {
s := sandpit.With().Conn(func(t *testing.T, c *pgx.Conn) {
_, err := c.Exec(t.Context(), `SET application_name = 'pgsandpit_session_conn'`)
require.NoError(t, err)
}).Session(t)
Expand All @@ -180,16 +180,39 @@ func TestSessionBuilderConn(t *testing.T) {
t.Run("does not change the builder", func(t *testing.T) {
b := sandpit.With()
called := false
_ = b.Conn(func(*pgx.Conn) { called = true })
_ = b.Conn(func(*testing.T, *pgx.Conn) { called = true })

require.NoError(t, b.Session(t).DB().Ping())
assert.False(t, called)
})
}

func TestBuilderFuncsAreGivenTheSessionsTest(t *testing.T) {
t.Parallel()

var got []*testing.T
conn := func(t *testing.T, _ *pgx.Conn) { got = append(got, t) }
connector := func(t *testing.T, c driver.Connector) driver.Connector {
got = append(got, t)
return c
}

s := sandpit.With().Conn(conn).Connector(connector).Session(t)
t.Run("from a subtest", func(*testing.T) {
s.With().Conn(conn).Connector(connector).DB()
})

// SessionBuilder.Conn, DBBuilder.Conn, SessionBuilder.Connector and
// DBBuilder.Connector.
require.Len(t, got, 4)
for _, g := range got {
assert.Same(t, t, g)
}
}

func TestSessionBuilderConnFailsTest(t *testing.T) {
if os.Getenv("PGSANDPIT_CHILD_SESSION_CONN") != "" {
sandpit.With().Conn(func(*pgx.Conn) {
sandpit.With().Conn(func(*testing.T, *pgx.Conn) {
require.Fail(t, "failed in the callback")
}).Session(t)
t.Log("Session returned")
Expand Down
Loading