testdb

package module
v0.0.0-...-8d10e4a Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2016 License: BSD-2-Clause Imports: 9 Imported by: 44

README

go-testdb

Framework for stubbing responses from go's driver.Driver interface.

This can be used to sit in place of your sql.Db so that you can stub responses for sql calls, and remove database dependencies for your test suite.

This project is in its infancy, but has worked well for all the use cases i've had so far, and continues to evolve as new scenarios are uncovered. Please feel free to send pull-requests, or submit feature requests if you have scenarios that are not accounted for yet.

Setup

The only thing needed for setup is to include the go-testdb package, then you can create your db connection specifying "testdb" as your driver.

import (
	"database/sql"
	_"github.com/erikstmartin/go-testdb"
)

db, _ := sql.Open("testdb", "")

Stubbing connection failure

You're able to set your own function to execute when the sql library calls sql.Open

testdb.SetOpenFunc(func(dsn string) (driver.Conn, error) {
	return c, errors.New("failed to connect")
})

Stubbing queries

You're able to stub responses to known queries, unknown queries will trigger log errors so that you can see that queries were executed that were not stubbed.

Differences in whitespace, and case are ignored.

For convenience a method has been created for you to take a CSV string and turn it into a database result object (RowsFromCSVString).

db, _ := sql.Open("testdb", "")

sql := "select id, name, age from users"
columns := []string{"id", "name", "age", "created"}
result := `
1,tim,20,2012-10-01 01:00:01
2,joe,25,2012-10-02 02:00:02
3,bob,30,2012-10-03 03:00:03
`
testdb.StubQuery(sql, testdb.RowsFromCSVString(columns, result))

res, err := db.Query(sql)

If for some reason you need to specify another rune to split the columns, you can do it passing the rune that you want to use as Comma character as third argument to RowsFromCSVString

db, _ := sql.Open("testdb", "")

sql := "select id, name, age, data from users"
columns := []string{"id", "name", "age", "data", "created"}
result := `
1|tim|20|part_1,part_2,part_3|2014-10-16 15:01:00
2|joe|25|part_4,part_5,part_6|2014-10-17 15:01:01
3|bob|30|part_7,part_8,part_9|2014-10-18 15:01:02
`
testdb.StunQuery(sql, RowsFromCSVString(columns, result, '|'))

res, err := db.Query(sql)

Stubbing Query function

Some times you need more control over Query being run, maybe you need to assert whether or not a particular query is run.

You can return either a driver.Rows for response (your own or utilize RowsFromCSV) or an error to be returned

testdb.SetQueryFunc(func(query string) (result driver.Rows, err error) {
	columns := []string{"id", "name", "age", "created"}
	rows := `
1,tim,20,2012-10-01 01:00:01
2,joe,25,2012-10-02 02:00:02
3,bob,30,2012-10-03 03:00:03`

	// inspect query to ensure it matches a pattern, or anything else you want to do first
	return RowsFromCSVString(columns, rows), nil
})

db, _ := sql.Open("testdb", "")

res, err := db.Query("SELECT foo FROM bar")

Stubbing Parameterized Query

Sometimes you need control over the results of a parameterized query.

testdb.SetQueryWithArgsFunc(func(query string, args []driver.Value) (result driver.Rows, err error) {
	columns := []string{"id", "name", "age", "created"}

	rows := ""
	if args[0] == "joe" {
		rows = "2,joe,25,2012-10-02 02:00:02"
	}
	return testdb.RowsFromCSVString(columns, rows), nil
})

db, _ := sql.Open("testdb", "")

res, _ := db.Query("SELECT foo FROM bar WHERE name = $1", "joe")

Stubbing errors returned from queries

In case you need to stub errors returned from queries to ensure your code handles them properly

db, _ := sql.Open("testdb", "")

sql := "select count(*) from error"
testdb.StubQueryError(sql, errors.New("test error"))

res, err := db.Query(sql)

Stubbing Parameterized Exec query

Sometimes you need control over the handling of a parameterized query that does not return any rows.

type testResult struct{
	lastId int64
	affectedRows int64
}

func (r testResult) LastInsertId() (int64, error){
	return r.lastId, nil
}

func (r testResult) RowsAffected() (int64, error) {
	return r.affectedRows, nil
}
testdb.SetExecWithArgsFunc(func(query string, args []driver.Value) (result driver.Result, err error) {
	if args[0] == "joe" {
		return testResult{1, 1}, nil
	}
	return testResult{1, 0}, nil
})

db, _ := sql.Open("testdb", "")

res, _ := db.Exec("UPDATE bar SET name = 'foo' WHERE name = ?", "joe")

Stubbing Prepared Statements

You can use the same methods as SetQueryFunc, SetQueryWithArgsFunc for Prepared Statements

testdb.SetQueryFunc(func(query string) (result driver.Rows, err error) {
	columns := []string{"id", "name", "age", "created"}
	rows := `
1,tim,20,2012-10-01 01:00:01
2,joe,25,2012-10-02 02:00:02
3,bob,30,2012-10-03 03:00:03`

	// inspect query to ensure it matches a pattern, or anything else you want to do first
	return RowsFromCSVString(columns, rows), nil
})

db, _ := sql.Open("testdb", "")

stmt, _ := db.Prepare("SELECT foo FROM bar")
res, err := stmt.Query("SELECT foo FROM bar")

Reset

At any point in your test, or as a defer you can remove all stubbed queries, errors, custom set Query or Open functions by calling the reset method.

func TestMyDatabase(t *testing.T){
	defer testdb.Reset()
}
TODO

Feel free to contribute and send pull requests

  • Transactions
License

Copyright (c) 2013, Erik St. Martin All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Conn

func Conn() driver.Conn

Returns a pointer to the global conn object associated with this driver.

func EnableTimeParsing

func EnableTimeParsing(flag bool)

func Reset

func Reset()

Clears all stubbed queries, and replaced functions.

func RowsFromCSVString

func RowsFromCSVString(columns []string, s string, c ...rune) driver.Rows
Example
columns := []string{"id", "name", "age", "created"}
result := `
  1,tim,20,2012-10-01 01:00:01
  2,joe,25,2012-10-02 02:00:02
  3,bob,30,2012-10-03 03:00:03
  `
rows := RowsFromCSVString(columns, result)

fmt.Println(rows.Columns())
Output:

[id name age created]

func RowsFromSlice

func RowsFromSlice(columns []string, data [][]driver.Value) driver.Rows

func SetBeginFunc

func SetBeginFunc(f func() (driver.Tx, error))

Set your own function to be executed when db.Begin() is called. You can either hand back a valid transaction, or an error. Conn() can be used to grab the global Conn object containing stubbed queries.

Example
defer Reset()

commitCalled := false
rollbackCalled := false
SetBeginFunc(func() (txn driver.Tx, err error) {
	t := &Tx{}
	t.SetCommitFunc(func() error {
		commitCalled = true
		return nil
	})
	t.SetRollbackFunc(func() error {
		rollbackCalled = true
		return nil
	})
	return t, nil
})

db, _ := sql.Open("testdb", "")
tx, _ := db.Begin()
tx.Commit()

fmt.Println("CommitCalled =", commitCalled)
fmt.Println("RollbackCalled =", rollbackCalled)
Output:

CommitCalled = true
RollbackCalled = false

func SetCommitFunc

func SetCommitFunc(f func() error)

Set your own function to be executed when tx.Commit() is called on the default transcation. Conn() can be used to grab the global Conn object containing stubbed queries.

Example
defer Reset()

SetCommitFunc(func() error {
	return errors.New("commit failed")
})

db, _ := sql.Open("testdb", "")
tx, _ := db.Begin()

fmt.Println("CommitResult =", tx.Commit())
Output:

CommitResult = commit failed

func SetExecFunc

func SetExecFunc(f func(query string) (driver.Result, error))

Set your own function to be executed when db.Exec is called. You can return an error or a Result object with the LastInsertId and RowsAffected

func SetExecWithArgsFunc

func SetExecWithArgsFunc(f func(query string, args []driver.Value) (driver.Result, error))

Set your own function to be executed when db.Exec is called. You can return an error or a Result object with the LastInsertId and RowsAffected

Example
defer Reset()

SetExecWithArgsFunc(func(query string, args []driver.Value) (result driver.Result, err error) {
	if args[0] == "joe" {
		return testResult{1, 1}, nil
	}
	return testResult{1, 0}, nil
})

db, _ := sql.Open("testdb", "")

res, _ := db.Exec("UPDATE bar SET name = 'foo' WHERE name = ?", "joe")

rowsAffected, _ := res.RowsAffected()
fmt.Println("RowsAffected =", rowsAffected)
Output:

RowsAffected = 1

func SetOpenFunc

func SetOpenFunc(f func(dsn string) (driver.Conn, error))

Set your own function to be executed when db.Open() is called. You can either hand back a valid connection, or an error. Conn() can be used to grab the global Conn object containing stubbed queries.

Example
defer Reset()

SetOpenFunc(func(dsn string) (driver.Conn, error) {
	// Conn() will return the same internal driver.Conn being used by the driver
	return Conn(), errors.New("test error")
})

// err only returns from this if it's an unknown driver, we are stubbing opening a connection
db, _ := sql.Open("testdb", "foo")
_, err := db.Driver().Open("foo")

if err != nil {
	fmt.Println("Stubbed error returned as expected: " + err.Error())
}
Output:

Stubbed error returned as expected: test error

func SetQueryFunc

func SetQueryFunc(f func(query string) (result driver.Rows, err error))

Set your own function to be executed when db.Query() is called. As with StubQuery() you can use the RowsFromCSVString() method to easily generate the driver.Rows, or you can return your own.

Example
defer Reset()

columns := []string{"id", "name", "age", "created"}
rows := "1,tim,20,2012-10-01 01:00:01\n2,joe,25,2012-10-02 02:00:02\n3,bob,30,2012-10-03 03:00:03"

SetQueryFunc(func(query string) (result driver.Rows, err error) {
	return RowsFromCSVString(columns, rows), nil
})

db, _ := sql.Open("testdb", "")

res, _ := db.Query("SELECT foo FROM bar")

for res.Next() {
	var u = new(user)
	res.Scan(&u.id, &u.name, &u.age, &u.created)

	fmt.Println(u.name + " - " + strconv.FormatInt(u.age, 10))
}
Output:

tim - 20
joe - 25
bob - 30
Example (QueryRow)
defer Reset()

columns := []string{"id", "name", "age", "created"}
rows := "1,tim,20,2012-10-01 01:00:01"

SetQueryFunc(func(query string) (result driver.Rows, err error) {
	return RowsFromCSVString(columns, rows), nil
})

db, _ := sql.Open("testdb", "")

row := db.QueryRow("SELECT foo FROM bar")

var u = new(user)
row.Scan(&u.id, &u.name, &u.age, &u.created)

fmt.Println(u.name + " - " + strconv.FormatInt(u.age, 10))
Output:

tim - 20

func SetQueryWithArgsFunc

func SetQueryWithArgsFunc(f func(query string, args []driver.Value) (result driver.Rows, err error))

Set your own function to be executed when db.Query() is called. As with StubQuery() you can use the RowsFromCSVString() method to easily generate the driver.Rows, or you can return your own.

Example
defer Reset()

SetQueryWithArgsFunc(func(query string, args []driver.Value) (result driver.Rows, err error) {
	columns := []string{"id", "name", "age", "created"}

	rows := ""
	if args[0] == "joe" {
		rows = "2,joe,25,2012-10-02 02:00:02"
	}
	return RowsFromCSVString(columns, rows), nil
})

db, _ := sql.Open("testdb", "")

res, _ := db.Query("SELECT foo FROM bar WHERE name = $1", "joe")

for res.Next() {
	var u = new(user)
	res.Scan(&u.id, &u.name, &u.age, &u.created)

	fmt.Println(u.name + " - " + strconv.FormatInt(u.age, 10))
}
Output:

joe - 25

func SetRollbackFunc

func SetRollbackFunc(f func() error)

Set your own function to be executed when tx.Rollback() is called on the default transcation. Conn() can be used to grab the global Conn object containing stubbed queries.

Example
defer Reset()

SetRollbackFunc(func() error {
	return errors.New("rollback failed")
})

db, _ := sql.Open("testdb", "")
tx, _ := db.Begin()

fmt.Println("RollbackResult =", tx.Rollback())
Output:

RollbackResult = rollback failed

func StubBegin

func StubBegin(tx driver.Tx, err error)

Stubs the global driver.Conn to return the supplied tx and error when db.Begin() is called.

func StubCommitError

func StubCommitError(err error)

Stubs the default transaction to return the supplied error when tx.Commit() is called.

func StubExec

func StubExec(q string, r *Result)

Stubs the global driver.Conn to return the supplied Result when db.Exec is called, query stubbing is case insensitive, and whitespace is also ignored.

func StubExecError

func StubExecError(q string, err error)

Stubs the global driver.Conn to return the supplied error when db.Exec() is called, query stubbing is case insensitive, and whitespace is also ignored.

func StubQuery

func StubQuery(q string, rows driver.Rows)

Stubs the global driver.Conn to return the supplied driver.Rows when db.Query() is called, query stubbing is case insensitive, and whitespace is also ignored.

Example
defer Reset()

db, _ := sql.Open("testdb", "")

sql := "select id, name, age from users"
columns := []string{"id", "name", "age", "created"}
result := `
  1,tim,20,2012-10-01 01:00:01
  2,joe,25,2012-10-02 02:00:02
  3,bob,30,2012-10-03 03:00:03
  `
StubQuery(sql, RowsFromCSVString(columns, result))

res, _ := db.Query(sql)

for res.Next() {
	var u = new(user)
	res.Scan(&u.id, &u.name, &u.age, &u.created)

	fmt.Println(u.name + " - " + strconv.FormatInt(u.age, 10))
}
Output:

tim - 20
joe - 25
bob - 30
Example (QueryRow)
defer Reset()

db, _ := sql.Open("testdb", "")

sql := "select id, name, age from users"
columns := []string{"id", "name", "age", "created"}
result := `
  1,tim,20,2012-10-01 01:00:01
  `
StubQuery(sql, RowsFromCSVString(columns, result))

row := db.QueryRow(sql)

u := new(user)
row.Scan(&u.id, &u.name, &u.age, &u.created)

fmt.Println(u.name + " - " + strconv.FormatInt(u.age, 10))
Output:

tim - 20

func StubQueryError

func StubQueryError(q string, err error)

Stubs the global driver.Conn to return the supplied error when db.Query() is called, query stubbing is case insensitive, and whitespace is also ignored.

Example
defer Reset()

db, _ := sql.Open("testdb", "")

sql := "select count(*) from error"

StubQueryError(sql, errors.New("test error"))

_, err := db.Query(sql)

if err != nil {
	fmt.Println("Error returned: " + err.Error())
}
Output:

Error returned: test error

func StubRollbackError

func StubRollbackError(err error)

Stubs the default transaction to return the supplied error when tx.Rollback() is called.

Types

type Result

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

func NewResult

func NewResult(lastId int64, lastIdError error, rowsAffected int64, rowsAffectedError error) (res *Result)

func (*Result) LastInsertId

func (res *Result) LastInsertId() (int64, error)

func (*Result) RowsAffected

func (res *Result) RowsAffected() (int64, error)

type Tx

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

func (*Tx) Commit

func (t *Tx) Commit() error

func (*Tx) Rollback

func (t *Tx) Rollback() error

func (*Tx) SetCommitFunc

func (t *Tx) SetCommitFunc(f func() error)

func (*Tx) SetRollbackFunc

func (t *Tx) SetRollbackFunc(f func() error)

func (*Tx) StubCommitError

func (t *Tx) StubCommitError(err error)

func (*Tx) StubRollbackError

func (t *Tx) StubRollbackError(err error)

Jump to

Keyboard shortcuts

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