go-sqlmock: github.com/DATA-DOG/go-sqlmock Index | Examples | Files | Directories

package sqlmock

import "github.com/DATA-DOG/go-sqlmock"

Package sqlmock is a mock library implementing sql driver. Which has one and only purpose - to simulate any sql driver behavior in tests, without needing a real database connection. It helps to maintain correct **TDD** workflow.

It does not require any modifications to your source code in order to test and mock database operations. Supports concurrency and multiple database mocking.

The driver allows to mock any sql driver method behavior.

Code:

// Open new mock database
db, mock, err := New()
if err != nil {
    fmt.Println("error creating mock database")
    return
}
// columns to be used for result
columns := []string{"id", "status"}
// expect transaction begin
mock.ExpectBegin()
// expect query to fetch order, match it with regexp
mock.ExpectQuery("SELECT (.+) FROM orders (.+) FOR UPDATE").
    WithArgs(1).
    WillReturnRows(NewRows(columns).AddRow(1, 1))
// expect transaction rollback, since order status is "cancelled"
mock.ExpectRollback()

// run the cancel order function
someOrderID := 1
// call a function which executes expected database operations
err = cancelOrder(db, someOrderID)
if err != nil {
    fmt.Printf("unexpected error: %s", err)
    return
}

// ensure all expectations have been met
if err = mock.ExpectationsWereMet(); err != nil {
    fmt.Printf("unmet expectation error: %s", err)
}

Index

Examples

Package Files

argument.go driver.go expectations.go expectations_go18.go options.go result.go rows.go rows_go18.go sqlmock.go sqlmock_go18.go statement.go util.go

Variables

var CSVColumnParser = func(s string) []byte {
    switch {
    case strings.ToLower(s) == "null":
        return nil
    }
    return []byte(s)
}

CSVColumnParser is a function which converts trimmed csv column string to a []byte representation. currently transforms NULL to nil

var ErrCancelled = errors.New("canceling query due to user request")

func NewErrorResult Uses

func NewErrorResult(err error) driver.Result

NewErrorResult creates a new sql driver Result which returns an error given for both interface methods

Code:

db, mock, _ := New()
result := NewErrorResult(fmt.Errorf("some error"))
mock.ExpectExec("^INSERT (.+)").WillReturnResult(result)
res, _ := db.Exec("INSERT something")
_, err := res.LastInsertId()
fmt.Println(err)

Output:

some error

func NewResult Uses

func NewResult(lastInsertID int64, rowsAffected int64) driver.Result

NewResult creates a new sql driver Result for Exec based query mocks.

Code:

var lastInsertID, affected int64
result := NewResult(lastInsertID, affected)
mock.ExpectExec("^INSERT (.+)").WillReturnResult(result)
fmt.Println(mock.ExpectationsWereMet())

Output:

there is a remaining expectation which was not matched: ExpectedExec => expecting Exec or ExecContext which:
  - matches sql: '^INSERT (.+)'
  - is without arguments
  - should return Result having:
      LastInsertId: 0
      RowsAffected: 0

func ValueConverterOption Uses

func ValueConverterOption(converter driver.ValueConverter) func(*sqlmock) error

ValueConverterOption allows to create a sqlmock connection with a custom ValueConverter to support drivers with special data types.

type Argument Uses

type Argument interface {
    Match(driver.Value) bool
}

Argument interface allows to match any argument in specific way when used with ExpectedQuery and ExpectedExec expectations.

func AnyArg Uses

func AnyArg() Argument

AnyArg will return an Argument which can match any kind of arguments.

Useful for time.Time or similar kinds of arguments.

type ExpectedBegin Uses

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

ExpectedBegin is used to manage *sql.DB.Begin expectation returned by *Sqlmock.ExpectBegin.

func (*ExpectedBegin) String Uses

func (e *ExpectedBegin) String() string

String returns string representation

func (*ExpectedBegin) WillDelayFor Uses

func (e *ExpectedBegin) WillDelayFor(duration time.Duration) *ExpectedBegin

WillDelayFor allows to specify duration for which it will delay result. May be used together with Context

func (*ExpectedBegin) WillReturnError Uses

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

WillReturnError allows to set an error for *sql.DB.Begin action

type ExpectedClose Uses

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

ExpectedClose is used to manage *sql.DB.Close expectation returned by *Sqlmock.ExpectClose.

func (*ExpectedClose) String Uses

func (e *ExpectedClose) String() string

String returns string representation

func (*ExpectedClose) WillReturnError Uses

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

WillReturnError allows to set an error for *sql.DB.Close action

type ExpectedCommit Uses

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

ExpectedCommit is used to manage *sql.Tx.Commit expectation returned by *Sqlmock.ExpectCommit.

func (*ExpectedCommit) String Uses

func (e *ExpectedCommit) String() string

String returns string representation

func (*ExpectedCommit) WillReturnError Uses

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

WillReturnError allows to set an error for *sql.Tx.Close action

type ExpectedExec Uses

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

ExpectedExec is used to manage *sql.DB.Exec, *sql.Tx.Exec or *sql.Stmt.Exec expectations. Returned by *Sqlmock.ExpectExec.

Code:

db, mock, _ := New()
result := NewErrorResult(fmt.Errorf("some error"))
mock.ExpectExec("^INSERT (.+)").WillReturnResult(result)
res, _ := db.Exec("INSERT something")
_, err := res.LastInsertId()
fmt.Println(err)

Output:

some error

func (*ExpectedExec) String Uses

func (e *ExpectedExec) String() string

String returns string representation

func (*ExpectedExec) WillDelayFor Uses

func (e *ExpectedExec) WillDelayFor(duration time.Duration) *ExpectedExec

WillDelayFor allows to specify duration for which it will delay result. May be used together with Context

func (*ExpectedExec) WillReturnError Uses

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

WillReturnError allows to set an error for expected database exec action

func (*ExpectedExec) WillReturnResult Uses

func (e *ExpectedExec) WillReturnResult(result driver.Result) *ExpectedExec

WillReturnResult arranges for an expected Exec() to return a particular result, there is sqlmock.NewResult(lastInsertID int64, affectedRows int64) method to build a corresponding result. Or if actions needs to be tested against errors sqlmock.NewErrorResult(err error) to return a given error.

func (*ExpectedExec) WithArgs Uses

func (e *ExpectedExec) WithArgs(args ...driver.Value) *ExpectedExec

WithArgs will match given expected args to actual database exec operation arguments. if at least one argument does not match, it will return an error. For specific arguments an sqlmock.Argument interface can be used to match an argument.

type ExpectedPrepare Uses

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

ExpectedPrepare is used to manage *sql.DB.Prepare or *sql.Tx.Prepare expectations. Returned by *Sqlmock.ExpectPrepare.

func (*ExpectedPrepare) ExpectExec Uses

func (e *ExpectedPrepare) ExpectExec() *ExpectedExec

ExpectExec allows to expect Exec() on this prepared statement. this method is convenient in order to prevent duplicating sql query string matching.

func (*ExpectedPrepare) ExpectQuery Uses

func (e *ExpectedPrepare) ExpectQuery() *ExpectedQuery

ExpectQuery allows to expect Query() or QueryRow() on this prepared statement. this method is convenient in order to prevent duplicating sql query string matching.

func (*ExpectedPrepare) String Uses

func (e *ExpectedPrepare) String() string

String returns string representation

func (*ExpectedPrepare) WillBeClosed Uses

func (e *ExpectedPrepare) WillBeClosed() *ExpectedPrepare

WillBeClosed expects this prepared statement to be closed.

func (*ExpectedPrepare) WillDelayFor Uses

func (e *ExpectedPrepare) WillDelayFor(duration time.Duration) *ExpectedPrepare

WillDelayFor allows to specify duration for which it will delay result. May be used together with Context

func (*ExpectedPrepare) WillReturnCloseError Uses

func (e *ExpectedPrepare) WillReturnCloseError(err error) *ExpectedPrepare

WillReturnCloseError allows to set an error for this prepared statement Close action

func (*ExpectedPrepare) WillReturnError Uses

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

WillReturnError allows to set an error for the expected *sql.DB.Prepare or *sql.Tx.Prepare action.

type ExpectedQuery Uses

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

ExpectedQuery is used to manage *sql.DB.Query, *dql.DB.QueryRow, *sql.Tx.Query, *sql.Tx.QueryRow, *sql.Stmt.Query or *sql.Stmt.QueryRow expectations. Returned by *Sqlmock.ExpectQuery.

func (*ExpectedQuery) String Uses

func (e *ExpectedQuery) String() string

String returns string representation

func (*ExpectedQuery) WillDelayFor Uses

func (e *ExpectedQuery) WillDelayFor(duration time.Duration) *ExpectedQuery

WillDelayFor allows to specify duration for which it will delay result. May be used together with Context

func (*ExpectedQuery) WillReturnError Uses

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

WillReturnError allows to set an error for expected database query

func (*ExpectedQuery) WillReturnRows Uses

func (e *ExpectedQuery) WillReturnRows(rows ...*Rows) *ExpectedQuery

WillReturnRows specifies the set of resulting rows that will be returned by the triggered query

func (*ExpectedQuery) WithArgs Uses

func (e *ExpectedQuery) WithArgs(args ...driver.Value) *ExpectedQuery

WithArgs will match given expected args to actual database query arguments. if at least one argument does not match, it will return an error. For specific arguments an sqlmock.Argument interface can be used to match an argument.

type ExpectedRollback Uses

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

ExpectedRollback is used to manage *sql.Tx.Rollback expectation returned by *Sqlmock.ExpectRollback.

func (*ExpectedRollback) String Uses

func (e *ExpectedRollback) String() string

String returns string representation

func (*ExpectedRollback) WillReturnError Uses

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

WillReturnError allows to set an error for *sql.Tx.Rollback action

type Rows Uses

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

Rows is a mocked collection of rows to return for Query result

Code:

db, mock, err := New()
if err != nil {
    fmt.Println("failed to open sqlmock database:", err)
}
defer db.Close()

rows := NewRows([]string{"id", "title"}).
    AddRow(1, "one").
    AddRow(2, "two")

mock.ExpectQuery("SELECT").WillReturnRows(rows)

rs, _ := db.Query("SELECT")
defer rs.Close()

for rs.Next() {
    var id int
    var title string
    rs.Scan(&id, &title)
    fmt.Println("scanned id:", id, "and title:", title)
}

if rs.Err() != nil {
    fmt.Println("got rows error:", rs.Err())
}

Output:

scanned id: 1 and title: one
scanned id: 2 and title: two

Code:

db, mock, err := New()
if err != nil {
    fmt.Println("failed to open sqlmock database:", err)
}
defer db.Close()

rows := NewRows([]string{"id", "title"}).CloseError(fmt.Errorf("close error"))
mock.ExpectQuery("SELECT").WillReturnRows(rows)

rs, _ := db.Query("SELECT")

// Note: that close will return error only before rows EOF
// that is a default sql package behavior. If you run rs.Next()
// it will handle the error internally and return nil bellow
if err := rs.Close(); err != nil {
    fmt.Println("got error:", err)
}

Output:

got error: close error

Code:

db, mock, err := New()
if err != nil {
    fmt.Println("failed to open sqlmock database:", err)
}
defer db.Close()

rows := NewRows([]string{"id", "null_int"}).
    AddRow(1, 7).
    AddRow(5, sql.NullInt64{Int64: 5, Valid: true}).
    AddRow(2, sql.NullInt64{})

mock.ExpectQuery("SELECT").WillReturnRows(rows)

rs, _ := db.Query("SELECT")
defer rs.Close()

for rs.Next() {
    var id int
    var num sql.NullInt64
    rs.Scan(&id, &num)
    fmt.Println("scanned id:", id, "and null int64:", num)
}

if rs.Err() != nil {
    fmt.Println("got rows error:", rs.Err())
}

Output:

scanned id: 1 and null int64: {7 true}
scanned id: 5 and null int64: {5 true}
scanned id: 2 and null int64: {0 false}

Code:

db, mock, err := New()
if err != nil {
    fmt.Println("failed to open sqlmock database:", err)
}
defer db.Close()

rows := NewRows([]string{"id", "title"}).
    AddRow(0, "one").
    AddRow(1, "two").
    RowError(1, fmt.Errorf("row error"))
mock.ExpectQuery("SELECT").WillReturnRows(rows)

rs, _ := db.Query("SELECT")
defer rs.Close()

for rs.Next() {
    var id int
    var title string
    rs.Scan(&id, &title)
    fmt.Println("scanned id:", id, "and title:", title)
}

if rs.Err() != nil {
    fmt.Println("got rows error:", rs.Err())
}

Output:

scanned id: 0 and title: one
got rows error: row error

func NewRows Uses

func NewRows(columns []string) *Rows

NewRows allows Rows to be created from a sql driver.Value slice or from the CSV string and to be used as sql driver.Rows. Use Sqlmock.NewRows instead if using a custom converter

func (*Rows) AddRow Uses

func (r *Rows) AddRow(values ...driver.Value) *Rows

AddRow composed from database driver.Value slice return the same instance to perform subsequent actions. Note that the number of values must match the number of columns

func (*Rows) CloseError Uses

func (r *Rows) CloseError(err error) *Rows

CloseError allows to set an error which will be returned by rows.Close function.

The close error will be triggered only in cases when rows.Next() EOF was not yet reached, that is a default sql library behavior

func (*Rows) FromCSVString Uses

func (r *Rows) FromCSVString(s string) *Rows

FromCSVString build rows from csv string. return the same instance to perform subsequent actions. Note that the number of values must match the number of columns

func (*Rows) RowError Uses

func (r *Rows) RowError(row int, err error) *Rows

RowError allows to set an error which will be returned when a given row number is read

type Sqlmock Uses

type Sqlmock interface {

    // ExpectClose queues an expectation for this database
    // action to be triggered. the *ExpectedClose allows
    // to mock database response
    ExpectClose() *ExpectedClose

    // ExpectationsWereMet checks whether all queued expectations
    // were met in order. If any of them was not met - an error is returned.
    ExpectationsWereMet() error

    // ExpectPrepare expects Prepare() to be called with sql query
    // which match sqlRegexStr given regexp.
    // the *ExpectedPrepare allows to mock database response.
    // Note that you may expect Query() or Exec() on the *ExpectedPrepare
    // statement to prevent repeating sqlRegexStr
    ExpectPrepare(sqlRegexStr string) *ExpectedPrepare

    // ExpectQuery expects Query() or QueryRow() to be called with sql query
    // which match sqlRegexStr given regexp.
    // the *ExpectedQuery allows to mock database response.
    ExpectQuery(sqlRegexStr string) *ExpectedQuery

    // ExpectExec expects Exec() to be called with sql query
    // which match sqlRegexStr given regexp.
    // the *ExpectedExec allows to mock database response
    ExpectExec(sqlRegexStr string) *ExpectedExec

    // ExpectBegin expects *sql.DB.Begin to be called.
    // the *ExpectedBegin allows to mock database response
    ExpectBegin() *ExpectedBegin

    // ExpectCommit expects *sql.Tx.Commit to be called.
    // the *ExpectedCommit allows to mock database response
    ExpectCommit() *ExpectedCommit

    // ExpectRollback expects *sql.Tx.Rollback to be called.
    // the *ExpectedRollback allows to mock database response
    ExpectRollback() *ExpectedRollback

    // MatchExpectationsInOrder gives an option whether to match all
    // expectations in the order they were set or not.
    //
    // By default it is set to - true. But if you use goroutines
    // to parallelize your query executation, that option may
    // be handy.
    //
    // This option may be turned on anytime during tests. As soon
    // as it is switched to false, expectations will be matched
    // in any order. Or otherwise if switched to true, any unmatched
    // expectations will be expected in order
    MatchExpectationsInOrder(bool)

    // NewRows allows Rows to be created from a
    // sql driver.Value slice or from the CSV string and
    // to be used as sql driver.Rows.
    NewRows(columns []string) *Rows
}

Sqlmock interface serves to create expectations for any kind of database action in order to mock and test real database behavior.

Code:

db, mock, err := New()
if err != nil {
    fmt.Println("failed to open sqlmock database:", err)
}
defer db.Close()

// note this line is important for unordered expectation matching
mock.MatchExpectationsInOrder(false)

result := NewResult(1, 1)

mock.ExpectExec("^UPDATE one").WithArgs("one").WillReturnResult(result)
mock.ExpectExec("^UPDATE two").WithArgs("one", "two").WillReturnResult(result)
mock.ExpectExec("^UPDATE three").WithArgs("one", "two", "three").WillReturnResult(result)

var wg sync.WaitGroup
queries := map[string][]interface{}{
    "one":   {"one"},
    "two":   {"one", "two"},
    "three": {"one", "two", "three"},
}

wg.Add(len(queries))
for table, args := range queries {
    go func(tbl string, a []interface{}) {
        if _, err := db.Exec("UPDATE "+tbl, a...); err != nil {
            fmt.Println("error was not expected:", err)
        }
        wg.Done()
    }(table, args)
}

wg.Wait()

if err := mock.ExpectationsWereMet(); err != nil {
    fmt.Println("there were unfulfilled expectations:", err)
}

func New Uses

func New(options ...func(*sqlmock) error) (*sql.DB, Sqlmock, error)

New creates sqlmock database connection and a mock to manage expectations. Accepts options, like ValueConverterOption, to use a ValueConverter from a specific driver. Pings db so that all expectations could be asserted.

Code:

db, mock, err := New()
if err != nil {
    fmt.Println("expected no error, but got:", err)
    return
}
defer db.Close()
// now we can expect operations performed on db
mock.ExpectBegin().WillReturnError(fmt.Errorf("an error will occur on db.Begin() call"))

func NewWithDSN Uses

func NewWithDSN(dsn string, options ...func(*sqlmock) error) (*sql.DB, Sqlmock, error)

NewWithDSN creates sqlmock database connection with a specific DSN and a mock to manage expectations. Accepts options, like ValueConverterOption, to use a ValueConverter from a specific driver. Pings db so that all expectations could be asserted.

This method is introduced because of sql abstraction libraries, which do not provide a way to initialize with sql.DB instance. For example GORM library.

Note, it will error if attempted to create with an already used dsn

It is not recommended to use this method, unless you really need it and there is no other way around.

Directories

PathSynopsis
examples
examples/basic
examples/blog
examples/orders

Package sqlmock imports 12 packages (graph) and is imported by 7 packages. Updated 2018-10-21. Refresh now. Tools for package owners.