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