top
(README.md)
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.
<pre>
import (
	"database/sql"
	_"github.com/erikstmartin/go-testdb"
)

db, _ := sql.Open("testdb", "")
</pre>

## Stubbing connection failure
You're able to set your own function to execute when the sql library calls sql.Open
<pre>
testdb.SetOpenFunc(func(dsn string) (driver.Conn, error) {
	return c, errors.New("failed to connect")
})
</pre>

## 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).

<pre>
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)
</pre>

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

<pre>
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)
</pre>

## 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
<pre>
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")
</pre>

## Stubbing Parameterized Query
Sometimes you need control over the results of a parameterized query.

<pre>
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")
</pre>

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

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

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

res, err := db.Query(sql)
</pre>

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

<pre>
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")
</pre>

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

<pre>
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")
</pre>

## 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.

<pre>
func TestMyDatabase(t *testing.T){
	defer testdb.Reset()
}
</pre>

#### 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.

Imported by 30 package(s)

  1. github.com/Billups/golang-geo
  2. github.com/GordonDiggs/golang-geo
  3. github.com/JosephBuchma/golang-geo
  4. github.com/RiftBit/ALS-Go
  5. github.com/Sproutling/golang-geo
  6. github.com/XuKaiqiang/golang-geo
  7. github.com/adampresley/golangdb
  8. github.com/ahl5esoft/golang-geo
  9. github.com/apo-j/golang-geo
  10. github.com/briansorahan/golang-geo
  11. github.com/cvanderschuere/golang-geo
  12. github.com/enj/golang-geo
  13. github.com/geraldstanje/golang-geo
  14. github.com/heetch/golang-geo
  15. github.com/ihcsim/golang-geo
  16. github.com/jeevatkm/golang-geo
  17. github.com/jonathaningram/golang-geo
  18. github.com/jpemberthy/golang-geo
  19. github.com/jrbudnack/cf-sql-broker/dbconnection/testDbConnection
  20. github.com/kellydunn/golang-geo
  21. github.com/mrnugget/golang-geo
  22. github.com/rustyoz/golang-geo
  23. github.com/sajari/golang-geo
  24. github.com/troophq/golang-geo
  25. github.com/twanies/golang-geo
  26. github.com/varver/golang-geo
  27. github.com/whinette/golang-geo
  28. github.com/yiziz/golang-geo
  29. gopkg.in/Billups/golang-geo.v2/db
  30. gopkg.in/kellydunn/golang-geo.v0

Imported only in test by 200 package(s)

  1. coding.net/moss/yogo/gorm
  2. github.com/4ydx/gorm
  3. github.com/8090boy/gorm
  4. github.com/9uuso/gorm
  5. github.com/BrandonStrickland/site
  6. github.com/CodeRushing/gorm
  7. github.com/DSchalla/gorm
  8. github.com/Eazynow/gorm
  9. github.com/ElvizLai/gorm
  10. github.com/G-pu/gorm
  11. github.com/Go-Promo/gorm
  12. github.com/Jiajun-Fan/gorm
  13. github.com/KevinSjoberg/gorm
  14. github.com/LukeShu/gorm
  15. github.com/MendelGusmao/gorm
  16. github.com/NOX73/gorm
  17. github.com/NotoriousTracker/gorm
  18. github.com/RckMrkr/go-lite-authentication
  19. github.com/RichardKnop/gorm
  20. github.com/RobinUS2/gorm
  21. github.com/SamuelRamond/gorm
  22. github.com/SebastianCzoch/gorm
  23. github.com/ShionRyuu/gorm
  24. github.com/StackEngine/gorm
  25. github.com/TeamFairmont/gorm
  26. github.com/Xiol/gorm
  27. github.com/a-know/mackerel-agent-plugins/mackerel-plugin-postgres
  28. github.com/abelfletcher/gorm
  29. github.com/abhi11/gorm
  30. github.com/adamar/gorm
  31. github.com/aiwuTech/gorm
  32. github.com/andrevalgrande/gorm
  33. github.com/andreynering/gorm
  34. github.com/andviro/gorm
  35. github.com/anexia-it/gorm
  36. github.com/arianitu/gorm
  37. github.com/arthurpro/gorm
  38. github.com/avadhutp/phileas/lib
  39. github.com/awakenetworks/gorm
  40. github.com/bendemaree/gorm
  41. github.com/bennAH/gorm
  42. github.com/bh5-go/gorm
  43. github.com/bhcleek/sqldecoder
  44. github.com/bramp/gorm
  45. github.com/carbin-gun/gorm
  46. github.com/ch3lo/gorm
  47. github.com/chanshik/gorm
  48. github.com/chr4/gorm
  49. github.com/cihangir/gorm
  50. github.com/cloudfoundry-incubator/galera-healthcheck/healthcheck
  51. github.com/cloudfoundry-incubator/galera-healthcheck/sequence_number
  52. github.com/cocotyty/gorm
  53. github.com/cortex/gorm
  54. github.com/corybuecker/trade-fetcher/database
  55. github.com/cristian-sima/gorm
  56. github.com/crystalin/gorm
  57. github.com/cuiweiqiang/gorm
  58. github.com/dabfleming/gorm
  59. github.com/daffodil/gorm
  60. github.com/davyzhang/gorm
  61. github.com/derlaft/gorm
  62. github.com/devchakraborty/gorm
  63. github.com/dvdplm/gorm
  64. github.com/eAndrius/gorm
  65. github.com/eazynow/gorm
  66. github.com/ehabit/gorm
  67. github.com/elgris/gorm
  68. github.com/elvizlai/gorm
  69. github.com/embroker/gorm
  70. github.com/etcinit/gorm
  71. github.com/euforia/gorm
  72. github.com/eurie-inc/gorm
  73. github.com/futurez/gorm
  74. github.com/galeone/gorm
  75. github.com/generationtux/brizo/auth
  76. github.com/generationtux/brizo/resources
  77. github.com/go-web-framework/gorm
  78. github.com/h4ck3rm1k3/gorm
  79. github.com/hazbo/gorm
  80. github.com/henriquemenezes/gorm
  81. github.com/hico-horiuchi/mackerel-agent-plugins/mackerel-plugin-postgres
  82. github.com/hiroakis/mackerel-agent-plugins/mackerel-plugin-postgres
  83. github.com/hobeone/rss2go/db
  84. github.com/hongzhen/gorm
  85. github.com/housinganywhere/gorm
  86. github.com/hoysoft/gorm
  87. github.com/huacnlee/gorm
  88. github.com/hugorut/gorm
  89. github.com/huydx/gorm
  90. github.com/ikawaha/gorm
  91. github.com/ilgooz/gorm
  92. github.com/ilisin/gorm
  93. github.com/illyabusigin/gorm
  94. github.com/ingaged/gorm
  95. github.com/j1436go/gorm
  96. github.com/jansichermann/gorm
  97. github.com/jayceecam/gorm
  98. github.com/jaytaylor/gorm
  99. github.com/jcrussell/crawlol/external/github.com/jinzhu/gorm
  100. github.com/jcscottiii/gorm
  101. github.com/jeffbmartinez/gorm
  102. github.com/jfbus/sqlbind
  103. github.com/jinzhu/gorm
  104. github.com/jlburkhead/gorm
  105. github.com/jnfeinstein/gorm
  106. github.com/jrdnull/gorm
  107. github.com/jsimnz/gorm
  108. github.com/juliendsv/gorm
  109. github.com/karamani/gorm
  110. github.com/kazhuravlev/gorm
  111. github.com/kiwih/gorm
  112. github.com/kressh/gorm
  113. github.com/leonmaia/gorm
  114. github.com/levinalex/gorm
  115. github.com/leyra/gorm
  116. github.com/likestripes/gorm
  117. github.com/liudanking/gorm
  118. github.com/lixueping/gorm
  119. github.com/longniao/gorm
  120. github.com/lucumt/gorm
  121. github.com/mackerelio/mackerel-agent-plugins/mackerel-plugin-postgres
  122. github.com/macropodhq/gorm
  123. github.com/maxid/gorm
  124. github.com/mclarkson/obdi/external/jinzhu/gorm
  125. github.com/mejinke/gorm
  126. github.com/mrkplt/gorm
  127. github.com/msmarino/gorm
  128. github.com/najeira/mackerel-agent-plugins/mackerel-plugin-postgres
  129. github.com/naokibtn/mackerel-agent-plugins/mackerel-plugin-postgres
  130. github.com/newsquid/gorm
  131. github.com/nicday/gorm
  132. github.com/nicholasf/gorm
  133. github.com/nkovacs/gorm
  134. github.com/norisu0313/mackerel-agent-plugins/mackerel-plugin-postgres
  135. github.com/nourish/gorm
  136. github.com/octoberstorm/gorm
  137. github.com/oiooj/gorm
  138. github.com/pacificporter/gorm
  139. github.com/pakohan/gorm
  140. github.com/pandax381/mackerel-agent-plugins/mackerel-plugin-postgres
  141. github.com/pariz/gorm
  142. github.com/piemapping/gorm
  143. github.com/plar/gorm
  144. github.com/postmates/gorm
  145. github.com/pyama86/mackerel-agent-plugins/mackerel-plugin-postgres
  146. github.com/qapi/gorm
  147. github.com/registrobr/gostk/db
  148. github.com/rohanthewiz/gorm
  149. github.com/ronna-s/gorm
  150. github.com/ronna-s/gorm-without-ocd
  151. github.com/rtfb/gorm
  152. github.com/rtfb/gorm-named-fields-experiments
  153. github.com/ruprict/loccasions-go
  154. github.com/ryanss/gorm
  155. github.com/samuelramond/gorm
  156. github.com/sarim/gorm
  157. github.com/sdhjl2000/gorm
  158. github.com/sendyHalim/gorm
  159. github.com/sendyhalim/gorm
  160. github.com/senseobservationsystems/gorm
  161. github.com/shesuyo/gorm
  162. github.com/shirou/gorm
  163. github.com/sidorenko-ruslan/gorm
  164. github.com/smacker/gorm
  165. github.com/smirzaei/gorm
  166. github.com/spencerkimball/sqlbind
  167. github.com/stackengine/gorm
  168. github.com/sttts/galera-healthcheck/healthcheck
  169. github.com/sunfmin/gorm
  170. github.com/svarlamov/gorm
  171. github.com/tgregory/gorm
  172. github.com/thecaddy/gorm
  173. github.com/themecloud/galera-healthcheck/healthcheck
  174. github.com/thomasdao/gorm
  175. github.com/tom--bo/mackerel-agent-plugins/mackerel-plugin-postgres
  176. github.com/trajber/gostk/db
  177. github.com/turnkey-commerce/go-ping-sites/pinger
  178. github.com/ulule/gorm
  179. github.com/umisama/gorm
  180. github.com/unravelin/gorm
  181. github.com/ushios/gorm
  182. github.com/velocity-toolkit/golang-geo
  183. github.com/vibhavp/gorm
  184. github.com/wallclockbuilder/gorm
  185. github.com/waniji/mackerel-agent-plugins/mackerel-plugin-postgres
  186. github.com/willglynn/gorm
  187. github.com/xaionaro/gorm
  188. github.com/xconstruct/gorm
  189. github.com/xinhuang327/gorm
  190. github.com/yagince/gorm
  191. github.com/yanfali/gorm
  192. github.com/yne717/gorm
  193. github.com/yoheimuta/mackerel-agent-plugins/mackerel-plugin-postgres
  194. github.com/yucchiy/mackerel-agent-plugins/mackerel-plugin-postgres
  195. github.com/yyoshiki41/mackerel-agent-plugins/mackerel-plugin-postgres
  196. github.com/zhaozhi406/gorm
  197. go.bh5.co/gorm
  198. gopkg.in/jinzhu/gorm.v0
  199. gopkg.in/jinzhu/gorm.v1
  200. gopkg.in/leyra/gorm.v1