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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
127 changes: 127 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
10 changes: 10 additions & 0 deletions pgsandpit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 36 additions & 1 deletion session_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Loading