Commit 42a0bf16 authored by Tianon Gravi's avatar Tianon Gravi

Imported Upstream version 1.0.0

parent e8a98c33
/examples/blog/blog
/examples/orders/orders
/examples/basic/basic
language: go
sudo: false
go:
- 1.2
- 1.3
- 1.4
- release
- tip
script:
- go test -v ./...
- go test -race ./...
The three clause BSD license (http://en.wikipedia.org/wiki/BSD_licenses)
Copyright (c) 2013-2015, DataDog.lt team
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.
* The name DataDog.lt may not be used to endorse or promote products
derived from this software without specific prior written permission.
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 MICHAEL BOSTOCK 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.
[![Build Status](https://travis-ci.org/DATA-DOG/go-sqlmock.png)](https://travis-ci.org/DATA-DOG/go-sqlmock)
[![GoDoc](https://godoc.org/github.com/DATA-DOG/go-sqlmock?status.png)](https://godoc.org/github.com/DATA-DOG/go-sqlmock)
# Sql driver mock for Golang
This is a **mock** driver as **database/sql/driver** which is very flexible and pragmatic to
manage and mock expected queries. All the expectations should be met and all queries and actions
triggered should be mocked in order to pass a test. The package has no 3rd party dependencies.
**NOTE:** regarding major issues #20 and #9 the **api** has changed to support concurrency and more than
one database connection.
If you need an old version, checkout **go-sqlmock** at gopkg.in:
go get gopkg.in/DATA-DOG/go-sqlmock.v0
Otherwise use the **v1** branch from master which should be stable afterwards, because all the issues which
were known will be fixed in this version.
## Install
go get gopkg.in/DATA-DOG/go-sqlmock.v1
Or take an older version:
go get gopkg.in/DATA-DOG/go-sqlmock.v0
## Documentation and Examples
Visit [godoc](http://godoc.org/github.com/DATA-DOG/go-sqlmock) for general examples and public api reference.
See **.travis.yml** for supported **go** versions.
Different use case, is to functionally test with a real database - [go-txdb](https://github.com/DATA-DOG/go-txdb)
all database related actions are isolated within a single transaction so the database can remain in the same state.
See implementation examples:
- [blog API server](https://github.com/DATA-DOG/go-sqlmock/tree/master/examples/blog)
- [the same orders example](https://github.com/DATA-DOG/go-sqlmock/tree/master/examples/orders)
### Something you may want to test
``` go
package main
import "database/sql"
func recordStats(db *sql.DB, userID, productID int64) (err error) {
tx, err := db.Begin()
if err != nil {
return
}
defer func() {
switch err {
case nil:
err = tx.Commit()
default:
tx.Rollback()
}
}()
if _, err = tx.Exec("UPDATE products SET views = views + 1"); err != nil {
return
}
if _, err = tx.Exec("INSERT INTO product_viewers (user_id, product_id) VALUES (?, ?)", userID, productID); err != nil {
return
}
return
}
func main() {
// @NOTE: the real connection is not required for tests
db, err := sql.Open("mysql", "root@/blog")
if err != nil {
panic(err)
}
defer db.Close()
if err = recordStats(db, 1 /*some user id*/, 5 /*some product id*/); err != nil {
panic(err)
}
}
```
### Tests with sqlmock
``` go
package main
import (
"fmt"
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
// a successful case
func TestShouldUpdateStats(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
// now we execute our method
if err = recordStats(db, 2, 3); err != nil {
t.Errorf("error was not expected while updating stats: %s", err)
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expections: %s", err)
}
}
// a failing test case
func TestShouldRollbackStatUpdatesOnFailure(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO product_viewers").
WithArgs(2, 3).
WillReturnError(fmt.Errorf("some error"))
mock.ExpectRollback()
// now we execute our method
if err = recordStats(db, 2, 3); err == nil {
t.Errorf("was expecting an error, but there was none")
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expections: %s", err)
}
}
```
## Run tests
go test -race
## Changes
- **2015-08-27** - **v1** api change, concurrency support, all known issues fixed.
- **2014-08-16** instead of **panic** during reflect type mismatch when comparing query arguments - now return error
- **2014-08-14** added **sqlmock.NewErrorResult** which gives an option to return driver.Result with errors for
interface methods, see [issue](https://github.com/DATA-DOG/go-sqlmock/issues/5)
- **2014-05-29** allow to match arguments in more sophisticated ways, by providing an **sqlmock.Argument** interface
- **2014-04-21** introduce **sqlmock.New()** to open a mock database connection for tests. This method
calls sql.DB.Ping to ensure that connection is open, see [issue](https://github.com/DATA-DOG/go-sqlmock/issues/4).
This way on Close it will surely assert if all expectations are met, even if database was not triggered at all.
The old way is still available, but it is advisable to call db.Ping manually before asserting with db.Close.
- **2014-02-14** RowsFromCSVString is now a part of Rows interface named as FromCSVString.
It has changed to allow more ways to construct rows and to easily extend this API in future.
See [issue 1](https://github.com/DATA-DOG/go-sqlmock/issues/1)
**RowsFromCSVString** is deprecated and will be removed in future
## Contributions
Feel free to open a pull request. Note, if you wish to contribute an extension to public (exported methods or types) -
please open an issue before, to discuss whether these changes can be accepted. All backward incompatible changes are
and will be treated cautiously
## License
The [three clause BSD license](http://en.wikipedia.org/wiki/BSD_licenses)
package sqlmock
import (
"database/sql"
"database/sql/driver"
"fmt"
"sync"
)
var pool *mockDriver
func init() {
pool = &mockDriver{
conns: make(map[string]*sqlmock),
}
sql.Register("sqlmock", pool)
}
type mockDriver struct {
sync.Mutex
counter int
conns map[string]*sqlmock
}
func (d *mockDriver) Open(dsn string) (driver.Conn, error) {
d.Lock()
defer d.Unlock()
c, ok := d.conns[dsn]
if !ok {
return c, fmt.Errorf("expected a connection to be available, but it is not")
}
c.opened++
return c, nil
}
// New creates sqlmock database connection
// and a mock to manage expectations.
// Pings db so that all expectations could be
// asserted.
func New() (db *sql.DB, mock Sqlmock, err error) {
pool.Lock()
dsn := fmt.Sprintf("sqlmock_db_%d", pool.counter)
pool.counter++
smock := &sqlmock{dsn: dsn, drv: pool, ordered: true}
pool.conns[dsn] = smock
pool.Unlock()
db, err = sql.Open("sqlmock", dsn)
if err != nil {
return
}
return db, smock, db.Ping()
}
package sqlmock
import (
"fmt"
"testing"
)
func ExampleNew() {
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 TestShouldOpenConnectionIssue15(t *testing.T) {
db, mock, err := New()
if err != nil {
t.Errorf("expected no error, but got: %s", err)
}
if len(pool.conns) != 1 {
t.Errorf("expected 1 connection in pool, but there is: %d", len(pool.conns))
}
smock, _ := mock.(*sqlmock)
if smock.opened != 1 {
t.Errorf("expected 1 connection on mock to be opened, but there is: %d", smock.opened)
}
// defer so the rows gets closed first
defer func() {
if smock.opened != 0 {
t.Errorf("expected no connections on mock to be opened, but there is: %d", smock.opened)
}
}()
mock.ExpectQuery("SELECT").WillReturnRows(NewRows([]string{"one", "two"}).AddRow("val1", "val2"))
rows, err := db.Query("SELECT")
if err != nil {
t.Errorf("unexpected error: %s", err)
}
defer rows.Close()
mock.ExpectExec("UPDATE").WillReturnResult(NewResult(1, 1))
if _, err = db.Exec("UPDATE"); err != nil {
t.Errorf("unexpected error: %s", err)
}
// now there should be two connections open
if smock.opened != 2 {
t.Errorf("expected 2 connection on mock to be opened, but there is: %d", smock.opened)
}
mock.ExpectClose()
if err = db.Close(); err != nil {
t.Errorf("expected no error on close, but got: %s", err)
}
// one is still reserved for rows
if smock.opened != 1 {
t.Errorf("expected 1 connection on mock to be still reserved for rows, but there is: %d", smock.opened)
}
}
func TestTwoOpenConnectionsOnTheSameDSN(t *testing.T) {
db, mock, err := New()
if err != nil {
t.Errorf("expected no error, but got: %s", err)
}
db2, mock2, err := New()
if len(pool.conns) != 2 {
t.Errorf("expected 2 connection in pool, but there is: %d", len(pool.conns))
}
if db == db2 {
t.Errorf("expected not the same database instance, but it is the same")
}
if mock == mock2 {
t.Errorf("expected not the same mock instance, but it is the same")
}
}
package main
import "database/sql"
func recordStats(db *sql.DB, userID, productID int64) (err error) {
tx, err := db.Begin()
if err != nil {
return
}
defer func() {
switch err {
case nil:
err = tx.Commit()
default:
tx.Rollback()
}
}()
if _, err = tx.Exec("UPDATE products SET views = views + 1"); err != nil {
return
}
if _, err = tx.Exec("INSERT INTO product_viewers (user_id, product_id) VALUES (?, ?)", userID, productID); err != nil {
return
}
return
}
func main() {
// @NOTE: the real connection is not required for tests
db, err := sql.Open("mysql", "root@/blog")
if err != nil {
panic(err)
}
defer db.Close()
if err = recordStats(db, 1 /*some user id*/, 5 /*some product id*/); err != nil {
panic(err)
}
}
package main
import (
"fmt"
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
// a successful case
func TestShouldUpdateStats(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO product_viewers").WithArgs(2, 3).WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
// now we execute our method
if err = recordStats(db, 2, 3); err != nil {
t.Errorf("error was not expected while updating stats: %s", err)
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expections: %s", err)
}
}
// a failing test case
func TestShouldRollbackStatUpdatesOnFailure(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
mock.ExpectBegin()
mock.ExpectExec("UPDATE products").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectExec("INSERT INTO product_viewers").
WithArgs(2, 3).
WillReturnError(fmt.Errorf("some error"))
mock.ExpectRollback()
// now we execute our method
if err = recordStats(db, 2, 3); err == nil {
t.Errorf("was expecting an error, but there was none")
}
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expections: %s", err)
}
}
package main
import (
"database/sql"
"encoding/json"
"net/http"
)
type api struct {
db *sql.DB
}
type post struct {
ID int
Title string
Body string
}
func (a *api) posts(w http.ResponseWriter, r *http.Request) {
rows, err := a.db.Query("SELECT id, title, body FROM posts")
if err != nil {
a.fail(w, "failed to fetch posts: "+err.Error(), 500)
return
}
defer rows.Close()
var posts []*post
for rows.Next() {
p := &post{}
if err := rows.Scan(&p.ID, &p.Title, &p.Body); err != nil {
a.fail(w, "failed to scan post: "+err.Error(), 500)
return
}
posts = append(posts, p)
}
if rows.Err() != nil {
a.fail(w, "failed to read all posts: "+rows.Err().Error(), 500)
return
}
data := struct {
Posts []*post
}{posts}
a.ok(w, data)
}
func main() {
// @NOTE: the real connection is not required for tests
db, err := sql.Open("mysql", "root@/blog")
if err != nil {
panic(err)
}
app := &api{db: db}
http.HandleFunc("/posts", app.posts)
http.ListenAndServe(":8080", nil)
}
func (a *api) fail(w http.ResponseWriter, msg string, status int) {
w.Header().Set("Content-Type", "application/json")
data := struct {
Error string
}{Error: msg}
resp, _ := json.Marshal(data)
w.WriteHeader(status)
w.Write(resp)
}
func (a *api) ok(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
resp, err := json.Marshal(data)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
a.fail(w, "oops something evil has happened", 500)
return
}
w.Write(resp)
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/DATA-DOG/go-sqlmock"
)
func (a *api) assertJSON(actual []byte, data interface{}, t *testing.T) {
expected, err := json.Marshal(data)
if err != nil {
t.Fatalf("an error '%s' was not expected when marshaling expected json data", err)
}
if bytes.Compare(expected, actual) != 0 {
t.Errorf("the expected json: %s is different from actual %s", expected, actual)
}
}
func TestShouldGetPosts(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
// create app with mocked db, request and response to test
app := &api{db}
req, err := http.NewRequest("GET", "http://localhost/posts", nil)
if err != nil {
t.Fatalf("an error '%s' was not expected while creating request", err)
}
w := httptest.NewRecorder()
// before we actually execute our api function, we need to expect required DB actions
rows := sqlmock.NewRows([]string{"id", "title", "body"}).
AddRow(1, "post 1", "hello").
AddRow(2, "post 2", "world")
mock.ExpectQuery("^SELECT (.+) FROM posts$").WillReturnRows(rows)
// now we execute our request
app.posts(w, req)
if w.Code != 200 {
t.Fatalf("expected status code to be 200, but got: %d", w.Code)
}
data := struct {
Posts []*post
}{Posts: []*post{
{ID: 1, Title: "post 1", Body: "hello"},
{ID: 2, Title: "post 2", Body: "world"},
}}
app.assertJSON(w.Body.Bytes(), data, t)
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expections: %s", err)
}
}
func TestShouldRespondWithErrorOnFailure(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
// create app with mocked db, request and response to test
app := &api{db}
req, err := http.NewRequest("GET", "http://localhost/posts", nil)
if err != nil {
t.Fatalf("an error '%s' was not expected while creating request", err)
}
w := httptest.NewRecorder()
// before we actually execute our api function, we need to expect required DB actions
mock.ExpectQuery("^SELECT (.+) FROM posts$").WillReturnError(fmt.Errorf("some error"))
// now we execute our request
app.posts(w, req)
if w.Code != 500 {
t.Fatalf("expected status code to be 500, but got: %d", w.Code)
}
data := struct {
Error string
}{"failed to fetch posts: some error"}
app.assertJSON(w.Body.Bytes(), data, t)
// we make sure that all expectations were met
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expections: %s", err)
}
}
package examples
package main
import (
"database/sql"
"fmt"
"log"
"github.com/kisielk/sqlstruct"
)
const ORDER_PENDING = 0
const ORDER_CANCELLED = 1
type User struct {
Id int `sql:"id"`
Username string `sql:"username"`
Balance float64 `sql:"balance"`
}
type Order struct {
Id int `sql:"id"`
Value float64 `sql:"value"`
ReservedFee float64 `sql:"reserved_fee"`
Status int `sql:"status"`
}
func cancelOrder(id int, db *sql.DB) (err error) {
tx, err := db.Begin()
if err != nil {
return
}
var order Order
var user User
sql := fmt.Sprintf(`
SELECT %s, %s
FROM orders AS o
INNER JOIN users AS u ON o.buyer_id = u.id
WHERE o.id = ?
FOR UPDATE`,
sqlstruct.ColumnsAliased(order, "o"),
sqlstruct.ColumnsAliased(user, "u"))
// fetch order to cancel
rows, err := tx.Query(sql, id)
if err != nil {
tx.Rollback()
return
}
defer rows.Close()
// no rows, nothing to do
if !rows.Next() {
tx.Rollback()
return
}
// read order
err = sqlstruct.ScanAliased(&order, rows, "o")
if err != nil {
tx.Rollback()
return
}
// ensure order status
if order.Status != ORDER_PENDING {
tx.Rollback()
return
}
// read user
err = sqlstruct.ScanAliased(&user, rows, "u")
if err != nil {
tx.Rollback()
return
}
rows.Close() // manually close before other prepared statements
// refund order value
sql = "UPDATE users SET balance = balance + ? WHERE id = ?"
refundStmt, err := tx.Prepare(sql)
if err != nil {
tx.Rollback()
return
}
defer refundStmt.Close()