diff --git a/README.md b/README.md index 14d0840..cf9acc1 100644 --- a/README.md +++ b/README.md @@ -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() ``` @@ -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) } }) @@ -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). @@ -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. diff --git a/cache_test.go b/cache_test.go index f935b8b..0fc1363 100644 --- a/cache_test.go +++ b/cache_test.go @@ -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)) diff --git a/conn_test.go b/conn_test.go index b8742fd..4d6a2f4 100644 --- a/conn_test.go +++ b/conn_test.go @@ -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"}})) @@ -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) @@ -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) @@ -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") @@ -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 } diff --git a/connector_test.go b/connector_test.go index 27157a4..e0aa28f 100644 --- a/connector_test.go +++ b/connector_test.go @@ -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() @@ -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() @@ -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 }) diff --git a/db_builder.go b/db_builder.go index 230b7ca..1274724 100644 --- a/db_builder.go +++ b/db_builder.go @@ -5,6 +5,7 @@ import ( "database/sql" "database/sql/driver" "errors" + "testing" "time" "github.com/jackc/pgx/v5" @@ -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 @@ -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 @@ -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. diff --git a/session.go b/session.go index 5baa505..dd79c84 100644 --- a/session.go +++ b/session.go @@ -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 @@ -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 @@ -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 } diff --git a/session_builder.go b/session_builder.go index 0a6ffc1..b3cb5b0 100644 --- a/session_builder.go +++ b/session_builder.go @@ -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 } @@ -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 diff --git a/session_builder_test.go b/session_builder_test.go index fdd425e..f923aec 100644 --- a/session_builder_test.go +++ b/session_builder_test.go @@ -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) @@ -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 @@ -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 @@ -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 }) @@ -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) @@ -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) @@ -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")