1
0
mirror of https://github.com/DATA-DOG/go-sqlmock.git synced 2024-11-28 08:49:01 +02:00

Merge pull request #65 from ahmadmuzakki29/master

Build query before regex
This commit is contained in:
Gediminas Morkevicius 2017-01-15 15:12:39 +02:00 committed by GitHub
commit d24b409866
3 changed files with 38 additions and 0 deletions

View File

@ -103,3 +103,27 @@ func ExampleExpectedExec() {
fmt.Println(err)
// Output: some error
}
func TestBuildQuery(t *testing.T){
db, mock, _ := New()
query := `
SELECT
name,
email,
address,
anotherfield
FROM user
`
mock.ExpectQuery(query)
mock.ExpectExec(query)
mock.ExpectPrepare(query)
db.QueryRow(query)
db.Exec(query)
db.Prepare(query)
if err:=mock.ExpectationsWereMet(); err!=nil{
t.Error(err)
}
}

View File

@ -255,6 +255,7 @@ func (c *sqlmock) Exec(query string, args []driver.Value) (res driver.Result, er
func (c *sqlmock) ExpectExec(sqlRegexStr string) *ExpectedExec {
e := &ExpectedExec{}
sqlRegexStr = buildQuery(sqlRegexStr)
e.sqlRegex = regexp.MustCompile(sqlRegexStr)
c.expected = append(c.expected, e)
return e
@ -301,6 +302,7 @@ func (c *sqlmock) Prepare(query string) (driver.Stmt, error) {
}
func (c *sqlmock) ExpectPrepare(sqlRegexStr string) *ExpectedPrepare {
sqlRegexStr = buildQuery(sqlRegexStr)
e := &ExpectedPrepare{sqlRegex: regexp.MustCompile(sqlRegexStr), mock: c}
c.expected = append(c.expected, e)
return e
@ -369,6 +371,7 @@ func (c *sqlmock) Query(query string, args []driver.Value) (rw driver.Rows, err
func (c *sqlmock) ExpectQuery(sqlRegexStr string) *ExpectedQuery {
e := &ExpectedQuery{}
sqlRegexStr = buildQuery(sqlRegexStr)
e.sqlRegex = regexp.MustCompile(sqlRegexStr)
c.expected = append(c.expected, e)
return e

11
util.go
View File

@ -11,3 +11,14 @@ var re = regexp.MustCompile("\\s+")
func stripQuery(q string) (s string) {
return strings.TrimSpace(re.ReplaceAllString(q, " "))
}
// mimicking how sql.DB build their queries
func buildQuery(q string)string{
q = strings.TrimSpace(q)
lines := strings.Split(q,"\n")
var newQuery string
for _,l := range lines{
newQuery = newQuery +" " +strings.TrimSpace(l)
}
return strings.TrimSpace(newQuery)
}