user776942
user776942

Reputation:

Mocking postgresql with a stored procedure

I've been going through the test files of https://github.com/DATA-DOG/go-sqlmock to figure out how to create a stored procedure for mocking purposes. I have:

_, err = db.Exec(`
    CREATE OR REPLACE FUNCTION val() RETURNS INT AS 
        $$ SELECT 1; $$ 
    LANGUAGE sql;   
`)

if err != nil {
    t.Fatal(err)
}

I get:

all expectations were already fulfilled, call to exec 'CREATE OR REPLACE FUNCTION val() RETURNS INT AS $$ SELECT 1; $$ LANGUAGE sql;' query with args [] was not expected

If, instead, I try it with

        mock.ExpectExec(`
            CREATE OR REPLACE FUNCTION val() RETURNS INT AS
                $$ SELECT 1; $$
            LANGUAGE sql;
        `,
        ).WillReturnResult(sqlmock.NewResult(0, 0))

        if err := mock.ExpectationsWereMet(); err != nil {
            t.Fatal(err)
        }

I get:

there is a remaining expectation which was not matched: ExpectedExec => expecting Exec which:
              - matches sql: 'CREATE OR REPLACE FUNCTION val() RETURNS INT AS $$ SELECT 1; $$ LANGUAGE sql;'
              - is without arguments
              - should return Result having:
                  LastInsertId: 0
                  RowsAffected: 0

I am really confused on how to setup a basic stored procedure.

Upvotes: 2

Views: 6882

Answers (1)

eugenioy
eugenioy

Reputation: 12393

The sqlmock library works pretty well for this.

But please note that the ExpectExec receives a regular expression in order to match:

// ExpectExec expects Exec() to be called with sql query
// which match sqlRegexStr given regexp.
// the *ExpectedExec allows to mock database response
ExpectExec(sqlRegexStr string) *ExpectedExec

You are sending that function the exact string you expect to receive without any escaping.

To escape the string, add this:

import (
   "regexp"
)

And then when adding the expectation, escape your string (note the regexp.QuoteMeta):

mock.ExpectExec(regexp.QuoteMeta(`
    CREATE OR REPLACE FUNCTION val() RETURNS INT AS
        $$
        SELECT 1;
        $$
    LANGUAGE sql;
`),
).WillReturnResult(sqlmock.NewResult(0, 0))

That way, the escaped regexp will match your exec command.

Upvotes: 2

Related Questions