pashagolub / pgxmock

pgx mock driver for golang to test database interactions
Other
393 stars 49 forks source link

Problem getting rows to return #213

Closed AshMcConnell closed 4 months ago

AshMcConnell commented 4 months ago

Hi @pashagolub

Sorry, I am a bit of a newbie to Go and to pgxmock. I can't seem to get it to return any rows.

Here is the function I am testing:-

func (crud *DbCrud[T]) SingleRow(tableName string, id string) (*T, error) {
    caser := cases.Title(language.English)

    rows, _ := crud.Pool.Query(context.Background(), "SELECT * FROM race_stats."+tableName+" WHERE id = $1", id)

    entity, err := pgx.CollectOneRow(rows, pgx.RowToStructByNameLax[T])
    if err != nil {
        return nil, SingleErrorHandler(err, caser.String(tableName), id, "Fetching "+tableName)
    }
    return &entity, nil
}

Here is my test function: -

func TestSingleRow_Success(t *testing.T) {
    mockPool, _ := pgxmock.NewPool()
    mockLog := &mocks.MockLogger{}

    rows := pgxmock.NewRows([]string{"id", "name"}).AddRow(int64(1), "thing")

    mockPool.ExpectQuery("SELECT * FROM race_stats.thing WHERE id = $1").
        WithArgs("1").
        WillReturnRows(rows)

    dbCrud := NewDbCrud[Thing](mockPool, mockLog)

    dbCrud.SingleRow("thing", "1")
}

I've debugged and rows is always returning nil. I've tried wrapping it in a ExpectBegin / ExpectCommit, but no luck. Is it not matching the SQL / args or am I doing something else wrong?

Thanks for your help! Ash

AshMcConnell commented 4 months ago

Ah, the rubber 🦆 strikes again.

I realised that ExpectQuery uses a regex to match. I'll figure out how to escape the * (and perhaps the $?)

EDIT - For googlers yep, I used SELECT (.+) FROM race_stats.thing WHERE id = (.+) and it works as expected! Onwards and upwards!

Thanks! Ash

pashagolub commented 4 months ago

You can change how you match a query. You can even write your own matcher :)

AshMcConnell commented 4 months ago

Fancy! 😂 Thanks!