From 84bd1fa23676007d4d5367fd18ba22f5785562e5 Mon Sep 17 00:00:00 2001 From: winebarrel Date: Sun, 8 Nov 2026 17:31:22 +0900 Subject: [PATCH] Add Register and Lookup Co-Authored-By: Claude Opus 5.5 --- README.md | 23 +++++++++ registry.go | 45 ++++++++++++++++++ registry_test.go | 121 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 189 insertions(+) create mode 100644 registry.go create mode 100644 registry_test.go diff --git a/README.md b/README.md index 928492b..13c9cef 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/registry.go b/registry.go new file mode 100644 index 0000000..9bdc2c3 --- /dev/null +++ b/registry.go @@ -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 +} diff --git a/registry_test.go b/registry_test.go new file mode 100644 index 0000000..9936a9e --- /dev/null +++ b/registry_test.go @@ -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) + }) +}