pgxpoolmock

package module
v1.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2022 License: MIT Imports: 11 Imported by: 1

README

PGX POOL MOCK

This repo provides a mock of pgxpool.Pool, pgx.Tx, and pgx.BatchResult from https://github.com/jackc/pgx so that you can test your data access code locally without using a real database.

I forked this from https://www.github.com/driftprogramming/pgxpoolmock to add support for transactions and batch sends with pgxpool.Pool.

How to install

go get -u github.com/chrisyxlee/pgxpoolmock

How to Use

See file order_dao_example_test.go to figure out how to use it. Or see the below:

package pgxpoolmock_test

import (
	"context"
	"fmt"
	"testing"

	"github.com/chrisyxlee/pgxpoolmock"
	"github.com/chrisyxlee/pgxpoolmock/sqlc"
	"github.com/chrisyxlee/pgxpoolmock/testdata"
	"github.com/golang/mock/gomock"
	"github.com/jackc/pgx/v4"
	"github.com/stretchr/testify/assert"
)

func TestName(t *testing.T) {
	t.Parallel()
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	// given
	mockPool := pgxpoolmock.NewMockPgxIface(ctrl)
	columns := []string{"id", "price"}
	pgxRows := pgxpoolmock.NewRows(columns).AddRow(100, 100000.9).ToPgxRows()
	mockPool.EXPECT().Query(gomock.Any(), gomock.Any(), gomock.Any()).Return(pgxRows, nil)
	orderDao := testdata.OrderDAO{
		Pool: mockPool,
	}

	// when
	actualOrder := orderDao.GetOrderByID(1)

	// then
	assert.NotNil(t, actualOrder)
	assert.Equal(t, 100, actualOrder.ID)
	assert.Equal(t, 100000.9, actualOrder.Price)
}

func TestMap(t *testing.T) {
	t.Parallel()
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	// given
	mockPool := pgxpoolmock.NewMockPgxIface(ctrl)
	columns := []string{"id", "price"}
	pgxRows := pgxpoolmock.NewRows(columns).AddRow(100, 100000.9).ToPgxRows()
	assert.NotEqual(t, "with empty rows", fmt.Sprintf("%s", pgxRows))

	mockPool.EXPECT().Query(gomock.Any(), gomock.Any(), gomock.Any()).Return(pgxRows, nil)
	orderDao := testdata.OrderDAO{
		Pool: mockPool,
	}

	// when
	actualOrder := orderDao.GetOrderMapByID(1)

	// then
	assert.NotNil(t, actualOrder)
	assert.Equal(t, 100, actualOrder["ID"])
	assert.Equal(t, 100000.9, actualOrder["Price"])
}

func TestTx(t *testing.T) {
	t.Parallel()
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockPool := pgxpoolmock.NewMockPgxIface(ctrl)

	// begin tx - given
	mockPool.EXPECT().BeginTx(gomock.Any(), gomock.Any()).Return(mockPool, nil)
	tx, err := mockPool.BeginTx(context.Background(), pgx.TxOptions{})
	assert.NoError(t, err)

	mockPool.EXPECT().QueryRow(gomock.Any(), "blah").Return(
		pgxpoolmock.NewRow("1"))
	row := tx.QueryRow(context.Background(), "blah")
	var s string
	err = row.Scan(&s)
	assert.NoError(t, err)
	assert.EqualValues(t, s, "1")

	mockPool.EXPECT().Rollback(gomock.Any()).Return(nil)
	assert.NoError(t, tx.Rollback(context.Background()))
}

func TestQueryMatcher(t *testing.T) {
	t.Parallel()
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockPool := pgxpoolmock.NewMockPgxIface(ctrl)

	mockPool.EXPECT().QueryRow(gomock.Any(), pgxpoolmock.QueryContains("blah")).Return(
		pgxpoolmock.NewRow("1"))
	row := mockPool.QueryRow(context.Background(), "SELECT blah FROM some_table;")
	var s string
	err := row.Scan(&s)
	assert.NoError(t, err)
}

func TestBatchResults(t *testing.T) {
	t.Parallel()
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	mockPool := pgxpoolmock.NewMockPgxIface(ctrl)
	mockBatch := pgxpoolmock.NewMockBatchResults(ctrl)

	// Unfortunately pgx.Batch isn't passed as an interface, so there's no way to mock the
	// intermediate data. The best bet is probably to separate the data creation and handling
	// into a separate function to test separately.
	mockPool.EXPECT().SendBatch(gomock.Any(), gomock.Any()).Return(mockBatch)
	mockBatch.EXPECT().QueryRow().Return(pgxpoolmock.NewRow(int32(1)))
	mockBatch.EXPECT().QueryRow().Return(pgxpoolmock.NewRow(int32(2)))
	mockBatch.EXPECT().QueryRow().Return(pgxpoolmock.NewRow(int32(3)))
	mockBatch.EXPECT().QueryRow().Return(pgxpoolmock.NewRow(int32(0)).WithError(pgxpoolmock.ErrEndBatchResult))

	q := sqlc.New(mockPool)
	var inserted int32
	q.InsertAuthors(context.Background(), []string{"a", "b", "c"}).QueryRow(func(i int, authorID int32, err error) {
		inserted++
		assert.Equal(t, inserted, authorID)
		assert.NoError(t, err)
	})
	assert.Equal(t, int32(3), inserted)
}

Documentation

Overview

Package pgxpoolmock is a generated GoMock package.

Package pgxpoolmock is a generated GoMock package.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Use the error to signify the end of a batch result.
	ErrEndBatchResult = fmt.Errorf("batch already closed")
	ErrNoBatchResult  = fmt.Errorf("no result")
)
View Source
var CSVColumnParser = func(s string) interface{} {
	switch {
	case strings.ToLower(s) == "null":
		return nil
	}
	return s
}

CSVColumnParser is a function which converts trimmed csv column string to a []byte representation. Currently transforms NULL to nil

Functions

func QueryContains added in v1.1.3

func QueryContains(s string) gomock.Matcher

Types

type BatchResults added in v1.1.4

type BatchResults interface {
	Exec() (pgconn.CommandTag, error)
	Query() (pgx.Rows, error)
	QueryRow() pgx.Row
	QueryFunc(scans []interface{}, f func(pgx.QueryFuncRow) error) (pgconn.CommandTag, error)
	Close() error
}

BatchResults is the same interface as pgx.BatchResults, placed here for mocking. https://github.com/jackc/pgx/blob/dc0ad04ff58f72f4819289f54745a36124cdbec3/batch.go#L35-L52

type MockBatchResults added in v1.1.4

type MockBatchResults struct {
	// contains filtered or unexported fields
}

MockBatchResults is a mock of BatchResults interface.

func NewMockBatchResults added in v1.1.4

func NewMockBatchResults(ctrl *gomock.Controller) *MockBatchResults

NewMockBatchResults creates a new mock instance.

func (*MockBatchResults) Close added in v1.1.4

func (m *MockBatchResults) Close() error

Close mocks base method.

func (*MockBatchResults) EXPECT added in v1.1.4

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockBatchResults) Exec added in v1.1.4

func (m *MockBatchResults) Exec() (pgconn.CommandTag, error)

Exec mocks base method.

func (*MockBatchResults) Query added in v1.1.4

func (m *MockBatchResults) Query() (pgx.Rows, error)

Query mocks base method.

func (*MockBatchResults) QueryFunc added in v1.1.4

func (m *MockBatchResults) QueryFunc(scans []interface{}, f func(pgx.QueryFuncRow) error) (pgconn.CommandTag, error)

QueryFunc mocks base method.

func (*MockBatchResults) QueryRow added in v1.1.4

func (m *MockBatchResults) QueryRow() pgx.Row

QueryRow mocks base method.

type MockBatchResultsMockRecorder added in v1.1.4

type MockBatchResultsMockRecorder struct {
	// contains filtered or unexported fields
}

MockBatchResultsMockRecorder is the mock recorder for MockBatchResults.

func (*MockBatchResultsMockRecorder) Close added in v1.1.4

Close indicates an expected call of Close.

func (*MockBatchResultsMockRecorder) Exec added in v1.1.4

Exec indicates an expected call of Exec.

func (*MockBatchResultsMockRecorder) Query added in v1.1.4

Query indicates an expected call of Query.

func (*MockBatchResultsMockRecorder) QueryFunc added in v1.1.4

func (mr *MockBatchResultsMockRecorder) QueryFunc(scans, f interface{}) *gomock.Call

QueryFunc indicates an expected call of QueryFunc.

func (*MockBatchResultsMockRecorder) QueryRow added in v1.1.4

func (mr *MockBatchResultsMockRecorder) QueryRow() *gomock.Call

QueryRow indicates an expected call of QueryRow.

type MockPgxIface

type MockPgxIface struct {
	// contains filtered or unexported fields
}

MockPgxIface is a mock of PgxIface interface.

func NewMockPgxIface

func NewMockPgxIface(ctrl *gomock.Controller) *MockPgxIface

NewMockPgxIface creates a new mock instance.

func (*MockPgxIface) Begin

func (m *MockPgxIface) Begin(ctx context.Context) (pgx.Tx, error)

Begin mocks base method.

func (*MockPgxIface) BeginFunc

func (m *MockPgxIface) BeginFunc(ctx context.Context, f func(pgx.Tx) error) error

BeginFunc mocks base method.

func (*MockPgxIface) BeginTx

func (m *MockPgxIface) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)

BeginTx mocks base method.

func (*MockPgxIface) BeginTxFunc

func (m *MockPgxIface) BeginTxFunc(ctx context.Context, txOptions pgx.TxOptions, f func(pgx.Tx) error) error

BeginTxFunc mocks base method.

func (*MockPgxIface) Close

func (m *MockPgxIface) Close()

Close mocks base method.

func (*MockPgxIface) Commit

func (m *MockPgxIface) Commit(ctx context.Context) error

Commit mocks base method.

func (*MockPgxIface) Conn

func (m *MockPgxIface) Conn() *pgx.Conn

Conn mocks base method.

func (*MockPgxIface) CopyFrom

func (m *MockPgxIface) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnName []string, rowSvc pgx.CopyFromSource) (int64, error)

CopyFrom mocks base method.

func (*MockPgxIface) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockPgxIface) Exec

func (m *MockPgxIface) Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)

Exec mocks base method.

func (*MockPgxIface) LargeObjects

func (m *MockPgxIface) LargeObjects() pgx.LargeObjects

LargeObjects mocks base method.

func (*MockPgxIface) Prepare

func (m *MockPgxIface) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error)

Prepare mocks base method.

func (*MockPgxIface) Query

func (m *MockPgxIface) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)

Query mocks base method.

func (*MockPgxIface) QueryFunc

func (m *MockPgxIface) QueryFunc(ctx context.Context, sql string, args, scans []interface{}, f func(pgx.QueryFuncRow) error) (pgconn.CommandTag, error)

QueryFunc mocks base method.

func (*MockPgxIface) QueryRow

func (m *MockPgxIface) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row

QueryRow mocks base method.

func (*MockPgxIface) Rollback

func (m *MockPgxIface) Rollback(ctx context.Context) error

Rollback mocks base method.

func (*MockPgxIface) SendBatch

func (m *MockPgxIface) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults

SendBatch mocks base method.

type MockPgxIfaceMockRecorder

type MockPgxIfaceMockRecorder struct {
	// contains filtered or unexported fields
}

MockPgxIfaceMockRecorder is the mock recorder for MockPgxIface.

func (*MockPgxIfaceMockRecorder) Begin

func (mr *MockPgxIfaceMockRecorder) Begin(ctx interface{}) *gomock.Call

Begin indicates an expected call of Begin.

func (*MockPgxIfaceMockRecorder) BeginFunc

func (mr *MockPgxIfaceMockRecorder) BeginFunc(ctx, f interface{}) *gomock.Call

BeginFunc indicates an expected call of BeginFunc.

func (*MockPgxIfaceMockRecorder) BeginTx

func (mr *MockPgxIfaceMockRecorder) BeginTx(ctx, txOptions interface{}) *gomock.Call

BeginTx indicates an expected call of BeginTx.

func (*MockPgxIfaceMockRecorder) BeginTxFunc

func (mr *MockPgxIfaceMockRecorder) BeginTxFunc(ctx, txOptions, f interface{}) *gomock.Call

BeginTxFunc indicates an expected call of BeginTxFunc.

func (*MockPgxIfaceMockRecorder) Close

func (mr *MockPgxIfaceMockRecorder) Close() *gomock.Call

Close indicates an expected call of Close.

func (*MockPgxIfaceMockRecorder) Commit

func (mr *MockPgxIfaceMockRecorder) Commit(ctx interface{}) *gomock.Call

Commit indicates an expected call of Commit.

func (*MockPgxIfaceMockRecorder) Conn

func (mr *MockPgxIfaceMockRecorder) Conn() *gomock.Call

Conn indicates an expected call of Conn.

func (*MockPgxIfaceMockRecorder) CopyFrom

func (mr *MockPgxIfaceMockRecorder) CopyFrom(ctx, tableName, columnName, rowSvc interface{}) *gomock.Call

CopyFrom indicates an expected call of CopyFrom.

func (*MockPgxIfaceMockRecorder) Exec

func (mr *MockPgxIfaceMockRecorder) Exec(ctx, sql interface{}, arguments ...interface{}) *gomock.Call

Exec indicates an expected call of Exec.

func (*MockPgxIfaceMockRecorder) LargeObjects

func (mr *MockPgxIfaceMockRecorder) LargeObjects() *gomock.Call

LargeObjects indicates an expected call of LargeObjects.

func (*MockPgxIfaceMockRecorder) Prepare

func (mr *MockPgxIfaceMockRecorder) Prepare(ctx, name, sql interface{}) *gomock.Call

Prepare indicates an expected call of Prepare.

func (*MockPgxIfaceMockRecorder) Query

func (mr *MockPgxIfaceMockRecorder) Query(ctx, sql interface{}, args ...interface{}) *gomock.Call

Query indicates an expected call of Query.

func (*MockPgxIfaceMockRecorder) QueryFunc

func (mr *MockPgxIfaceMockRecorder) QueryFunc(ctx, sql, args, scans, f interface{}) *gomock.Call

QueryFunc indicates an expected call of QueryFunc.

func (*MockPgxIfaceMockRecorder) QueryRow

func (mr *MockPgxIfaceMockRecorder) QueryRow(ctx, sql interface{}, args ...interface{}) *gomock.Call

QueryRow indicates an expected call of QueryRow.

func (*MockPgxIfaceMockRecorder) Rollback

func (mr *MockPgxIfaceMockRecorder) Rollback(ctx interface{}) *gomock.Call

Rollback indicates an expected call of Rollback.

func (*MockPgxIfaceMockRecorder) SendBatch

func (mr *MockPgxIfaceMockRecorder) SendBatch(ctx, b interface{}) *gomock.Call

SendBatch indicates an expected call of SendBatch.

type PgxIface

type PgxIface interface {
	// pgx.Tx
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
	CopyFrom(ctx context.Context, tableName pgx.Identifier, columnName []string, rowSvc pgx.CopyFromSource) (int64, error)
	LargeObjects() pgx.LargeObjects
	Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error)
	Conn() *pgx.Conn

	// pgx.PgxPool
	Close()
	Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
	QueryFunc(ctx context.Context, sql string, args []interface{}, scans []interface{}, f func(pgx.QueryFuncRow) error) (pgconn.CommandTag, error)
	SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
	Begin(ctx context.Context) (pgx.Tx, error)
	BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)
	BeginFunc(ctx context.Context, f func(pgx.Tx) error) error
	BeginTxFunc(ctx context.Context, txOptions pgx.TxOptions, f func(pgx.Tx) error) error
}

Implements pgxpool.PgxPool and pgx.Tx

type PgxPool

type PgxPool interface {
	Close()
	Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
	QueryFunc(ctx context.Context, sql string, args []interface{}, scans []interface{}, f func(pgx.QueryFuncRow) error) (pgconn.CommandTag, error)
	SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
	Begin(ctx context.Context) (pgx.Tx, error)
	BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error)
	BeginFunc(ctx context.Context, f func(pgx.Tx) error) error
	BeginTxFunc(ctx context.Context, txOptions pgx.TxOptions, f func(pgx.Tx) error) error
}

type QueryContainsMatcher added in v1.1.3

type QueryContainsMatcher struct {
	// contains filtered or unexported fields
}

QueryContainsMatcher implements the gomock matcher interface (https://pkg.go.dev/github.com/golang/mock/gomock#Matcher) to match a string (SQL query) that contains the given string. This is useful for passing into pgxpoolmock.MockPgxIface as the SQL query string argument since SQLC generated code will contain the associated function name as well.

Usage: pgxMock.EXPECT().QueryRow(gomock.Any(), QueryContains("GetSomething")).Return(NewRow(1, "foo"))

func (*QueryContainsMatcher) Matches added in v1.1.3

func (m *QueryContainsMatcher) Matches(x interface{}) bool

func (*QueryContainsMatcher) String added in v1.1.3

func (m *QueryContainsMatcher) String() string

type Row

type Row struct {
	// contains filtered or unexported fields
}

Row implements the pgx.Row interface and can be passed into pgxpoolmock.PgxPoolMock.QueryRow as the expected returned row.

Usage: pgxMock.EXPECT().QueryRow(gomock.Any(), HasString("GetEntityByID")).Return(NewRow(1, "foo"))

func NewRow

func NewRow(values ...interface{}) *Row

func (*Row) Scan

func (r *Row) Scan(dest ...interface{}) error

func (*Row) WithError added in v1.1.4

func (r *Row) WithError(err error) *Row

type Rows

type Rows struct {
	// contains filtered or unexported fields
}

Rows is a mocked collection of rows to return for Query result

func NewRows

func NewRows(columns []string) *Rows

NewMockRows allows Rows to be created from a sql interface{} slice or from the CSV string and to be used as sql driver.Rows. Use Sqlmock.NewRows instead if using a custom converter

func NewRowsWithColumnDefinition

func NewRowsWithColumnDefinition(columns ...pgproto3.FieldDescription) *Rows

NewRowsWithColumnDefinition return rows with columns metadata

func (*Rows) AddRow

func (r *Rows) AddRow(values ...interface{}) *Rows

AddRow composed from database interface{} slice return the same instance to perform subsequent actions. Note that the number of values must match the number of columns

func (*Rows) CloseError

func (r *Rows) CloseError(err error) *Rows

CloseError allows to set an error which will be returned by rows.Close function.

The close error will be triggered only in cases when rows.Next() EOF was not yet reached, that is a default sql library behavior

func (*Rows) FromCSVString

func (r *Rows) FromCSVString(s string) *Rows

FromCSVString build rows from csv string. return the same instance to perform subsequent actions. Note that the number of values must match the number of columns

func (*Rows) RowError

func (r *Rows) RowError(row int, err error) *Rows

RowError allows to set an error which will be returned when a given row number is read

func (*Rows) ToPgxRows

func (r *Rows) ToPgxRows() pgx.Rows

Directories

Path Synopsis
Code generated by sqlc.
Code generated by sqlc.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL