CSVColumnParser is a function which converts trimmed csv column string to a []byte representation. Currently transforms NULL to nil
var CSVColumnParser = func(s string) interface{} { switch { case strings.ToLower(s) == "null": return nil } return []byte(s) }
ErrCancelled defines an error value, which can be expected in case of such cancellation error.
var ErrCancelled = errors.New("canceling query due to user request")
func MonitorPingsOption(monitorPings bool) func(*sqlmock) error
MonitorPingsOption determines whether calls to Ping on the driver should be observed and mocked.
If true is passed, we will check these calls were expected. Expectations can be registered using the ExpectPing() method on the mock.
If false is passed or this option is omitted, calls to Ping will not be considered when determining expectations and calls to ExpectPing will have no effect.
func NewErrorResult(err error) driver.Result
NewErrorResult creates a new sql driver Result which returns an error given for both interface methods
▹ Example
func NewResult(lastInsertID int64, rowsAffected int64) driver.Result
NewResult creates a new sql driver Result for Exec based query mocks.
▹ Example
func QueryMatcherOption(queryMatcher QueryMatcher) func(*sqlmock) error
QueryMatcherOption allows to customize SQL query matcher and match SQL query strings in more sophisticated ways. The default QueryMatcher is QueryMatcherRegexp.
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.
Argument interface allows to match any argument in specific way when used with ExpectedQuery and ExpectedExec expectations.
type Argument interface { Match(driver.Value) bool }
func AnyArg() Argument
AnyArg will return an Argument which can match any kind of arguments.
Useful for time.Time or similar kinds of arguments.
Column is a mocked column Metadata for rows.ColumnTypes()
type Column struct {
// contains filtered or unexported fields
}
func NewColumn(name string) *Column
NewColumn returns a Column with specified name
func (c *Column) DbType() string
func (c *Column) IsNullable() (bool, bool)
func (c *Column) Length() (int64, bool)
func (c *Column) Name() string
func (c *Column) Nullable(nullable bool) *Column
Nullable returns the column with nullable metadata set
func (c *Column) OfType(dbType string, sampleValue interface{}) *Column
OfType returns the column with type metadata set
func (c *Column) PrecisionScale() (int64, int64, bool)
func (c *Column) ScanType() reflect.Type
func (c *Column) WithLength(length int64) *Column
WithLength returns the column with length metadata set.
func (c *Column) WithPrecisionAndScale(precision, scale int64) *Column
WithPrecisionAndScale returns the column with precision and scale metadata set.
ExpectedBegin is used to manage *sql.DB.Begin expectation returned by *Sqlmock.ExpectBegin.
type ExpectedBegin struct {
// contains filtered or unexported fields
}
func (e *ExpectedBegin) String() string
String returns string representation
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 (e *ExpectedBegin) WillReturnError(err error) *ExpectedBegin
WillReturnError allows to set an error for *sql.DB.Begin action
ExpectedClose is used to manage *sql.DB.Close expectation returned by *Sqlmock.ExpectClose.
type ExpectedClose struct {
// contains filtered or unexported fields
}
func (e *ExpectedClose) String() string
String returns string representation
func (e *ExpectedClose) WillReturnError(err error) *ExpectedClose
WillReturnError allows to set an error for *sql.DB.Close action
ExpectedCommit is used to manage *sql.Tx.Commit expectation returned by *Sqlmock.ExpectCommit.
type ExpectedCommit struct {
// contains filtered or unexported fields
}
func (e *ExpectedCommit) String() string
String returns string representation
func (e *ExpectedCommit) WillReturnError(err error) *ExpectedCommit
WillReturnError allows to set an error for *sql.Tx.Close action
ExpectedExec is used to manage *sql.DB.Exec, *sql.Tx.Exec or *sql.Stmt.Exec expectations. Returned by *Sqlmock.ExpectExec.
type ExpectedExec struct {
// contains filtered or unexported fields
}
▹ Example
func (e *ExpectedExec) String() string
String returns string representation
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 (e *ExpectedExec) WillReturnError(err error) *ExpectedExec
WillReturnError allows to set an error for expected database exec action
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 (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. Must not be used together with WithoutArgs()
func (e *ExpectedExec) WithoutArgs() *ExpectedExec
WithoutArgs will ensure that no args are passed for this expected database exec action. if at least one argument is passed, it will return an error. This allows for stricter validation of the query arguments. Must not be used together with WithArgs()
ExpectedPing is used to manage *sql.DB.Ping expectations. Returned by *Sqlmock.ExpectPing.
type ExpectedPing struct {
// contains filtered or unexported fields
}
func (e *ExpectedPing) String() string
String returns string representation
func (e *ExpectedPing) WillDelayFor(duration time.Duration) *ExpectedPing
WillDelayFor allows to specify duration for which it will delay result. May be used together with Context.
func (e *ExpectedPing) WillReturnError(err error) *ExpectedPing
WillReturnError allows to set an error for expected database ping
ExpectedPrepare is used to manage *sql.DB.Prepare or *sql.Tx.Prepare expectations. Returned by *Sqlmock.ExpectPrepare.
type ExpectedPrepare struct {
// contains filtered or unexported fields
}
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 (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 (e *ExpectedPrepare) String() string
String returns string representation
func (e *ExpectedPrepare) WillBeClosed() *ExpectedPrepare
WillBeClosed expects this prepared statement to be closed.
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 (e *ExpectedPrepare) WillReturnCloseError(err error) *ExpectedPrepare
WillReturnCloseError allows to set an error for this prepared statement Close action
func (e *ExpectedPrepare) WillReturnError(err error) *ExpectedPrepare
WillReturnError allows to set an error for the expected *sql.DB.Prepare or *sql.Tx.Prepare action.
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.
type ExpectedQuery struct {
// contains filtered or unexported fields
}
func (e *ExpectedQuery) RowsWillBeClosed() *ExpectedQuery
RowsWillBeClosed expects this query rows to be closed.
func (e *ExpectedQuery) String() string
String returns string representation
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 (e *ExpectedQuery) WillReturnError(err error) *ExpectedQuery
WillReturnError allows to set an error for expected database query
func (e *ExpectedQuery) WillReturnRows(rows ...*Rows) *ExpectedQuery
WillReturnRows specifies the set of resulting rows that will be returned by the triggered query
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. Must not be used together with WithoutArgs()
func (e *ExpectedQuery) WithoutArgs() *ExpectedQuery
WithoutArgs will ensure that no arguments are passed for this query. if at least one argument is passed, it will return an error. This allows for stricter validation of the query arguments. Must no be used together with WithArgs()
ExpectedRollback is used to manage *sql.Tx.Rollback expectation returned by *Sqlmock.ExpectRollback.
type ExpectedRollback struct {
// contains filtered or unexported fields
}
func (e *ExpectedRollback) String() string
String returns string representation
func (e *ExpectedRollback) WillReturnError(err error) *ExpectedRollback
WillReturnError allows to set an error for *sql.Tx.Rollback action
QueryMatcher is an SQL query string matcher interface, which can be used to customize validation of SQL query strings. As an example, external library could be used to build and validate SQL ast, columns selected.
sqlmock can be customized to implement a different QueryMatcher configured through an option when sqlmock.New or sqlmock.NewWithDSN is called, default QueryMatcher is QueryMatcherRegexp.
type QueryMatcher interface { // Match expected SQL query string without whitespace to // actual SQL. Match(expectedSQL, actualSQL string) error }
QueryMatcherEqual is the SQL query matcher which simply tries a case sensitive match of expected and actual SQL strings without whitespace.
var QueryMatcherEqual QueryMatcher = QueryMatcherFunc(func(expectedSQL, actualSQL string) error { expect := stripQuery(expectedSQL) actual := stripQuery(actualSQL) if actual != expect { return fmt.Errorf(`actual sql: "%s" does not equal to expected "%s"`, actual, expect) } return nil })
QueryMatcherRegexp is the default SQL query matcher used by sqlmock. It parses expectedSQL to a regular expression and attempts to match actualSQL.
var QueryMatcherRegexp QueryMatcher = QueryMatcherFunc(func(expectedSQL, actualSQL string) error { expect := stripQuery(expectedSQL) actual := stripQuery(actualSQL) re, err := regexp.Compile(expect) if err != nil { return err } if !re.MatchString(actual) { return fmt.Errorf(`could not match actual sql: "%s" with expected regexp "%s"`, actual, re.String()) } return nil })
▹ Example
QueryMatcherFunc type is an adapter to allow the use of ordinary functions as QueryMatcher. If f is a function with the appropriate signature, QueryMatcherFunc(f) is a QueryMatcher that calls f.
type QueryMatcherFunc func(expectedSQL, actualSQL string) error
func (f QueryMatcherFunc) Match(expectedSQL, actualSQL string) error
Match implements the QueryMatcher
Rows is a mocked collection of rows to return for Query result
type Rows struct {
// contains filtered or unexported fields
}
▹ Example
▹ Example (CloseError)
▹ Example (CustomDriverValue)
▹ Example (ExpectToBeClosed)
▹ Example (RawBytes)
▹ Example (RowError)
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 NewRowsWithColumnDefinition(columns ...*Column) *Rows
NewRowsWithColumnDefinition return rows with columns metadata
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 (r *Rows) AddRows(values ...[]driver.Value) *Rows
AddRows adds multiple rows composed from database driver.Value slice and returns the same instance to perform subsequent actions.
▹ Example
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 (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 (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
Sqlmock interface for Go 1.8+
type Sqlmock interface { // Embed common methods SqlmockCommon // NewRowsWithColumnDefinition allows Rows to be created from a // sql driver.Value slice with a definition of sql metadata NewRowsWithColumnDefinition(columns ...*Column) *Rows // New Column allows to create a Column NewColumn(name string) *Column }
▹ Example (Goroutines)
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.
▹ Example
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.
Sqlmock interface serves to create expectations for any kind of database action in order to mock and test real database behavior.
type SqlmockCommon 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 expectedSQL query. // the *ExpectedPrepare allows to mock database response. // Note that you may expect Query() or Exec() on the *ExpectedPrepare // statement to prevent repeating expectedSQL ExpectPrepare(expectedSQL string) *ExpectedPrepare // ExpectQuery expects Query() or QueryRow() to be called with expectedSQL query. // the *ExpectedQuery allows to mock database response. ExpectQuery(expectedSQL string) *ExpectedQuery // ExpectExec expects Exec() to be called with expectedSQL query. // the *ExpectedExec allows to mock database response ExpectExec(expectedSQL 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 // ExpectPing expected *sql.DB.Ping to be called. // the *ExpectedPing allows to mock database response // // Ping support only exists in the SQL library in Go 1.8 and above. // ExpectPing in Go <=1.7 will return an ExpectedPing but not register // any expectations. // // You must enable pings using MonitorPingsOption for this to register // any expectations. ExpectPing() *ExpectedPing // 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 }