Skip to content

Commit

Permalink
clean up Eventually usage (#14776)
Browse files Browse the repository at this point in the history
Co-authored-by: Radek Scheibinger <[email protected]>
  • Loading branch information
jmank88 and scheibinger authored Oct 22, 2024
1 parent 3fc5805 commit 7d1dc96
Show file tree
Hide file tree
Showing 21 changed files with 93 additions and 92 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"time"

mapset "github.com/deckarep/golang-set/v2"
"github.com/onsi/gomega"

"github.com/smartcontractkit/chainlink/v2/core/capabilities/ccip/ccip_integration_tests/integrationhelpers"

Expand Down Expand Up @@ -56,10 +55,10 @@ func TestHomeChainReader_ChainConfigs(t *testing.T) {
require.Len(t, chainConfigInfos, len(inputConfig))

// Wait for the home chain reader to read the expected amount of chain configs.
gomega.NewWithT(t).Eventually(func() bool {
require.Eventually(t, func() bool {
configs, _ := uni.HomeChainReader.GetAllChainConfigs()
return len(configs) == len(inputConfig)
}, testutils.WaitTimeout(t), 1*time.Second).Should(gomega.BeTrue())
}, testutils.WaitTimeout(t), 1*time.Second)

t.Logf("homchain reader is ready")

Expand All @@ -85,10 +84,10 @@ func TestHomeChainReader_ChainConfigs(t *testing.T) {
uni.Backend.Commit()

// Wait for the home chain reader to read the expected amount of chain configs.
gomega.NewWithT(t).Eventually(func() bool {
require.Eventually(t, func() bool {
chainConfigs, _ := uni.HomeChainReader.GetAllChainConfigs()
return len(chainConfigs) == len(inputConfig)-1
}, testutils.WaitTimeout(t), 1*time.Second).Should(gomega.BeTrue())
}, testutils.WaitTimeout(t), 1*time.Second)
configs, err = uni.HomeChainReader.GetAllChainConfigs()
require.NoError(t, err)

Expand Down
5 changes: 2 additions & 3 deletions core/capabilities/ccip/launcher/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest"
p2ptypes "github.com/smartcontractkit/chainlink/v2/core/services/p2p/types"

"github.com/onsi/gomega"
"github.com/stretchr/testify/require"

"github.com/smartcontractkit/chainlink/v2/core/gethwrappers/ccip/generated/ccip_home"
Expand Down Expand Up @@ -90,9 +89,9 @@ func TestIntegration_Launcher(t *testing.T) {
it.FChainA,
p2pIDs)

gomega.NewWithT(t).Eventually(func() bool {
require.Eventually(t, func() bool {
return len(launcher.runningDONIDs()) == 1
}, testutils.WaitTimeout(t), testutils.TestInterval).Should(gomega.BeTrue())
}, testutils.WaitTimeout(t), testutils.TestInterval)
}

type oraclePrints struct {
Expand Down
9 changes: 4 additions & 5 deletions core/capabilities/ccip/ocrimpls/contract_transmitter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core"
"github.com/jmoiron/sqlx"
"github.com/onsi/gomega"
"github.com/stretchr/testify/require"

"github.com/smartcontractkit/libocr/commontypes"
Expand Down Expand Up @@ -140,7 +139,7 @@ func testTransmitter(
uni.backend.Commit()

var txStatus uint64
gomega.NewWithT(t).Eventually(func() bool {
require.Eventually(t, func() bool {
uni.backend.Commit()
rows, err := uni.db.QueryContext(testutils.Context(t), `SELECT hash FROM evm.tx_attempts LIMIT 1`)
require.NoError(t, err, "failed to query txes")
Expand All @@ -158,10 +157,10 @@ func testTransmitter(
t.Log("tx found:", hexutil.Encode(txHash), "status:", receipt.Status)
txStatus = receipt.Status
return true
}, testutils.WaitTimeout(t), 1*time.Second).Should(gomega.BeTrue())
}, testutils.WaitTimeout(t), 1*time.Second)

// wait for receipt to be written to the db
gomega.NewWithT(t).Eventually(func() bool {
require.Eventually(t, func() bool {
rows, err := uni.db.QueryContext(testutils.Context(t), `SELECT count(*) as cnt FROM evm.receipts LIMIT 1`)
require.NoError(t, err, "failed to query receipts")
defer rows.Close()
Expand All @@ -170,7 +169,7 @@ func testTransmitter(
require.NoError(t, rows.Scan(&count), "failed to scan")
}
return count == 1
}, testutils.WaitTimeout(t), 2*time.Second).Should(gomega.BeTrue())
}, testutils.WaitTimeout(t), 2*time.Second)

require.Equal(t, uint64(1), txStatus, "tx status should be success")

Expand Down
4 changes: 2 additions & 2 deletions core/chains/evm/headtracker/head_tracker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -524,11 +524,11 @@ func TestHeadTracker_Start_LoadsLatestChain(t *testing.T) {
headers.TrySend(testutils.Head(1))
}()

gomega.NewWithT(t).Eventually(func() bool {
require.Eventually(t, func() bool {
report := ht.headTracker.HealthReport()
services.CopyHealth(report, ht.headBroadcaster.HealthReport())
return !slices.ContainsFunc(maps.Values(report), func(e error) bool { return e != nil })
}, 5*time.Second, tests.TestInterval).Should(gomega.Equal(true))
}, 5*time.Second, tests.TestInterval)

h, err := orm.LatestHead(tests.Context(t))
require.NoError(t, err)
Expand Down
4 changes: 2 additions & 2 deletions core/chains/evm/logpoller/log_poller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ func TestLogPoller_Integration(t *testing.T) {
require.Equal(t, 4, len(logs))

// Once the backup poller runs we should also have the log from block 3
testutils.AssertEventually(t, func() bool {
testutils.RequireEventually(t, func() bool {
l, err2 := th.LogPoller.Logs(ctx, 3, 3, EmitterABI.Events["Log1"].ID, th.EmitterAddress1)
require.NoError(t, err2)
return len(l) == 1
Expand Down Expand Up @@ -1518,7 +1518,7 @@ func TestLogPoller_DBErrorHandling(t *testing.T) {

time.Sleep(100 * time.Millisecond)
require.NoError(t, lp.Start(ctx))
testutils.AssertEventually(t, func() bool {
testutils.RequireEventually(t, func() bool {
return observedLogs.Len() >= 1
})
err = lp.Close()
Expand Down
4 changes: 3 additions & 1 deletion core/chains/evm/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/multierr"

"github.com/smartcontractkit/chainlink-common/pkg/utils/tests"
Expand Down Expand Up @@ -211,6 +212,7 @@ func TestRetryWithBackoff(t *testing.T) {

var counter atomic.Int32
ctx, cancel := context.WithCancel(tests.Context(t))
defer cancel()

utils.RetryWithBackoff(ctx, func() bool {
return false
Expand All @@ -222,7 +224,7 @@ func TestRetryWithBackoff(t *testing.T) {

go utils.RetryWithBackoff(ctx, retry)

assert.Eventually(t, func() bool {
require.Eventually(t, func() bool {
return counter.Load() == 3
}, tests.WaitTimeout(t), tests.TestInterval)

Expand Down
2 changes: 1 addition & 1 deletion core/cmd/cosmos_transaction_commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func TestShell_SendCosmosCoins(t *testing.T) {
require.NoError(t, err)
expBal := startBal.Sub(sent)

testutils.AssertEventually(t, func() bool {
testutils.RequireEventually(t, func() bool {
endBal, err := reader.Balance(ctx, from.Address, *cosmosChain.GasToken)
require.NoError(t, err)
t.Logf("%s <= %s", endBal, expBal)
Expand Down
18 changes: 9 additions & 9 deletions core/internal/cltest/cltest.go
Original file line number Diff line number Diff line change
Expand Up @@ -973,11 +973,13 @@ func WaitForSpecErrorV2(t *testing.T, ds sqlutil.DataSource, jobID int32, count

g := gomega.NewWithT(t)
var jse []job.SpecError
g.Eventually(func() []job.SpecError {
if !g.Eventually(func() []job.SpecError {
err := ds.SelectContext(ctx, &jse, `SELECT * FROM job_spec_errors WHERE job_id = $1`, jobID)
assert.NoError(t, err)
return jse
}, testutils.WaitTimeout(t), DBPollingInterval).Should(gomega.HaveLen(count))
}, testutils.WaitTimeout(t), DBPollingInterval).Should(gomega.HaveLen(count)) {
t.Fatal()
}
return jse
}

Expand Down Expand Up @@ -1527,14 +1529,13 @@ func AssertCount(t *testing.T, ds sqlutil.DataSource, tableName string, expected
func WaitForCount(t *testing.T, ds sqlutil.DataSource, tableName string, want int64) {
t.Helper()
ctx := testutils.Context(t)
g := gomega.NewWithT(t)
var count int64
var err error
g.Eventually(func() int64 {
require.Eventually(t, func() bool {
err = ds.GetContext(ctx, &count, fmt.Sprintf(`SELECT count(*) FROM %s;`, tableName))
assert.NoError(t, err)
return count
}, testutils.WaitTimeout(t), DBPollingInterval).Should(gomega.Equal(want))
return count == want
}, testutils.WaitTimeout(t), DBPollingInterval)
}

func AssertCountStays(t testing.TB, ds sqlutil.DataSource, tableName string, want int64) {
Expand All @@ -1553,12 +1554,11 @@ func AssertCountStays(t testing.TB, ds sqlutil.DataSource, tableName string, wan
func AssertRecordEventually(t *testing.T, ds sqlutil.DataSource, model interface{}, stmt string, check func() bool) {
t.Helper()
ctx := testutils.Context(t)
g := gomega.NewWithT(t)
g.Eventually(func() bool {
require.Eventually(t, func() bool {
err := ds.GetContext(ctx, model, stmt)
require.NoError(t, err, "unable to find record in DB")
return check()
}, testutils.WaitTimeout(t), DBPollingInterval).Should(gomega.BeTrue())
}, testutils.WaitTimeout(t), DBPollingInterval)
}

func MustWebURL(t *testing.T, s string) *models.WebURL {
Expand Down
6 changes: 3 additions & 3 deletions core/internal/features/features_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1359,11 +1359,11 @@ func TestIntegration_BlockHistoryEstimator(t *testing.T) {
h43.ParentHash = h42.Hash
newHeads.TrySend(h43)

gomega.NewWithT(t).Eventually(func() string {
require.Eventually(t, func() bool {
gasPrice, _, err := estimator.GetFee(testutils.Context(t), nil, 500000, maxGasPrice, nil, nil)
require.NoError(t, err)
return gasPrice.GasPrice.String()
}, testutils.WaitTimeout(t), cltest.DBPollingInterval).Should(gomega.Equal("45 gwei"))
return gasPrice.GasPrice.String() == "45 gwei"
}, testutils.WaitTimeout(t), cltest.DBPollingInterval)
}

func triggerAllKeys(t *testing.T, app *cltest.TestApplication) {
Expand Down
17 changes: 11 additions & 6 deletions core/internal/testutils/testutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,9 +342,14 @@ func IntToHex(n int) string {
// risk of spamming
const TestInterval = 100 * time.Millisecond

// AssertEventually waits for f to return true
func AssertEventually(t *testing.T, f func() bool) {
assert.Eventually(t, f, WaitTimeout(t), TestInterval/2)
// AssertEventually calls assert.Eventually with default wait and tick durations.
func AssertEventually(t *testing.T, f func() bool) bool {
return assert.Eventually(t, f, WaitTimeout(t), TestInterval/2)
}

// RequireEventually calls assert.Eventually with default wait and tick durations.
func RequireEventually(t *testing.T, f func() bool) {
require.Eventually(t, f, WaitTimeout(t), TestInterval/2)
}

// RequireLogMessage fails the test if emitted logs don't contain the given message
Expand All @@ -368,7 +373,7 @@ func RequireLogMessage(t *testing.T, observedLogs *observer.ObservedLogs, msg st
// observedZapCore, observedLogs := observer.New(zap.DebugLevel)
// lggr := logger.TestLogger(t, observedZapCore)
func WaitForLogMessage(t *testing.T, observedLogs *observer.ObservedLogs, msg string) (le observer.LoggedEntry) {
AssertEventually(t, func() bool {
RequireEventually(t, func() bool {
for _, l := range observedLogs.All() {
if strings.Contains(l.Message, msg) {
le = l
Expand All @@ -381,7 +386,7 @@ func WaitForLogMessage(t *testing.T, observedLogs *observer.ObservedLogs, msg st
}

func WaitForLogMessageWithField(t *testing.T, observedLogs *observer.ObservedLogs, msg, field, value string) (le observer.LoggedEntry) {
AssertEventually(t, func() bool {
RequireEventually(t, func() bool {
for _, l := range observedLogs.All() {
if strings.Contains(l.Message, msg) && strings.Contains(l.ContextMap()[field].(string), value) {
le = l
Expand All @@ -396,7 +401,7 @@ func WaitForLogMessageWithField(t *testing.T, observedLogs *observer.ObservedLog
// WaitForLogMessageCount waits until at least count log message containing the
// specified msg is emitted
func WaitForLogMessageCount(t *testing.T, observedLogs *observer.ObservedLogs, msg string, count int) {
AssertEventually(t, func() bool {
RequireEventually(t, func() bool {
i := 0
for _, l := range observedLogs.All() {
if strings.Contains(l.Message, msg) {
Expand Down
2 changes: 1 addition & 1 deletion core/services/blockhashstore/delegate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func TestDelegate_StartStop(t *testing.T) {
err = services[0].Start(testutils.Context(t))
require.NoError(t, err)

assert.Eventually(t, func() bool {
require.Eventually(t, func() bool {
return testData.logs.FilterMessage("Starting BHS feeder").Len() > 0 &&
testData.logs.FilterMessage("Running BHS feeder").Len() > 0 &&
testData.logs.FilterMessage("BHS feeder run completed successfully").Len() > 0
Expand Down
3 changes: 1 addition & 2 deletions core/services/fluxmonitorv2/flux_monitor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/onsi/gomega"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"gopkg.in/guregu/null.v4"
Expand Down Expand Up @@ -1308,7 +1307,7 @@ func TestFluxMonitor_UsesPreviousRoundStateOnStartup_IdleTimer(t *testing.T) {

servicetest.Run(t, fm)

assert.Eventually(t, func() bool { return len(initialPollOccurred) == 1 }, 3*time.Second, 10*time.Millisecond)
require.Eventually(t, func() bool { return len(initialPollOccurred) == 1 }, 3*time.Second, 10*time.Millisecond)

if tc.expectedToSubmit {
g.Eventually(chRoundState).Should(gomega.BeClosed())
Expand Down
11 changes: 5 additions & 6 deletions core/services/job/spawner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"testing"
"time"

"github.com/onsi/gomega"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -247,11 +246,11 @@ func TestSpawner_CreateJobDeleteJob(t *testing.T) {
eventuallyStart.AwaitOrFail(t)

// Wait for the claim lock to be taken
gomega.NewWithT(t).Eventually(func() bool {
require.Eventually(t, func() bool {
jobs := spawner.ActiveJobs()
_, exists := jobs[jobSpecIDA]
return exists
}, testutils.WaitTimeout(t), cltest.DBPollingInterval).Should(gomega.Equal(true))
}, testutils.WaitTimeout(t), cltest.DBPollingInterval)

eventuallyClose := cltest.NewAwaiter()
serviceA1.On("Close").Return(nil).Once()
Expand All @@ -263,11 +262,11 @@ func TestSpawner_CreateJobDeleteJob(t *testing.T) {
eventuallyClose.AwaitOrFail(t)

// Wait for the claim lock to be released
gomega.NewWithT(t).Eventually(func() bool {
require.Eventually(t, func() bool {
jobs := spawner.ActiveJobs()
_, exists := jobs[jobSpecIDA]
return exists
}, testutils.WaitTimeout(t), cltest.DBPollingInterval).Should(gomega.Equal(false))
return !exists
}, testutils.WaitTimeout(t), cltest.DBPollingInterval)

clearDB(t, db)
})
Expand Down
7 changes: 3 additions & 4 deletions core/services/keeper/orm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"time"

"github.com/ethereum/go-ethereum/common"
"github.com/onsi/gomega"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -57,11 +56,11 @@ func newUpkeep(registry keeper.Registry, upkeepID int64) keeper.UpkeepRegistrati
func waitLastRunHeight(t *testing.T, db *sqlx.DB, upkeep keeper.UpkeepRegistration, height int64) {
t.Helper()

gomega.NewWithT(t).Eventually(func() int64 {
require.Eventually(t, func() bool {
err := db.Get(&upkeep, `SELECT * FROM upkeep_registrations WHERE id = $1`, upkeep.ID)
require.NoError(t, err)
return upkeep.LastRunBlockHeight
}, time.Second*2, time.Millisecond*100).Should(gomega.Equal(height))
return upkeep.LastRunBlockHeight == height
}, time.Second*2, time.Millisecond*100)
}

func assertLastRunHeight(t *testing.T, db *sqlx.DB, upkeep keeper.UpkeepRegistration, lastRunBlockHeight int64, lastKeeperIndex int64) {
Expand Down
Loading

0 comments on commit 7d1dc96

Please sign in to comment.