Skip to content

Commit

Permalink
Add test for ExecPagedQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
reductionista committed Sep 29, 2024
1 parent 5de9bd4 commit 58d42c9
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions core/chains/evm/logpoller/orm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"math"
"math/big"
"strconv"
"testing"
"time"

"github.com/stretchr/testify/mock"

"github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest"

"github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -1155,6 +1158,69 @@ func TestORM_SelectLogsWithSigsByBlockRangeFilter(t *testing.T) {
assertion(t, logs, err, startBlock, endBlock)
}

type mockQueryExecutor struct {
mock.Mock
}

func (m *mockQueryExecutor) Exec(limitBlock int64) (int64, error) {
res := m.Called(limitBlock)
return int64(res.Int(0)), res.Error(1)
}

func TestORM_ExecPagedQuery(t *testing.T) {
t.Parallel()
ctx := testutils.Context(t)
lggr := logger.Test(t)
chainID := testutils.NewRandomEVMChainID()
db := pgtest.NewSqlxDB(t)
o := logpoller.NewORM(chainID, db, lggr)

m := mockQueryExecutor{}

queryError := errors.New("some error")
m.On("Exec", int64(0)).Return(0, queryError).Once()

// Should handle errors gracefully
_, err := o.ExecPagedQuery(ctx, 0, 0, m.Exec)
assert.ErrorIs(t, err, queryError)

m.On("Exec", int64(60)).Return(4, nil).Once()

// Query should only get executed once with limitBlock=end if called with limit=0
numResults, err := o.ExecPagedQuery(ctx, 0, 60, m.Exec)
require.NoError(t, err)
assert.Equal(t, int64(4), numResults)

// Should report actual db errors
_, err = o.ExecPagedQuery(ctx, 300, 1000, m.Exec)
assert.Error(t, err)

o.InsertBlock(ctx, common.HexToHash("0x1234"), 42, time.Now(), 0)

m.On("Exec", mock.Anything).Return(3, nil)

// Should get called with limitBlock = 342, 642, 942, 1000
numResults, err = o.ExecPagedQuery(ctx, 300, 1000, m.Exec)
require.NoError(t, err)
assert.Equal(t, int64(12), numResults) // 3 results in each of 4 calls
m.AssertNumberOfCalls(t, "Exec", 6) // 4 new calls, plus the prior 2
expectedLimitBlocks := []int64{341, 641, 941, 1000}
for _, expected := range expectedLimitBlocks {
m.AssertCalled(t, "Exec", expected)
}

// Should not go all the way to 1000, but stop after ~ 13 results have
// been returned
numResults, err = o.ExecPagedQuery(ctx, 15, 1000, m.Exec)
require.NoError(t, err)
assert.Equal(t, int64(15), numResults)
m.AssertNumberOfCalls(t, "Exec", 11)
expectedLimitBlocks = []int64{56, 71, 86, 101, 116} // 42 + 15 * n - 1 for n = 1, 2, 3, 4, 5
for _, expected := range expectedLimitBlocks {
m.AssertCalled(t, "Exec", expected)
}
}

func TestORM_DeleteBlocksBefore(t *testing.T) {
th := SetupTH(t, lpOpts)
o1 := th.ORM
Expand Down

0 comments on commit 58d42c9

Please sign in to comment.