driftprogramming / pgxpoolmock

pgx postgresql pool
MIT License
38 stars 16 forks source link

Add support of value cast into interface value type #4

Closed demdxx closed 2 years ago

demdxx commented 2 years ago

In case of interface type of the field need to map any type from DB response. It works in the original PGX driver so need to support for proper unit testing.

For example: This type of code is properly works with real pgx driver.

type Record map[string]interface{}

func (b *Bind) list(ctx context.Context, ectx keypattern.ExecContext) ([]Record, error) {
    res := make([]Record, 0, 10)
    err := pgxscan.Select(ctx, b.conn, &res, b.listQuery.String(), b.listQuery.args(ectx)...)
    return res, err
}

The pool request makes possible to work such kind of tests

    t.Run("select list", func(t *testing.T) {
        columns := []string{"id", "username"}
        pgxRows := pgxpoolmock.NewRows(columns).
            AddRow(1, "testuser1").
            AddRow(2, "testuser2").ToPgxRows()
        mockPool.EXPECT().
            Query(gomock.Any(), gomock.Any()).
            Return(pgxRows, nil)
        res, err := bind.list(ctx, ectx)
        if assert.NoError(t, err) {
            assert.Equal(t, 2, len(res))
            assert.Equal(t, 1, res[0]["id"])
            assert.Equal(t, 2, res[1]["id"])
        }
    })