Documentation
¶
Overview ¶
Package pgsandpit gives each test a PostgreSQL session wrapped in a transaction that is rolled back when the test ends, and hands the test *sql.DB values that run on that session.
var sandpit = pgsandpit.New("postgres://postgres@localhost:5432/postgres")
func TestFoo(t *testing.T) {
t.Parallel()
s := sandpit.Session(t)
db := s.DB()
ro := s.With().ReadOnly().DB()
// db and ro share the session: ro sees what db wrote, and nothing is
// left in the database after the test.
}
Index ¶
- Constants
- Variables
- func Register(name string, sp *Sandpit)
- type DBBuilder
- type Sandpit
- type Session
- type SessionBuilder
- func (b *SessionBuilder) Cache() *SessionBuilder
- func (b *SessionBuilder) Conn(f func(t *testing.T, c *pgx.Conn)) *SessionBuilder
- func (b *SessionBuilder) Connector(f func(driver.Connector) driver.Connector) *SessionBuilder
- func (b *SessionBuilder) Interleave() *SessionBuilder
- func (b *SessionBuilder) ReadOnly() *SessionBuilder
- func (b *SessionBuilder) Session(t *testing.T) *Session
- func (b *SessionBuilder) Timeout(d time.Duration) *SessionBuilder
- type TxResult
Constants ¶
const DefaultTimeout = 60 * time.Second
DefaultTimeout is how long a call waits for the session while another transaction holds it, unless the session was built with SessionBuilder.Timeout or the *sql.DB with DBBuilder.Timeout.
Variables ¶
var ( // ErrTimeout is returned, wrapped, when a call waited longer than the // timeout for the session. It usually means a transaction was left open, // or the *sql.DB was used outside a transaction while that transaction was // open in the same goroutine. ErrTimeout = errors.New("pgsandpit: timed out waiting for the session") // ErrSessionClosed is returned when a *sql.DB is used after its session // ended. ErrSessionClosed = errors.New("pgsandpit: session is closed") // ErrTxOrder is returned, wrapped, with SessionBuilder.Interleave, when // nested transactions do not end in the reverse order they began, such as // when transactions in different goroutines overlap. The transactions that // could not end as asked are rolled back. ErrTxOrder = errors.New("pgsandpit: transactions ended out of order") )
Functions ¶
func Register ¶ added in v0.5.0
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.
Types ¶
type DBBuilder ¶ added in v0.3.0
type DBBuilder struct {
// contains filtered or unexported fields
}
DBBuilder builds a *sql.DB for a Session. Each method returns a new DBBuilder, so a DBBuilder can be shared and branched.
func (*DBBuilder) Conn ¶ added in v0.3.0
Conn sets a function that DB calls once, before it returns, with the 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 (*DBBuilder) Connector ¶ added in v0.3.0
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 (*DBBuilder) DB ¶ added in v0.3.0
DB returns the *sql.DB. It is closed when the test ends; closing it earlier does not end the session.
func (*DBBuilder) ReadOnly ¶ added in v0.3.0
ReadOnly makes the *sql.DB reject writes. It still sees what the other *sql.DB values of the session wrote. A rejected write fails only that statement, as in a read-only transaction outside a test, except that inside an application transaction it aborts that transaction. Every *sql.DB of a session built with SessionBuilder.ReadOnly is read-only.
type Sandpit ¶
type Sandpit struct {
// contains filtered or unexported fields
}
Sandpit opens sessions on one database. Create it once per test package.
func Lookup ¶ added in v0.5.0
Lookup returns the Sandpit registered under name. It panics if name is not registered.
func New ¶
New returns a Sandpit for the database dsn points to. It does not connect until the first Session call.
func NewWithConfig ¶ added in v0.2.0
func NewWithConfig(cfg *pgx.ConnConfig, opts ...stdlib.OptionOpenDB) *Sandpit
NewWithConfig returns a Sandpit that connects with a copy of cfg and opts, as stdlib.OpenDB does. It does not connect until the first Session call.
pgsandpit replaces cfg.BuildContextWatcherHandler, so that a canceled context cancels the query instead of closing the session's connection.
The connections are pooled across sessions: a hook such as stdlib.OptionAfterConnect runs once per connection, not once per session.
func (*Sandpit) Close ¶
Close closes the connection pool the sessions are taken from. Call it from TestMain after the tests have run, if at all.
func (*Sandpit) Session ¶
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. It is the same as sp.With().Session(t).
func (*Sandpit) With ¶ added in v0.3.0
func (sp *Sandpit) With() *SessionBuilder
With starts building a Session with options. The Sandpit itself is not changed.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is one PostgreSQL connection with one transaction open on it. Every *sql.DB made from a Session runs on that connection, so they all see each other's changes. Only one statement, or one application transaction, runs on the session at a time; the others wait. With SessionBuilder.Interleave, statements and transactions do not wait for an open application transaction: they run, or nest, inside it (see there).
func (*Session) DB ¶
DB returns a *sql.DB that runs on the session. It is the same as s.With().DB().
func (*Session) TxResults ¶ added in v0.4.0
TxResults returns how the application transactions of every *sql.DB of the session ended, in the order they ended. A transaction that is still open is not included. It does not wait for the session, so it can be called while a transaction is open.
database/sql rolls back a transaction whose context was canceled in another goroutine, so its result may appear shortly after the cancellation.
type SessionBuilder ¶ added in v0.3.0
type SessionBuilder struct {
// contains filtered or unexported fields
}
SessionBuilder builds a Session for a Sandpit. Each method returns a new SessionBuilder, so a SessionBuilder can be shared and branched, and made before the tests run:
var base = sandpit.With().Timeout(5 * time.Second)
func TestFoo(t *testing.T) {
s := base.Session(t)
// ...
}
func (*SessionBuilder) Cache ¶ added in v0.5.0
func (b *SessionBuilder) Cache() *SessionBuilder
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 (*SessionBuilder) Conn ¶ added in v0.3.0
func (b *SessionBuilder) Conn(f func(t *testing.T, c *pgx.Conn)) *SessionBuilder
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 (*SessionBuilder) Connector ¶ added in v0.3.0
func (b *SessionBuilder) Connector(f func(driver.Connector) driver.Connector) *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 (*SessionBuilder) Interleave ¶ added in v0.6.0
func (b *SessionBuilder) Interleave() *SessionBuilder
Interleave lets a statement run outside an application transaction while that transaction is open, instead of waiting for it to end. The statement runs at once, inside the open transaction, in a savepoint of its own: it sees what the transaction wrote, a failure fails only that statement, and what it writes is rolled back with the transaction if the transaction rolls back.
It is for code that begins a transaction on a *sql.DB and then, before the transaction ends, uses the *sql.DB outside the transaction, which runs on another connection outside a test. Without Interleave, such a statement waits for the transaction, which waits for the statement, until ErrTimeout.
A transaction begun while another is open does not wait for it either: it nests inside it, in a savepoint inside the open transaction's savepoint. Nested transactions must end in the reverse order they began. If one ends before a transaction begun after it, PostgreSQL ends the later one with it: a Commit of the earlier one rolls both back and returns an error wrapping ErrTxOrder, and the later one's Commit or Rollback returns such an error.
Statements still run one at a time. A statement or a transaction in another goroutine also runs inside an open transaction instead of waiting for it, so transactions that overlap in different goroutines can end out of order.
func (*SessionBuilder) ReadOnly ¶ added in v0.3.0
func (b *SessionBuilder) ReadOnly() *SessionBuilder
ReadOnly makes every *sql.DB of the session reject writes, as DBBuilder.ReadOnly does. A function set with Conn is not affected by it, so it can insert the data the test reads.
func (*SessionBuilder) Session ¶ added in v0.3.0
func (b *SessionBuilder) Session(t *testing.T) *Session
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. With Cache, it returns the session cached for t if there is one.
func (*SessionBuilder) Timeout ¶ added in v0.3.0
func (b *SessionBuilder) Timeout(d time.Duration) *SessionBuilder
Timeout sets how long a call waits for the session while another transaction holds it. It is the default of DBBuilder.Timeout for the *sql.DB values of the session, and also bounds how long the end of the test waits for the session. The default is DefaultTimeout.
type TxResult ¶ added in v0.4.0
type TxResult int
TxResult is how an application transaction ended.
const ( // TxCommitted means Commit succeeded. TxCommitted TxResult = iota // TxRolledBack means the transaction ended with a rollback: Rollback was // called, or database/sql rolled it back because its context was canceled. TxRolledBack // TxCommitFailed means Commit was called but did not commit, such as when // the transaction had hit an error, which rolls it back and makes Commit // return pgx.ErrTxCommitRollback. TxCommitFailed )