diff --git a/README.md b/README.md index 13c9cef..485d90f 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,23 @@ func TestFoo(t *testing.T) { - `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. +- `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. + +```go +var cached = sandpit.With().Cache() + +func insertOrder(t *testing.T) { + t.Helper() + db := cached.Session(t).DB() + // ... +} + +func TestOrder(t *testing.T) { + insertOrder(t) + s := cached.Session(t) // the session insertOrder used + // ... +} +``` `TxResults` returns how the transactions of the session's `*sql.DB` values ended, in order, so a test can check that the code under test rolled back: diff --git a/cache_test.go b/cache_test.go new file mode 100644 index 0000000..f935b8b --- /dev/null +++ b/cache_test.go @@ -0,0 +1,127 @@ +package pgsandpit_test + +import ( + "os" + "sync" + "sync/atomic" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/winebarrel/pgsandpit" +) + +func backendPID(t *testing.T, s *pgsandpit.Session) int { + t.Helper() + var pid int + require.NoError(t, s.DB().QueryRow("SELECT pg_backend_pid()").Scan(&pid)) + return pid +} + +func TestCacheSameTest(t *testing.T) { + t.Parallel() + + s := sandpit.With().Cache().Session(t) + assert.Same(t, s, sandpit.With().Cache().Session(t)) +} + +func TestCacheNotUsedWithoutCache(t *testing.T) { + t.Parallel() + + plain := sandpit.Session(t) + s := sandpit.With().Cache().Session(t) + assert.NotSame(t, plain, s, "a session built without Cache must not be cached") + assert.NotSame(t, s, sandpit.Session(t), "Session without Cache must open a new session") +} + +func TestCacheFirstOptionsApply(t *testing.T) { + t.Parallel() + + var calls atomic.Int32 + conn := func(*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)) + assert.Equal(t, int32(1), calls.Load()) + + _, err := s.DB().Exec("CREATE TEMP TABLE cache_first_options (id int)") + require.Error(t, err, "the session must stay read-only") +} + +func TestCacheConcurrentCalls(t *testing.T) { + t.Parallel() + + const n = 10 + b := sandpit.With().Cache() + got := make([]*pgsandpit.Session, n) + var wg sync.WaitGroup + for i := range n { + wg.Go(func() { got[i] = b.Session(t) }) + } + wg.Wait() + + for _, s := range got { + assert.Same(t, got[0], s) + } +} + +func TestCacheSeparatesTests(t *testing.T) { + t.Parallel() + + b := sandpit.With().Cache() + parent := b.Session(t) + parentPID := backendPID(t, parent) + + t.Run("subtest", func(t *testing.T) { + s := b.Session(t) + assert.NotSame(t, parent, s) + assert.NotEqual(t, parentPID, backendPID(t, s)) + }) + + assert.Same(t, parent, b.Session(t), "a subtest must not replace its parent's session") +} + +func TestCacheSeparatesSandpits(t *testing.T) { + t.Parallel() + + other := pgsandpit.New(dsn()) + t.Cleanup(func() { assert.NoError(t, other.Close()) }) + + assert.NotSame(t, sandpit.With().Cache().Session(t), other.With().Cache().Session(t)) +} + +func TestCacheForgottenAfterSessionCloses(t *testing.T) { + t.Parallel() + + var s *pgsandpit.Session + t.Run("subtest", func(t *testing.T) { + // Runs after the session is rolled back and forgotten, and gets a new one. + t.Cleanup(func() { + assert.NotSame(t, s, sandpit.With().Cache().Session(t)) + }) + s = sandpit.With().Cache().Session(t) + }) +} + +func TestCacheFailsTestAfterFailedCall(t *testing.T) { + if os.Getenv("PGSANDPIT_CHILD_CACHE") != "" { + b := pgsandpit.New("postgres://localhost:notaport/postgres").With().Cache() + done := make(chan struct{}) + go func() { + defer close(done) + b.Session(t) + }() + <-done + b.Session(t) + t.Log("Session returned") + return + } + t.Parallel() + + out, err := runChild(t, "TestCacheFailsTestAfterFailedCall", "PGSANDPIT_CHILD_CACHE=1") + require.Error(t, err) + assert.Contains(t, out, "pgsandpit: cannot parse") + assert.NotContains(t, out, "Session returned") + assert.NotContains(t, out, "panic") +} diff --git a/pgsandpit.go b/pgsandpit.go index 766d726..d47114b 100644 --- a/pgsandpit.go +++ b/pgsandpit.go @@ -45,6 +45,16 @@ type Sandpit struct { once sync.Once db *sql.DB err error + + cached sync.Map // *testing.T -> *cachedSession +} + +// cachedSession is the entry of a test in Sandpit.cached. once makes concurrent +// callers wait for one call that opens the session, and s stays nil if that call +// failed the test. +type cachedSession struct { + once sync.Once + s *Session } // New returns a Sandpit for the database dsn points to. It does not connect diff --git a/session_builder.go b/session_builder.go index 41ce942..59a158c 100644 --- a/session_builder.go +++ b/session_builder.go @@ -25,6 +25,7 @@ type SessionBuilder struct { timeout time.Duration connector func(driver.Connector) driver.Connector conn func(*pgx.Conn) + cache bool } // ReadOnly makes every *sql.DB of the session reject writes, as @@ -70,10 +71,44 @@ func (b *SessionBuilder) Conn(f func(c *pgx.Conn)) *SessionBuilder { return &c } +// Cache makes Session return the session cached for t in the Sandpit if there is +// one, and otherwise open one and cache it until t and its subtests finish, so +// that helpers can get the session from t alone. +// +// The options of the call that opened the session apply: those of a later call +// that finds it in the cache are ignored. Only sessions built with Cache are +// cached. A subtest has its own t, so it gets its own session rather than its +// parent's. +func (b *SessionBuilder) Cache() *SessionBuilder { + c := *b + c.cache = true + return &c +} + // Session opens a connection, begins a transaction on it, and returns a // Session for it. The transaction is rolled back and the connection closed when -// t and its subtests finish. Session fails t if it cannot connect. +// t and its subtests finish. Session fails t if it cannot connect. With Cache, +// it returns the session cached for t if there is one. func (b *SessionBuilder) Session(t *testing.T) *Session { + t.Helper() + if !b.cache { + return b.open(t) + } + v, _ := b.sp.cached.LoadOrStore(t, &cachedSession{}) + e := v.(*cachedSession) + e.once.Do(func() { + t.Helper() + t.Cleanup(func() { b.sp.cached.Delete(t) }) + e.s = b.open(t) + }) + if e.s == nil { + // Another call failed to open the session and has reported why. + t.FailNow() + } + return e.s +} + +func (b *SessionBuilder) open(t *testing.T) *Session { t.Helper() pool, err := b.sp.pool() if err != nil {