简体   繁体   中英

Call to Query with args [], was not expected in go-sqlmock for compound SQL queries

I was able to successfully mock the query to select from one table like so:

sqlMock.ExpectQuery("^SELECT DISTINCT (.+) FROM myTable1, myTable2").
        WillReturnRows(myResultRows)

But I was not able to mock the following query that checks for the existence of the table in my postgres db:

SELECT EXISTS
        ( SELECT 1
        FROM information_schema.tables
        WHERE table_schema = 'public'
           AND table_name = 'myTable3' );

The combination of:

    existsRows := sqlmock.NewRows([]string{"exists"}).
        AddRow(true)

AND

    slMock.ExpectQuery("^SELECT EXISTS").
        WillReturnRows(existsRows)

I tried mocking SELECT 1 as well but I get the exact same error:

time="2019-09-27T15:49:41-07:00" level=panic msg="db query" error="call to Query 'SELECT EXISTS\n\t\t( SELECT 1\n\t\tFROM information_schema.tables\n\t\tWHERE table_schema = 'public'\n\t\t   AND table_name = 'myTable3' );' with args [], was not expected, next expectation is: ExpectedExec => expecting Exec or ExecContext which......

Packages I am using:

import (
    "database/sql"
    "db"
    "os"
    "testing"

    // not explicitly called
    _ "github.com/denisenkom/go-mssqldb"
    _ "github.com/lib/pq"

    "github.com/DATA-DOG/go-sqlmock"
    "github.com/sirupsen/logrus"
)

Any ideas or pointers are appreciated. I couldn't find relevant examples on the internet

I am not sure but think the problem is in your indentation of ur query try to remove the line break or your tabulation in your query SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'myTable3' );

Like this SELECT EXISTS( SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'myTable3' );

Actually,


    sqlMock.ExpectQuery("SELECT EXISTS \\( SELECT 1 FROM information_schema\\.tables WHERE table_schema = 'public' AND table_name = 'myTable3' \\);").
        WillReturnRows(existsRows)

did the trick.

More examples here: https://chromium.googlesource.com/external/github.com/DATA-DOG/go-sqlmock/+/e36ad8d068217ee8e4df50408476b153e115e3e6/README.md

I also used regex101.com

The clue was it was expecting the next query straightaway. So we knew it didn't read this one at all. My co worker pointed it out:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM