Skip to content

Commit

Permalink
Merge pull request #121 from pashagolub/120-expectedcopyfromstring-ou…
Browse files Browse the repository at this point in the history
…tputs-table-name-instead-of-columns-names

[-] fix `ExpectedCopyFrom.String()` output, resolves #120
  • Loading branch information
pashagolub authored Dec 4, 2022
2 parents 106a759 + 8485c59 commit 64ed29d
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 56 deletions.
2 changes: 1 addition & 1 deletion expectations.go
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ func (e *ExpectedCopyFrom) WillDelayFor(duration time.Duration) *ExpectedCopyFro
func (e *ExpectedCopyFrom) String() string {
msg := "ExpectedCopyFrom => expecting CopyFrom which:"
msg += "\n - matches table name: '" + e.expectedTableName + "'"
msg += fmt.Sprintf("\n - matches column names: '%+v'", e.expectedTableName)
msg += fmt.Sprintf("\n - matches column names: '%+v'", e.expectedColumns)

if e.err != nil {
msg += fmt.Sprintf("\n - should return error: %s", e.err)
Expand Down
45 changes: 44 additions & 1 deletion expectations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ package pgxmock

import (
"context"
"errors"
"fmt"
"reflect"
"testing"
"time"

"github.com/jackc/pgx/v5"
)

func ExampleExpectedExec() {
Expand All @@ -25,6 +29,45 @@ func TestUnmonitoredPing(t *testing.T) {
}
}

func TestUnexpectedPing(t *testing.T) {
mock, _ := NewConn(MonitorPingsOption(true))
err := mock.Ping(context.Background())
if err == nil {
t.Error("Ping should return error for unexpected call")
}
mock.ExpectExec("foo")
err = mock.Ping(context.Background())
if err == nil {
t.Error("Ping should return error for unexpected call")
}
}

func TestUnexpectedPrepare(t *testing.T) {
mock, _ := NewConn()
_, err := mock.Prepare(context.Background(), "foo", "bar")
if err == nil {
t.Error("Prepare should return error for unexpected call")
}
mock.ExpectExec("foo")
_, err = mock.Prepare(context.Background(), "foo", "bar")
if err == nil {
t.Error("Prepare should return error for unexpected call")
}
}

func TestUnexpectedCopyFrom(t *testing.T) {
mock, _ := NewConn()
_, err := mock.CopyFrom(context.Background(), pgx.Identifier{"schema", "table"}, []string{"foo", "bar"}, nil)
if err == nil {
t.Error("CopyFrom should return error for unexpected call")
}
mock.ExpectExec("foo")
_, err = mock.CopyFrom(context.Background(), pgx.Identifier{"schema", "table"}, []string{"foo", "bar"}, nil)
if err == nil {
t.Error("CopyFrom should return error for unexpected call")
}
}

func TestBuildQuery(t *testing.T) {
mock, _ := NewConn(MonitorPingsOption(true))
query := `
Expand All @@ -41,7 +84,7 @@ func TestBuildQuery(t *testing.T) {
`

mock.ExpectPing()
mock.ExpectPing().WillDelayFor(1 * time.Second).WillReturnError(errors.New("no ping please"))
mock.ExpectQuery(query)
mock.ExpectExec(query)
mock.ExpectPrepare("foo", query)
Expand Down
39 changes: 5 additions & 34 deletions pgxmock.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,23 +50,23 @@ type pgxMockIface interface {
// the *ExpectedExec allows to mock database response
ExpectExec(expectedSQL string) *ExpectedExec

// ExpectBegin expects *sql.DB.Begin to be called.
// ExpectBegin expects pgx.Conn.Begin to be called.
// the *ExpectedBegin allows to mock database response
ExpectBegin() *ExpectedBegin

// ExpectBeginTx expects expects BeginTxFunc() to be called with expectedSQL
// ExpectBeginTx expects expects BeginTx() to be called with expectedSQL
// query. The *ExpectedBegin allows to mock database response.
ExpectBeginTx(txOptions pgx.TxOptions) *ExpectedBegin

// ExpectCommit expects *sql.Tx.Commit to be called.
// ExpectCommit expects pgx.Tx.Commit to be called.
// the *ExpectedCommit allows to mock database response
ExpectCommit() *ExpectedCommit

// ExpectRollback expects *sql.Tx.Rollback to be called.
// ExpectRollback expects pgx.Tx.Rollback to be called.
// the *ExpectedRollback allows to mock database response
ExpectRollback() *ExpectedRollback

// ExpectPing expected *sql.DB.Ping to be called.
// ExpectPing expected pgx.Conn.Ping to be called.
// the *ExpectedPing allows to mock database response
//
// Ping support only exists in the SQL library in Go 1.8 and above.
Expand Down Expand Up @@ -421,35 +421,6 @@ func (c *pgxmock) LargeObjects() pgx.LargeObjects {
return pgx.LargeObjects{}
}

func (c *pgxmock) BeginFunc(ctx context.Context, f func(pgx.Tx) error) (err error) {
return c.BeginTxFunc(ctx, pgx.TxOptions{}, f)
}

func (c *pgxmock) BeginTxFunc(ctx context.Context, txOptions pgx.TxOptions, f func(pgx.Tx) error) (err error) {
var tx pgx.Tx
tx, err = c.BeginTx(ctx, txOptions)
if err != nil {
return err
}
defer func() {
if err == nil {
return
}
rollbackErr := tx.Rollback(ctx)
if !(rollbackErr == nil || errors.Is(rollbackErr, pgx.ErrTxClosed)) {
err = rollbackErr
}
}()

fErr := f(tx)
if fErr != nil {
_ = tx.Rollback(ctx) // ignore rollback error as there is already an error to return
return fErr
}

return tx.Commit(ctx)
}

func (c *pgxmock) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) {
ex, err := c.begin(txOptions)
if ex != nil {
Expand Down
44 changes: 24 additions & 20 deletions pgxmock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func TestMockCopyFrom(t *testing.T) {
defer mock.Close(context.Background())

mock.ExpectCopyFrom(`"fooschema"."baztable"`, []string{"col1"}).
WillReturnResult(2)
WillReturnResult(2).WillDelayFor(1 * time.Second)

_, err = mock.CopyFrom(context.Background(), pgx.Identifier{"error", "error"}, []string{"error"}, nil)
if err == nil {
Expand All @@ -135,6 +135,14 @@ func TestMockCopyFrom(t *testing.T) {
t.Errorf("expected RowsAffected to be 2, but got %d instead", rows)
}

mock.ExpectCopyFrom(`"fooschema"."baztable"`, []string{"col1"}).
WillReturnError(errors.New("error is here"))

_, err = mock.CopyFrom(context.Background(), pgx.Identifier{"fooschema", "baztable"}, []string{"col1"}, nil)
if err == nil {
t.Error("error is expected while executing CopyFrom")
}

if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
Expand Down Expand Up @@ -229,24 +237,6 @@ func TestTransactionExpectations(t *testing.T) {
t.Errorf("an error '%s' was not expected when committing a transaction", err)
}

// // beginTxFunc and commit
// mock.ExpectBeginTx(pgx.TxOptions{})
// mock.ExpectCommit()

// err = mock.BeginFunc(context.Background(), func(tx pgx.Tx) error { return nil })
// if err != nil {
// t.Errorf("an error '%s' was not expected when beginning a transaction", err)
// }

// // beginTxFunc and rollback
// mock.ExpectBeginTx(pgx.TxOptions{})
// mock.ExpectRollback()

// err = mock.BeginFunc(context.Background(), func(tx pgx.Tx) error { return errors.New("smth wrong") })
// if err == nil {
// t.Error("an error was expected whithin a transaction, but got none")
// }

// begin and rollback
mock.ExpectBegin()
mock.ExpectRollback()
Expand Down Expand Up @@ -282,7 +272,9 @@ func TestPrepareExpectations(t *testing.T) {
}
defer mock.Close(context.Background())

mock.ExpectPrepare("foo", "SELECT (.+) FROM articles WHERE id = ?")
mock.ExpectPrepare("foo", "SELECT (.+) FROM articles WHERE id = ?").
WillDelayFor(1 * time.Second).
WillReturnCloseError(errors.New("invaders must die"))

stmt, err := mock.Prepare(context.Background(), "foo", "SELECT (.+) FROM articles WHERE id = $1")
if err != nil {
Expand Down Expand Up @@ -1250,3 +1242,15 @@ func TestPgConn(t *testing.T) {

_ = mock.PgConn()
}

func TestNewRowsWithColumnDefinition(t *testing.T) {
mock, err := NewConn()
if err != nil {
t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
r := mock.NewRowsWithColumnDefinition(*mock.NewColumn("foo"))
if len(r.defs) != 1 {
t.Error("NewRows failed")
}
}

0 comments on commit 64ed29d

Please sign in to comment.