diff --git a/README.md b/README.md index 8fb5c54..928492b 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,23 @@ func TestFoo(t *testing.T) { - `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. +`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: + +```go +s := sandpit.Session(t) + +err := svc.Transfer(ctx, s.DB(), from, to, 100) +require.Error(t, err) + +assert.Equal(t, []pgsandpit.TxResult{pgsandpit.TxRolledBack}, s.TxResults()) +``` + +- `TxCommitted`: `Commit` succeeded. +- `TxRolledBack`: `Rollback` was called, or the transaction's context was canceled. `database/sql` rolls back a canceled transaction in another goroutine, so its result may appear shortly after the cancellation. +- `TxCommitFailed`: `Commit` was called but did not commit, such as when the transaction had hit an error. + +A transaction that is still open is not included. Savepoints the application creates with SQL are not transactions here, so they are not included either. + To configure pgx, pass a `*pgx.ConnConfig` and the options of `stdlib.OpenDB`: ```go diff --git a/conn.go b/conn.go index 9d2ee66..6937ffd 100644 --- a/conn.go +++ b/conn.go @@ -211,7 +211,9 @@ type tx struct { // to the savepoint and returns pgx.ErrTxCommitRollback, as a COMMIT of an // aborted transaction does. func (t *tx) Commit() error { - defer t.finish() + result := TxCommitFailed + defer func() { t.finish(result) }() + ctx := context.Background() _, err := t.c.s.tx.ExecContext(ctx, "RELEASE SAVEPOINT "+t.name) var pgErr *pgconn.PgError @@ -221,17 +223,20 @@ func (t *tx) Commit() error { } return pgx.ErrTxCommitRollback } + if err == nil { + result = TxCommitted + } return err } func (t *tx) Rollback() error { - defer t.finish() + defer t.finish(TxRolledBack) return t.c.s.rollbackTo(context.Background(), t.name) } -func (t *tx) finish() { +func (t *tx) finish(result TxResult) { t.c.tx = nil - t.c.s.setHolder("") + t.c.s.endTx(result) t.release() } diff --git a/session.go b/session.go index c578bcf..2981df7 100644 --- a/session.go +++ b/session.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "runtime/debug" + "slices" "sync" "sync/atomic" "testing" @@ -50,8 +51,52 @@ type Session struct { seq atomic.Uint64 - mu sync.Mutex - holder string // stack of the Begin that holds the session, for ErrTimeout + mu sync.Mutex + holder string // stack of the Begin that holds the session, for ErrTimeout + txResults []TxResult // how the application transactions ended, in order +} + +// TxResult is how an application transaction ended. +type TxResult int + +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 +) + +// String returns the name of the constant, so that a failed assertion on +// TxResults reads well. +func (r TxResult) String() string { + switch r { + case TxCommitted: + return "TxCommitted" + case TxRolledBack: + return "TxRolledBack" + case TxCommitFailed: + return "TxCommitFailed" + default: + return fmt.Sprintf("TxResult(%d)", int(r)) + } +} + +// 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. +func (s *Session) TxResults() []TxResult { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.txResults) } // DB returns a *sql.DB that runs on the session. It is the same as @@ -109,6 +154,14 @@ func (s *Session) setHolder(stack string) { s.mu.Unlock() } +// endTx records how the application transaction that held the session ended. +func (s *Session) endTx(result TxResult) { + s.mu.Lock() + s.holder = "" + s.txResults = append(s.txResults, result) + s.mu.Unlock() +} + func (s *Session) close() { // The *sql.DB cleanups ran first and rolled back any transaction they // still had. A transaction that is still open here was leaked. diff --git a/tx_results_test.go b/tx_results_test.go new file mode 100644 index 0000000..9b81798 --- /dev/null +++ b/tx_results_test.go @@ -0,0 +1,154 @@ +package pgsandpit_test + +import ( + "context" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/winebarrel/pgsandpit" +) + +func TestTxResults(t *testing.T) { + t.Parallel() + + t.Run("empty without a transaction", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + _, err := s.DB().Exec(`SELECT 1`) + require.NoError(t, err) + _, err = s.DB().Exec(`SELECT * FROM no_such_table`) + require.Error(t, err) + + assert.Empty(t, s.TxResults()) + }) + + t.Run("commit", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + tx, err := s.DB().Begin() + require.NoError(t, err) + require.NoError(t, tx.Commit()) + + assert.Equal(t, []pgsandpit.TxResult{pgsandpit.TxCommitted}, s.TxResults()) + }) + + t.Run("rollback", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + tx, err := s.DB().Begin() + require.NoError(t, err) + require.NoError(t, tx.Rollback()) + + assert.Equal(t, []pgsandpit.TxResult{pgsandpit.TxRolledBack}, s.TxResults()) + }) + + t.Run("rollback after commit is not recorded", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + tx, err := s.DB().Begin() + require.NoError(t, err) + require.NoError(t, tx.Commit()) + require.Error(t, tx.Rollback()) + + assert.Equal(t, []pgsandpit.TxResult{pgsandpit.TxCommitted}, s.TxResults()) + }) + + t.Run("commit of an aborted transaction", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + tx, err := s.DB().Begin() + require.NoError(t, err) + _, err = tx.Exec(`SELECT * FROM no_such_table`) + require.Error(t, err) + require.ErrorIs(t, tx.Commit(), pgx.ErrTxCommitRollback) + + assert.Equal(t, []pgsandpit.TxResult{pgsandpit.TxCommitFailed}, s.TxResults()) + }) + + t.Run("canceled context", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + _, err := s.DB().BeginTx(ctx, nil) + require.NoError(t, err) + cancel() + + assert.Eventually(t, func() bool { + return assert.ObjectsAreEqual([]pgsandpit.TxResult{pgsandpit.TxRolledBack}, s.TxResults()) + }, 5*time.Second, 10*time.Millisecond) + }) + + t.Run("in order across every *sql.DB of the session", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + db := s.DB() + ro := s.With().ReadOnly().DB() + + tx, err := db.Begin() + require.NoError(t, err) + require.NoError(t, tx.Commit()) + tx, err = ro.Begin() + require.NoError(t, err) + require.NoError(t, tx.Rollback()) + tx, err = db.Begin() + require.NoError(t, err) + require.NoError(t, tx.Commit()) + + assert.Equal(t, []pgsandpit.TxResult{ + pgsandpit.TxCommitted, + pgsandpit.TxRolledBack, + pgsandpit.TxCommitted, + }, s.TxResults()) + }) + + t.Run("does not wait for an open transaction, which is not included", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + tx, err := s.DB().Begin() + require.NoError(t, err) + defer tx.Rollback() + + assert.Empty(t, s.TxResults()) + }) + + t.Run("returns a copy", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + tx, err := s.DB().Begin() + require.NoError(t, err) + require.NoError(t, tx.Commit()) + + s.TxResults()[0] = pgsandpit.TxRolledBack + + assert.Equal(t, []pgsandpit.TxResult{pgsandpit.TxCommitted}, s.TxResults()) + }) + + t.Run("sessions do not share results", func(t *testing.T) { + t.Parallel() + s := sandpit.Session(t) + other := sandpit.Session(t) + tx, err := s.DB().Begin() + require.NoError(t, err) + require.NoError(t, tx.Commit()) + + assert.Empty(t, other.TxResults()) + }) +} + +func TestTxResultString(t *testing.T) { + t.Parallel() + + tests := map[pgsandpit.TxResult]string{ + pgsandpit.TxCommitted: "TxCommitted", + pgsandpit.TxRolledBack: "TxRolledBack", + pgsandpit.TxCommitFailed: "TxCommitFailed", + pgsandpit.TxResult(99): "TxResult(99)", + } + for r, want := range tests { + assert.Equal(t, want, r.String()) + } +}