Skip to content

Commit

Permalink
[-] fix unordered batch expectations, fixes #207 (#208)
Browse files Browse the repository at this point in the history
  • Loading branch information
pashagolub authored Jun 11, 2024
1 parent 9ce8313 commit f0c7674
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
41 changes: 41 additions & 0 deletions batch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,44 @@ func TestExplicitBatch(t *testing.T) {

a.NoError(mock.ExpectationsWereMet())
}

func processBatch(db PgxPoolIface) error {
batch := &pgx.Batch{}
// Random order
batch.Queue("SELECT id FROM normalized_queries WHERE query = $1", "some query")
batch.Queue("INSERT INTO normalized_queries (query) VALUES ($1) RETURNING id", "some query")

results := db.SendBatch(ctx, batch)
defer results.Close()

for i := 0; i < batch.Len(); i++ {
var id int
err := results.QueryRow().Scan(&id)
if err != nil {
return err
}
}

return nil
}

func TestUnorderedBatchExpectations(t *testing.T) {
t.Parallel()
a := assert.New(t)

mock, err := NewPool()
a.NoError(err)
defer mock.Close()

mock.MatchExpectationsInOrder(false)

expectedBatch := mock.ExpectBatch()
expectedBatch.ExpectQuery("INSERT INTO").WithArgs("some query").
WillReturnRows(NewRows([]string{"id"}).AddRow(10))
expectedBatch.ExpectQuery("SELECT id").WithArgs("some query").
WillReturnRows(NewRows([]string{"id"}).AddRow(20))

err = processBatch(mock)
a.NoError(err)
a.NoError(mock.ExpectationsWereMet())
}
3 changes: 3 additions & 0 deletions pgxmock.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,9 @@ func (c *pgxmock) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
return fmt.Errorf("SendBatch: number of queries in batch '%d' was not expected, expected number of queries is '%d'",
len(b.QueuedQueries), len(batchExp.expectedQueries))
}
if !c.ordered { // postpone the check of every query until/if it is called
return nil
}
for i, query := range b.QueuedQueries {
if err := c.queryMatcher.Match(batchExp.expectedQueries[i].expectSQL, query.SQL); err != nil {
return err
Expand Down

0 comments on commit f0c7674

Please sign in to comment.