dbmock

package
v4.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2026 License: GPL-3.0 Imports: 6 Imported by: 0

README

dbmock

dbmock is an internal, expectation-based SQL mock package for deterministic backend tests.

What It Supports

  1. Ordered expectations by default
  2. Optional unordered matching via WithUnorderedExpectations()
  3. Exec, Query, and Prepare statement flows
  4. Transaction lifecycle (Begin, Commit, Rollback) with state guards
  5. Argument matchers:
    • Eq(value)
    • AnyArg()
    • TypeOf(sample)
    • Predicate(name, fn)

Basic Usage

mock := dbmock.New()
conn := mock.Conn()

mock.ExpectExec("UPDATE users SET enabled = ? WHERE id = ?", true, "u-1").
    WillReturnResult(1, 0)

result, err := conn.Exec("UPDATE users SET enabled = ? WHERE id = ?", true, "u-1")
if err != nil {
    t.Fatal(err)
}
if result.RowsAffected != 1 {
    t.Fatalf("unexpected rows affected: %d", result.RowsAffected)
}

if err = mock.ExpectationsWereMet(); err != nil {
    t.Fatal(err)
}

Prepared Statement Pattern

mock.ExpectPrepare("SELECT id FROM users WHERE id = ?").
    ExpectQuery("u-1").
    WillReturnRows(dbmock.NewRows("id").AddRow("u-1"))

stmt, err := conn.Prepare("SELECT id FROM users WHERE id = ?")
if err != nil {
    t.Fatal(err)
}
defer stmt.Close()

rows, err := stmt.Query("u-1")
if err != nil {
    t.Fatal(err)
}

Transaction Pattern

mock.ExpectBegin()
mock.ExpectExec("UPDATE users SET enabled = ? WHERE id = ?", true, "u-1").WillReturnResult(1, 0)
mock.ExpectCommit()

tx, err := conn.Begin()
if err != nil {
    t.Fatal(err)
}

if _, err = tx.Exec("UPDATE users SET enabled = ? WHERE id = ?", true, "u-1"); err != nil {
    t.Fatal(err)
}
if err = tx.Commit(); err != nil {
    t.Fatal(err)
}

Anti-Patterns

  1. Do not rely on SQL parser semantics. dbmock is expectation-based, not a SQL engine.
  2. Do not skip ExpectationsWereMet(). You lose missing-call diagnostics.
  3. Do not share one Mock instance across unrelated tests.
  4. Do not overuse AnyArg() if argument correctness matters.
  5. Do not enable unordered mode unless call order is intentionally irrelevant.

Documentation

Overview

Package dbmock provides dbmock functionality.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnexpectedCall is an exported package value.
	ErrUnexpectedCall = errors.New("unexpected call")
	// ErrKindMismatch is an exported package value.
	ErrKindMismatch = errors.New("call kind mismatch")
	// ErrPreparedModeMismatch reports an unexpected prepared statement mode.
	ErrPreparedModeMismatch = errors.New("prepared mode mismatch")
	// ErrSQLMismatch reports an unexpected SQL statement.
	ErrSQLMismatch = errors.New("sql mismatch")
	// ErrArgCountMismatch reports an unexpected argument count.
	ErrArgCountMismatch = errors.New("argument count mismatch")
	// ErrArgMismatch reports an unexpected argument value.
	ErrArgMismatch = errors.New("argument mismatch")
	// ErrPlaceholderCountMismatch reports a placeholder and argument count mismatch.
	ErrPlaceholderCountMismatch = errors.New("placeholder count mismatch")
	// ErrExpectationAlreadyConsumed reports a reused expectation.
	ErrExpectationAlreadyConsumed = errors.New("expectation already consumed")
	// ErrEmptyExpectationQueue reports that no expectation is available.
	ErrEmptyExpectationQueue = errors.New("expectation queue is empty")
	// ErrStatementClosed reports use of a closed statement.
	ErrStatementClosed = errors.New("statement is closed")
	// ErrTransactionDone reports use of an already finalized transaction.
	ErrTransactionDone = errors.New("transaction is already finalized")
)

Functions

This section is empty.

Types

type ArgMatcher

type ArgMatcher interface {
	Match(value any) bool
	Describe() string
}

ArgMatcher defines argument matching behavior for expectations.

func AnyArg

func AnyArg() ArgMatcher

AnyArg matches any value at the corresponding argument position.

func Eq

func Eq(expected any) ArgMatcher

Eq matches exactly one expected value.

func Predicate

func Predicate(name string, predicate func(any) bool) ArgMatcher

Predicate matches arguments for which predicate(value) returns true.

func TypeOf

func TypeOf(sample any) ArgMatcher

TypeOf matches arguments of the same dynamic type as sample.

type Call

type Call struct {
	Kind      CallKind
	Prepared  bool
	Query     string
	Args      []any
	Timestamp time.Time
}

Call is a normalized representation of an intercepted DB operation.

func NewCall

func NewCall(kind CallKind, query string, args ...any) Call

NewCall builds a Call with copied args and an initialized timestamp.

func NewPreparedCall

func NewPreparedCall(kind CallKind, query string, args ...any) Call

NewPreparedCall builds a Call for a prepared statement operation.

type CallKind

type CallKind string

CallKind identifies the database operation class.

const (
	// CallExec is an exported package constant.
	CallExec CallKind = "exec"
	// CallQuery is an exported package constant.
	CallQuery = "query"
	// CallPrepare identifies a prepared statement operation.
	CallPrepare CallKind = "prepare"
	// CallBegin identifies a transaction begin operation.
	CallBegin CallKind = "begin"
	// CallCommit identifies a transaction commit operation.
	CallCommit CallKind = "commit"
	// CallRollback identifies a transaction rollback operation.
	CallRollback CallKind = "rollback"
)

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn executes DB operations against mock expectations.

func (*Conn) Begin

func (c *Conn) Begin() (*Tx, error)

Begin matches the next begin expectation and returns a transaction handle.

func (*Conn) Exec

func (c *Conn) Exec(query string, args ...any) (ExecResult, error)

Exec matches and executes the next expected exec call.

func (*Conn) Prepare

func (c *Conn) Prepare(query string, args ...any) (*Stmt, error)

Prepare matches the next prepare expectation and returns a statement handle.

func (*Conn) Query

func (c *Conn) Query(query string, args ...any) (Rows, error)

Query matches and executes the next expected query call.

type ExecExpectation

type ExecExpectation struct {
	// contains filtered or unexported fields
}

ExecExpectation matches an exec call.

func NewExecExpectation

func NewExecExpectation(query string, args ...any) *ExecExpectation

NewExecExpectation creates an exec expectation.

func (*ExecExpectation) Consume

func (b *ExecExpectation) Consume() error

func (*ExecExpectation) DescribeMismatch

func (b *ExecExpectation) DescribeMismatch(call Call) string

func (*ExecExpectation) IsSatisfied

func (b *ExecExpectation) IsSatisfied() bool

func (*ExecExpectation) Kind

func (b *ExecExpectation) Kind() CallKind

func (*ExecExpectation) Match

func (b *ExecExpectation) Match(call Call) error

func (*ExecExpectation) WillReturnError

func (e *ExecExpectation) WillReturnError(err error) *ExecExpectation

WillReturnError configures the error returned by a matched exec call.

func (*ExecExpectation) WillReturnResult

func (e *ExecExpectation) WillReturnResult(rowsAffected, lastInsertID int64) *ExecExpectation

WillReturnResult configures the result returned by a matched exec call.

type ExecResult

type ExecResult struct {
	RowsAffected int64
	LastInsertID int64
}

ExecResult represents an exec operation result.

type Expectation

type Expectation interface {
	Kind() CallKind
	Match(call Call) error
	Consume() error
	IsSatisfied() bool
	DescribeMismatch(call Call) string
}

Expectation defines matching and lifecycle behavior for one expected DB call.

type ExpectationQueue

type ExpectationQueue struct {
	// contains filtered or unexported fields
}

ExpectationQueue provides synchronized expectation ordering and consumption.

func NewExpectationQueue

func NewExpectationQueue() *ExpectationQueue

NewExpectationQueue creates an empty expectation queue.

func NewExpectationQueueWithOrdering

func NewExpectationQueueWithOrdering(ordered bool) *ExpectationQueue

NewExpectationQueueWithOrdering creates an empty expectation queue with configured ordering mode.

func (*ExpectationQueue) Dequeue

func (q *ExpectationQueue) Dequeue() (Expectation, error)

Dequeue removes and returns the first expectation.

func (*ExpectationQueue) Enqueue

func (q *ExpectationQueue) Enqueue(exp Expectation)

Enqueue appends an expectation at the tail.

func (*ExpectationQueue) Len

func (q *ExpectationQueue) Len() int

Len returns the number of queued expectations.

func (*ExpectationQueue) MatchNext

func (q *ExpectationQueue) MatchNext(call Call) (Expectation, error)

MatchNext validates and consumes the next expected call.

func (*ExpectationQueue) Peek

func (q *ExpectationQueue) Peek() (Expectation, error)

Peek returns the first expectation without consuming it.

func (*ExpectationQueue) Snapshot

func (q *ExpectationQueue) Snapshot() []Expectation

Snapshot returns a shallow copy of currently queued expectations.

type Mock

type Mock struct {
	// contains filtered or unexported fields
}

Mock coordinates expectations and captured calls.

func New

func New(opts ...Option) *Mock

New creates a fresh mock instance.

func (*Mock) Calls

func (m *Mock) Calls() []Call

Calls returns a copied history of successfully matched calls.

func (*Mock) Conn

func (m *Mock) Conn() *Conn

Conn returns a connection handle bound to the mock.

func (*Mock) ExpectBegin

func (m *Mock) ExpectBegin() *TxExpectation

ExpectBegin appends a begin expectation.

func (*Mock) ExpectCommit

func (m *Mock) ExpectCommit() *TxExpectation

ExpectCommit appends a commit expectation.

func (*Mock) ExpectExec

func (m *Mock) ExpectExec(query string, args ...any) *ExecExpectation

ExpectExec appends an exec expectation.

func (*Mock) ExpectPrepare

func (m *Mock) ExpectPrepare(query string, args ...any) *PrepareExpectation

ExpectPrepare appends a prepare expectation.

func (*Mock) ExpectQuery

func (m *Mock) ExpectQuery(query string, args ...any) *QueryExpectation

ExpectQuery appends a query expectation.

func (*Mock) ExpectRollback

func (m *Mock) ExpectRollback() *TxExpectation

ExpectRollback appends a rollback expectation.

func (*Mock) ExpectationsWereMet

func (m *Mock) ExpectationsWereMet() error

ExpectationsWereMet fails if queued expectations remain unmatched.

type Option

type Option func(*options)

Option configures mock behavior.

func WithUnorderedExpectations

func WithUnorderedExpectations() Option

WithUnorderedExpectations enables matching calls in any order.

type PrepareExpectation

type PrepareExpectation struct {
	// contains filtered or unexported fields
}

PrepareExpectation matches a prepare call.

func NewPrepareExpectation

func NewPrepareExpectation(query string, args ...any) *PrepareExpectation

NewPrepareExpectation creates a prepare expectation.

func (*PrepareExpectation) Consume

func (b *PrepareExpectation) Consume() error

func (*PrepareExpectation) DescribeMismatch

func (b *PrepareExpectation) DescribeMismatch(call Call) string

func (*PrepareExpectation) ExpectExec

func (e *PrepareExpectation) ExpectExec(args ...any) *ExecExpectation

ExpectExec chains an expected prepared statement exec call.

func (*PrepareExpectation) ExpectQuery

func (e *PrepareExpectation) ExpectQuery(args ...any) *QueryExpectation

ExpectQuery chains an expected prepared statement query call.

func (*PrepareExpectation) IsSatisfied

func (b *PrepareExpectation) IsSatisfied() bool

func (*PrepareExpectation) Kind

func (b *PrepareExpectation) Kind() CallKind

func (*PrepareExpectation) Match

func (b *PrepareExpectation) Match(call Call) error

func (*PrepareExpectation) ValidatePlaceholderCount

func (e *PrepareExpectation) ValidatePlaceholderCount() *PrepareExpectation

ValidatePlaceholderCount enables placeholder-count checks for prepared stmt exec/query calls.

func (*PrepareExpectation) WillReturnError

func (e *PrepareExpectation) WillReturnError(err error) *PrepareExpectation

WillReturnError configures the error returned by a matched prepare call.

type QueryExpectation

type QueryExpectation struct {
	// contains filtered or unexported fields
}

QueryExpectation matches a query call.

func NewQueryExpectation

func NewQueryExpectation(query string, args ...any) *QueryExpectation

NewQueryExpectation creates a query expectation.

func (*QueryExpectation) Consume

func (b *QueryExpectation) Consume() error

func (*QueryExpectation) DescribeMismatch

func (b *QueryExpectation) DescribeMismatch(call Call) string

func (*QueryExpectation) IsSatisfied

func (b *QueryExpectation) IsSatisfied() bool

func (*QueryExpectation) Kind

func (b *QueryExpectation) Kind() CallKind

func (*QueryExpectation) Match

func (b *QueryExpectation) Match(call Call) error

func (*QueryExpectation) WillReturnError

func (e *QueryExpectation) WillReturnError(err error) *QueryExpectation

WillReturnError configures the error returned by a matched query call.

func (*QueryExpectation) WillReturnRows

func (e *QueryExpectation) WillReturnRows(rows Rows) *QueryExpectation

WillReturnRows configures rows returned by a matched query call.

type Rows

type Rows struct {
	Columns []string
	Data    [][]any
}

Rows is a simple query result container for tests.

func NewRows

func NewRows(columns ...string) Rows

NewRows initializes rows with a fixed column list.

func (Rows) AddRow

func (r Rows) AddRow(values ...any) Rows

AddRow appends a row and returns the updated Rows value.

func (Rows) Clone

func (r Rows) Clone() Rows

Clone returns a deep copy safe for test assertions.

type Stmt

type Stmt struct {
	// contains filtered or unexported fields
}

Stmt executes prepared statement operations against mock expectations.

func (*Stmt) Close

func (s *Stmt) Close()

Close marks the statement as unusable.

func (*Stmt) Exec

func (s *Stmt) Exec(args ...any) (ExecResult, error)

Exec matches and executes a prepared statement exec call.

func (*Stmt) Query

func (s *Stmt) Query(args ...any) (Rows, error)

Query matches and executes a prepared statement query call.

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Tx executes transaction lifecycle operations against mock expectations.

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit matches and executes a commit call for the active transaction.

func (*Tx) Exec

func (tx *Tx) Exec(query string, args ...any) (ExecResult, error)

Exec matches and executes an exec call inside the active transaction.

func (*Tx) Query

func (tx *Tx) Query(query string, args ...any) (Rows, error)

Query matches and executes a query call inside the active transaction.

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback matches and executes a rollback call for the active transaction.

type TxExpectation

type TxExpectation struct {
	// contains filtered or unexported fields
}

TxExpectation matches a transaction lifecycle call.

func NewTxExpectation

func NewTxExpectation(kind CallKind) *TxExpectation

NewTxExpectation creates a transaction expectation (begin, commit, rollback).

func (*TxExpectation) Consume

func (b *TxExpectation) Consume() error

func (*TxExpectation) DescribeMismatch

func (b *TxExpectation) DescribeMismatch(call Call) string

func (*TxExpectation) IsSatisfied

func (b *TxExpectation) IsSatisfied() bool

func (*TxExpectation) Kind

func (b *TxExpectation) Kind() CallKind

func (*TxExpectation) Match

func (b *TxExpectation) Match(call Call) error

func (*TxExpectation) WillReturnError

func (e *TxExpectation) WillReturnError(err error) *TxExpectation

WillReturnError configures the error returned by a matched tx call.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL