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
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,29 @@ sandpit := pgsandpit.NewWithConfig(cfg,

The connections are pooled across sessions, so `OptionAfterConnect` runs once per connection, not once per session. pgsandpit replaces `BuildContextWatcherHandler` (see Cancellation below).

To choose a database by name, for example in a table-driven test, register a `Sandpit` under a name and get it with `Lookup`. Each test package runs in its own process, so a package shared by the tests can register the names in its `init` function:

```go
// internal/testdb/testdb.go
package testdb

func init() {
pgsandpit.Register("testdb1", pgsandpit.New("postgres://xxx"))
pgsandpit.Register("testdb2", pgsandpit.New("postgres://yyy"))
}
```

```go
import _ "example.com/myapp/internal/testdb"

func TestFoo(t *testing.T) {
s := pgsandpit.Lookup("testdb1").Session(t)
// ...
}
```

`Register` panics if the name is already registered, and `Lookup` panics if it is not registered. A `Sandpit` does not connect until the first `Session` call, so registering one does not connect to the database.

## Behavior

- **Isolation**: each `Session` has its own connection and transaction, so parallel tests do not see each other's data. Tests that write the same rows or unique keys still wait for each other's locks until the first test ends.
Expand Down
45 changes: 45 additions & 0 deletions registry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package pgsandpit

import (
"fmt"
"sync"
)

var (
registryMu sync.RWMutex
registry = map[string]*Sandpit{}
)

// Register makes sp available under name, so that tests can choose a database
// by name with Lookup. Each test package runs in its own process, so a package
// shared by the tests can register the names in its init function:
//
// func init() {
// pgsandpit.Register("testdb1", pgsandpit.New("postgres://..."))
// }
//
// Register panics if sp is nil or name is already registered. Register and
// Lookup are safe for concurrent use.
func Register(name string, sp *Sandpit) {
if sp == nil {
panic("pgsandpit: Register of a nil Sandpit")
}
registryMu.Lock()
defer registryMu.Unlock()
if _, ok := registry[name]; ok {
panic(fmt.Sprintf("pgsandpit: Register called twice for %q", name))
}
registry[name] = sp
}

// Lookup returns the Sandpit registered under name. It panics if name is not
// registered.
func Lookup(name string) *Sandpit {
registryMu.RLock()
defer registryMu.RUnlock()
sp, ok := registry[name]
if !ok {
panic(fmt.Sprintf("pgsandpit: unknown name %q (is the package that registers it imported?)", name))
}
return sp
}
121 changes: 121 additions & 0 deletions registry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package pgsandpit_test

import (
"fmt"
"sync"
"sync/atomic"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/winebarrel/pgsandpit"
)

var registryNames atomic.Int64

// uniqueName returns a name that is not registered yet. The registry cannot be
// emptied, so a fixed name would panic when the tests run with -count above 1.
func uniqueName() string {
return fmt.Sprintf("name-%d", registryNames.Add(1))
}

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

name := uniqueName()
sp := pgsandpit.New(dsn())
t.Cleanup(func() { assert.NoError(t, sp.Close()) })
pgsandpit.Register(name, sp)

assert.Same(t, sp, pgsandpit.Lookup(name))

var one int
require.NoError(t, pgsandpit.Lookup(name).Session(t).DB().QueryRow("SELECT 1").Scan(&one))
assert.Equal(t, 1, one)
}

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

nameA, nameB := uniqueName(), uniqueName()
a := pgsandpit.New(dsn())
b := pgsandpit.New(dsn())
pgsandpit.Register(nameA, a)
pgsandpit.Register(nameB, b)

assert.Same(t, a, pgsandpit.Lookup(nameA))
assert.Same(t, b, pgsandpit.Lookup(nameB))
}

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

var wg sync.WaitGroup
for range 100 {
wg.Go(func() {
name := uniqueName()
sp := pgsandpit.New(dsn())
pgsandpit.Register(name, sp)
assert.Same(t, sp, pgsandpit.Lookup(name))
})
}
wg.Wait()
}

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

name := uniqueName()
var registered, panicked atomic.Int32
var winner atomic.Pointer[pgsandpit.Sandpit]

var wg sync.WaitGroup
for range 100 {
wg.Go(func() {
defer func() {
if recover() != nil {
panicked.Add(1)
}
}()
sp := pgsandpit.New(dsn())
pgsandpit.Register(name, sp)
winner.Store(sp)
registered.Add(1)
})
}
wg.Wait()

assert.Equal(t, int32(1), registered.Load())
assert.Equal(t, int32(99), panicked.Load())
assert.Same(t, winner.Load(), pgsandpit.Lookup(name))
}

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

name := uniqueName()
pgsandpit.Register(name, pgsandpit.New(dsn()))

want := fmt.Sprintf("pgsandpit: Register called twice for %q", name)
assert.PanicsWithValue(t, want, func() {
pgsandpit.Register(name, pgsandpit.New(dsn()))
})
}

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

assert.PanicsWithValue(t, "pgsandpit: Register of a nil Sandpit", func() {
pgsandpit.Register(uniqueName(), nil)
})
}

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

name := uniqueName()
want := fmt.Sprintf("pgsandpit: unknown name %q (is the package that registers it imported?)", name)
assert.PanicsWithValue(t, want, func() {
pgsandpit.Lookup(name)
})
}
Loading