dshmvqnl98119
dshmvqnl98119
2017-09-20 00:30

用存储过程模拟Postgresql

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • drsfgwuw61488 drsfgwuw61488 4年前

    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.

    点赞 评论 复制链接分享

为你推荐