diff --git a/core/chains/evm/gas/arbitrum_estimator_test.go b/core/chains/evm/gas/arbitrum_estimator_test.go index 53f81617988..9d56e2c10ad 100644 --- a/core/chains/evm/gas/arbitrum_estimator_test.go +++ b/core/chains/evm/gas/arbitrum_estimator_test.go @@ -15,6 +15,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/gas" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/gas/mocks" @@ -66,8 +67,7 @@ func TestArbitrumEstimator(t *testing.T) { }).Return(zeros.Bytes(), nil) o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{v: maxGasLimit}, rpcClient, ethClient) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, maxGasPrice) require.NoError(t, err) // Expected price for a standard l2_suggested_estimator would be 42, but we add a fixed gasPriceBufferPercentage. @@ -92,8 +92,7 @@ func TestArbitrumEstimator(t *testing.T) { assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(zeros.Bytes(), nil) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, assets.NewWeiI(40)) require.Error(t, err) assert.EqualError(t, err, "estimated gas price: 42 wei is greater than the maximum gas price configured: 40 wei") @@ -118,8 +117,7 @@ func TestArbitrumEstimator(t *testing.T) { assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(zeros.Bytes(), nil) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, assets.NewWeiI(110)) assert.EqualError(t, err, "estimated gas price: 120 wei is greater than the maximum gas price configured: 110 wei") assert.Nil(t, gasPrice) @@ -148,8 +146,7 @@ func TestArbitrumEstimator(t *testing.T) { assert.Equal(t, big.NewInt(-1), blockNumber) }).Return(zeros.Bytes(), nil) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) _, _, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, maxGasPrice) assert.EqualError(t, err, "failed to estimate gas; gas price not set") @@ -181,8 +178,7 @@ func TestArbitrumEstimator(t *testing.T) { }).Return(b.Bytes(), nil) o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{v: maxGasLimit}, rpcClient, ethClient) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, maxGasPrice) require.NoError(t, err) require.NotNil(t, gasPrice) @@ -216,8 +212,7 @@ func TestArbitrumEstimator(t *testing.T) { }).Return(b.Bytes(), nil) o := gas.NewArbitrumEstimator(logger.Test(t), &arbConfig{v: maxGasLimit}, rpcClient, ethClient) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, maxGasPrice) require.Error(t, err, "expected error but got (%s, %d)", gasPrice, chainSpecificGasLimit) }) diff --git a/core/chains/evm/gas/rollups/l1_gas_price_oracle_test.go b/core/chains/evm/gas/rollups/l1_gas_price_oracle_test.go index 2defedd6b47..1a1d1ffdeee 100644 --- a/core/chains/evm/gas/rollups/l1_gas_price_oracle_test.go +++ b/core/chains/evm/gas/rollups/l1_gas_price_oracle_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/common/config" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" @@ -50,8 +51,7 @@ func TestL1GasPriceOracle(t *testing.T) { }).Return(common.BigToHash(l1BaseFee).Bytes(), nil) oracle := NewL1GasPriceOracle(logger.Test(t), ethClient, config.ChainArbitrum) - require.NoError(t, oracle.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, oracle.Close()) }) + servicetest.RunHealthy(t, oracle) gasPrice, err := oracle.GasPrice(testutils.Context(t)) require.NoError(t, err) @@ -72,8 +72,7 @@ func TestL1GasPriceOracle(t *testing.T) { }).Return(common.BigToHash(l1BaseFee).Bytes(), nil) oracle := NewL1GasPriceOracle(logger.Test(t), ethClient, config.ChainKroma) - require.NoError(t, oracle.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, oracle.Close()) }) + servicetest.RunHealthy(t, oracle) gasPrice, err := oracle.GasPrice(testutils.Context(t)) require.NoError(t, err) @@ -94,8 +93,7 @@ func TestL1GasPriceOracle(t *testing.T) { }).Return(common.BigToHash(l1BaseFee).Bytes(), nil) oracle := NewL1GasPriceOracle(logger.Test(t), ethClient, config.ChainOptimismBedrock) - require.NoError(t, oracle.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, oracle.Close()) }) + servicetest.RunHealthy(t, oracle) gasPrice, err := oracle.GasPrice(testutils.Context(t)) require.NoError(t, err) diff --git a/core/chains/evm/gas/suggested_price_estimator_test.go b/core/chains/evm/gas/suggested_price_estimator_test.go index 304e5359107..8e45f5b759a 100644 --- a/core/chains/evm/gas/suggested_price_estimator_test.go +++ b/core/chains/evm/gas/suggested_price_estimator_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/gas" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/gas/mocks" @@ -40,8 +41,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { }) o := gas.NewSuggestedPriceEstimator(logger.Test(t), client) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, maxGasPrice) require.NoError(t, err) assert.Equal(t, assets.NewWeiI(42), gasPrice) @@ -57,8 +57,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { (*big.Int)(res).SetInt64(42) }) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, assets.NewWeiI(40)) require.Error(t, err) assert.EqualError(t, err, "estimated gas price: 42 wei is greater than the maximum gas price configured: 40 wei") @@ -75,8 +74,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { (*big.Int)(res).SetInt64(120) }) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) gasPrice, chainSpecificGasLimit, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, assets.NewWeiI(110)) assert.EqualError(t, err, "estimated gas price: 120 wei is greater than the maximum gas price configured: 110 wei") assert.Nil(t, gasPrice) @@ -96,8 +94,7 @@ func TestSuggestedPriceEstimator(t *testing.T) { client.On("CallContext", mock.Anything, mock.Anything, "eth_gasPrice").Return(errors.New("kaboom")) - require.NoError(t, o.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, o.Close()) }) + servicetest.RunHealthy(t, o) _, _, err := o.GetLegacyGas(testutils.Context(t), calldata, gasLimit, maxGasPrice) assert.EqualError(t, err, "failed to estimate gas; gas price not set") diff --git a/core/chains/evm/headtracker/head_broadcaster_test.go b/core/chains/evm/headtracker/head_broadcaster_test.go index 6fb151bfe6c..ac43c08fe87 100644 --- a/core/chains/evm/headtracker/head_broadcaster_test.go +++ b/core/chains/evm/headtracker/head_broadcaster_test.go @@ -11,6 +11,8 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + commonhtrk "github.com/smartcontractkit/chainlink/v2/common/headtracker" commonmocks "github.com/smartcontractkit/chainlink/v2/common/types/mocks" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/headtracker" @@ -21,7 +23,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/evmtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" - "github.com/smartcontractkit/chainlink/v2/core/services" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/store/models" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -68,14 +69,14 @@ func TestHeadBroadcaster_Subscribe(t *testing.T) { checker1 := &cltest.MockHeadTrackable{} checker2 := &cltest.MockHeadTrackable{} - hb := headtracker.NewHeadBroadcaster(logger) orm := headtracker.NewORM(db, logger, cfg.Database(), *ethClient.ConfiguredChainID()) hs := headtracker.NewHeadSaver(logger, orm, evmCfg.EVM(), evmCfg.EVM().HeadTracker()) mailMon := utils.NewMailboxMonitor(t.Name()) + servicetest.Run(t, mailMon) + hb := headtracker.NewHeadBroadcaster(logger) + servicetest.Run(t, hb) ht := headtracker.NewHeadTracker(logger, ethClient, evmCfg.EVM(), evmCfg.EVM().HeadTracker(), hb, hs, mailMon) - var ms services.MultiStart - require.NoError(t, ms.Start(testutils.Context(t), mailMon, hb, ht)) - t.Cleanup(func() { require.NoError(t, services.CloseAll(mailMon, hb, ht)) }) + servicetest.Run(t, ht) latest1, unsubscribe1 := hb.Subscribe(checker1) // "latest head" is nil here because we didn't receive any yet diff --git a/core/chains/evm/log/helpers_test.go b/core/chains/evm/log/helpers_test.go index 49f9266f705..e41f08e8d20 100644 --- a/core/chains/evm/log/helpers_test.go +++ b/core/chains/evm/log/helpers_test.go @@ -22,6 +22,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" evmconfig "github.com/smartcontractkit/chainlink/v2/core/chains/evm/config" diff --git a/core/chains/evm/log/integration_test.go b/core/chains/evm/log/integration_test.go index 2d66cdf585c..e5b6ad3caf5 100644 --- a/core/chains/evm/log/integration_test.go +++ b/core/chains/evm/log/integration_test.go @@ -18,6 +18,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log" logmocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log/mocks" @@ -1324,7 +1325,7 @@ func TestBroadcaster_AppendLogChannel(t *testing.T) { ch3 := make(chan types.Log) ethClient := evmtest.NewEthClientMockWithDefaultChain(t) - mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.RunHealthy(t, utils.NewMailboxMonitor(t.Name())) lb := log.NewBroadcaster(nil, ethClient, nil, logger.Test(t), nil, mailMon) chCombined := lb.ExportedAppendLogChannel(ch1, ch2) chCombined = lb.ExportedAppendLogChannel(chCombined, ch3) diff --git a/core/chains/evm/logpoller/log_poller_internal_test.go b/core/chains/evm/logpoller/log_poller_internal_test.go index e3ba8b655e8..f840eefc7b8 100644 --- a/core/chains/evm/logpoller/log_poller_internal_test.go +++ b/core/chains/evm/logpoller/log_poller_internal_test.go @@ -22,6 +22,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" @@ -351,8 +352,7 @@ func TestLogPoller_Replay(t *testing.T) { ec.On("FilterLogs", mock.Anything, mock.Anything).Return([]types.Log{log1}, nil).Maybe() // in case task gets delayed by >= 100ms t.Cleanup(lp.reset) - require.NoError(t, lp.Start(ctx)) - t.Cleanup(func() { assert.NoError(t, lp.Close()) }) + servicetest.Run(t, lp) select { case <-ctx.Done(): @@ -389,8 +389,7 @@ func TestLogPoller_Replay(t *testing.T) { ec.On("FilterLogs", mock.Anything, mock.Anything).Return([]types.Log{log1}, nil).Maybe() // in case task gets delayed by >= 100ms t.Cleanup(lp.reset) - require.NoError(t, lp.Start(ctx)) - t.Cleanup(func() { assert.NoError(t, lp.Close()) }) + servicetest.Run(t, lp) select { case <-ctx.Done(): @@ -402,8 +401,7 @@ func TestLogPoller_Replay(t *testing.T) { // ReplayAsync should return as soon as replayStart is received t.Run("ReplayAsync success", func(t *testing.T) { t.Cleanup(lp.reset) - require.NoError(t, lp.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, lp.Close()) }) + servicetest.Run(t, lp) lp.ReplayAsync(1) @@ -412,8 +410,7 @@ func TestLogPoller_Replay(t *testing.T) { t.Run("ReplayAsync error", func(t *testing.T) { t.Cleanup(lp.reset) - require.NoError(t, lp.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, lp.Close()) }) + servicetest.Run(t, lp) anyErr := errors.New("async error") observedLogs.TakeAll() diff --git a/core/chains/evm/monitor/balance_test.go b/core/chains/evm/monitor/balance_test.go index c2c976e78da..246d5d0759f 100644 --- a/core/chains/evm/monitor/balance_test.go +++ b/core/chains/evm/monitor/balance_test.go @@ -14,6 +14,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/monitor" @@ -44,7 +45,6 @@ func TestBalanceMonitor_Start(t *testing.T) { _, k0Addr := cltest.MustInsertRandomKey(t, ethKeyStore) bm := monitor.NewBalanceMonitor(ethClient, ethKeyStore, logger.Test(t)) - defer func() { assert.NoError(t, bm.Close()) }() k0bal := big.NewInt(42) k1bal := big.NewInt(43) @@ -54,7 +54,7 @@ func TestBalanceMonitor_Start(t *testing.T) { ethClient.On("BalanceAt", mock.Anything, k0Addr, nilBigInt).Once().Return(k0bal, nil) ethClient.On("BalanceAt", mock.Anything, k1Addr, nilBigInt).Once().Return(k1bal, nil) - assert.NoError(t, bm.Start(testutils.Context(t))) + servicetest.RunHealthy(t, bm) gomega.NewWithT(t).Eventually(func() *big.Int { return bm.GetEthBalance(k0Addr).ToInt() @@ -72,12 +72,11 @@ func TestBalanceMonitor_Start(t *testing.T) { _, k0Addr := cltest.MustInsertRandomKey(t, ethKeyStore) bm := monitor.NewBalanceMonitor(ethClient, ethKeyStore, logger.Test(t)) - defer func() { assert.NoError(t, bm.Close()) }() k0bal := big.NewInt(42) ethClient.On("BalanceAt", mock.Anything, k0Addr, nilBigInt).Once().Return(k0bal, nil) - assert.NoError(t, bm.Start(testutils.Context(t))) + servicetest.RunHealthy(t, bm) gomega.NewWithT(t).Eventually(func() *big.Int { return bm.GetEthBalance(k0Addr).ToInt() @@ -92,7 +91,6 @@ func TestBalanceMonitor_Start(t *testing.T) { _, k0Addr := cltest.MustInsertRandomKey(t, ethKeyStore) bm := monitor.NewBalanceMonitor(ethClient, ethKeyStore, logger.Test(t)) - defer func() { assert.NoError(t, bm.Close()) }() ctxCancelledAwaiter := cltest.NewAwaiter() ethClient.On("BalanceAt", mock.Anything, k0Addr, nilBigInt).Once().Run(func(args mock.Arguments) { @@ -122,13 +120,12 @@ func TestBalanceMonitor_Start(t *testing.T) { _, k0Addr := cltest.MustInsertRandomKey(t, ethKeyStore) bm := monitor.NewBalanceMonitor(ethClient, ethKeyStore, logger.Test(t)) - defer func() { assert.NoError(t, bm.Close()) }() ethClient.On("BalanceAt", mock.Anything, k0Addr, nilBigInt). Once(). Return(nil, errors.New("a little easter egg for the 4chan link marines error")) - assert.NoError(t, bm.Start(testutils.Context(t))) + servicetest.RunHealthy(t, bm) gomega.NewWithT(t).Consistently(func() *big.Int { return bm.GetEthBalance(k0Addr).ToInt() @@ -160,8 +157,7 @@ func TestBalanceMonitor_OnNewLongestChain_UpdatesBalance(t *testing.T) { ethClient.On("BalanceAt", mock.Anything, k0Addr, nilBigInt).Once().Return(k0bal, nil) ethClient.On("BalanceAt", mock.Anything, k1Addr, nilBigInt).Once().Return(k1bal, nil) - require.NoError(t, bm.Start(testutils.Context(t))) - defer func() { assert.NoError(t, bm.Close()) }() + servicetest.RunHealthy(t, bm) ethClient.On("BalanceAt", mock.Anything, k0Addr, nilBigInt).Once().Return(k0bal, nil) ethClient.On("BalanceAt", mock.Anything, k1Addr, nilBigInt).Once().Return(k1bal, nil) @@ -205,7 +201,7 @@ func TestBalanceMonitor_FewerRPCCallsWhenBehind(t *testing.T) { ethClient.On("BalanceAt", mock.Anything, mock.Anything, mock.Anything). Once(). Return(big.NewInt(1), nil) - require.NoError(t, bm.Start(testutils.Context(t))) + servicetest.RunHealthy(t, bm) head := cltest.Head(0) @@ -234,8 +230,6 @@ func TestBalanceMonitor_FewerRPCCallsWhenBehind(t *testing.T) { mockUnblocker <- time.Time{} }) - bm.Close() - // Make sure the BalanceAt mock wasn't called more than once assert.LessOrEqual(t, callCount.Load(), int32(1)) } diff --git a/core/chains/evm/txmgr/broadcaster_test.go b/core/chains/evm/txmgr/broadcaster_test.go index c6e05b0954b..21a4bd2865c 100644 --- a/core/chains/evm/txmgr/broadcaster_test.go +++ b/core/chains/evm/txmgr/broadcaster_test.go @@ -23,6 +23,7 @@ import ( "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" commonclient "github.com/smartcontractkit/chainlink/v2/common/client" @@ -59,7 +60,6 @@ func NewTestEthBroadcaster( nonceAutoSync bool, ) *txmgr.Broadcaster { t.Helper() - ctx := testutils.Context(t) lggr := logger.Test(t) ge := config.EVM().GasEstimator() @@ -70,8 +70,7 @@ func NewTestEthBroadcaster( // Mark instance as test ethBroadcaster.XXXTestDisableUnstartedTxAutoProcessing() - require.NoError(t, ethBroadcaster.Start(ctx)) - t.Cleanup(func() { assert.NoError(t, ethBroadcaster.Close()) }) + servicetest.Run(t, ethBroadcaster) return ethBroadcaster } @@ -634,8 +633,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_OptimisticLockingOnEthTx(t *testi eb.XXXTestDisableUnstartedTxAutoProcessing() // Start instance of broadcaster - require.NoError(t, eb.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, eb.Close()) }) + servicetest.Run(t, eb) mustCreateUnstartedGeneratedTx(t, txStore, fromAddress, &cltest.FixtureChainID) @@ -1794,8 +1792,7 @@ func TestEthBroadcaster_SyncNonce(t *testing.T) { eb := txmgr.NewEvmBroadcaster(txStore, txmgr.NewEvmTxmClient(ethClient), evmTxmCfg, txmgr.NewEvmTxmFeeConfig(ge), evmcfg.EVM().Transactions(), cfg.Database().Listener(), kst, txBuilder, txNonceSyncer, lggr, checkerFactory, true) ethClient.On("PendingNonceAt", mock.Anything, fromAddress).Return(uint64(ethNodeNonce), nil).Once() - require.NoError(t, eb.Start(ctx)) - defer func() { assert.NoError(t, eb.Close()) }() + servicetest.Run(t, eb) testutils.WaitForLogMessage(t, observed, "Fast-forward sequence") @@ -1828,8 +1825,7 @@ func TestEthBroadcaster_SyncNonce(t *testing.T) { ethClient.On("PendingNonceAt", mock.Anything, fromAddress).Return(uint64(0), errors.New("something exploded")).Once() ethClient.On("PendingNonceAt", mock.Anything, fromAddress).Return(ethNodeNonce, nil) - require.NoError(t, eb.Start(ctx)) - defer func() { assert.NoError(t, eb.Close()) }() + servicetest.Run(t, eb) testutils.WaitForLogMessage(t, observed, "Fast-forward sequence") diff --git a/core/chains/evm/txmgr/confirmer_test.go b/core/chains/evm/txmgr/confirmer_test.go index 84c42cd00f1..9d909d58344 100644 --- a/core/chains/evm/txmgr/confirmer_test.go +++ b/core/chains/evm/txmgr/confirmer_test.go @@ -21,6 +21,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" commonclient "github.com/smartcontractkit/chainlink/v2/common/client" commonfee "github.com/smartcontractkit/chainlink/v2/common/fee" txmgrcommon "github.com/smartcontractkit/chainlink/v2/common/txmgr" @@ -1646,7 +1647,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_WithConnectivityCheck(t *testing kst.On("EnabledAddressesForChain", &cltest.FixtureChainID).Return(addresses, nil).Maybe() // Create confirmer with necessary state ec := txmgr.NewEvmConfirmer(txStore, txmgr.NewEvmTxmClient(ethClient), ccfg.EVM(), txmgr.NewEvmTxmFeeConfig(ccfg.EVM().GasEstimator()), ccfg.EVM().Transactions(), cfg.Database(), kst, txBuilder, lggr) - require.NoError(t, ec.Start(testutils.Context(t))) + servicetest.Run(t, ec) currentHead := int64(30) oldEnough := int64(15) nonce := int64(0) @@ -1691,7 +1692,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_WithConnectivityCheck(t *testing addresses := []gethCommon.Address{fromAddress} kst.On("EnabledAddressesForChain", &cltest.FixtureChainID).Return(addresses, nil).Maybe() ec := txmgr.NewEvmConfirmer(txStore, txmgr.NewEvmTxmClient(ethClient), ccfg.EVM(), txmgr.NewEvmTxmFeeConfig(ccfg.EVM().GasEstimator()), ccfg.EVM().Transactions(), cfg.Database(), kst, txBuilder, lggr) - require.NoError(t, ec.Start(testutils.Context(t))) + servicetest.Run(t, ec) currentHead := int64(30) oldEnough := int64(15) nonce := int64(0) @@ -3080,6 +3081,6 @@ func newEthConfirmer(t testing.TB, txStore txmgr.EvmTxStore, ethClient client.Cl txBuilder := txmgr.NewEvmTxAttemptBuilder(*ethClient.ConfiguredChainID(), ge, ks, estimator) ec := txmgr.NewEvmConfirmer(txStore, txmgr.NewEvmTxmClient(ethClient), txmgr.NewEvmTxmConfig(config.EVM()), txmgr.NewEvmTxmFeeConfig(ge), config.EVM().Transactions(), config.Database(), ks, txBuilder, lggr) ec.SetResumeCallback(fn) - require.NoError(t, ec.Start(testutils.Context(t))) + servicetest.Run(t, ec) return ec } diff --git a/core/chains/evm/txmgr/txmgr_test.go b/core/chains/evm/txmgr/txmgr_test.go index 745623ed77e..9833acfd459 100644 --- a/core/chains/evm/txmgr/txmgr_test.go +++ b/core/chains/evm/txmgr/txmgr_test.go @@ -21,6 +21,7 @@ import ( "github.com/jmoiron/sqlx" "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" txmgrcommon "github.com/smartcontractkit/chainlink/v2/common/txmgr" txmgrtypes "github.com/smartcontractkit/chainlink/v2/common/txmgr/types" commontxmmocks "github.com/smartcontractkit/chainlink/v2/common/txmgr/types/mocks" @@ -552,8 +553,7 @@ func TestTxm_Reset(t *testing.T) { assert.EqualError(t, err, "not started") }) - require.NoError(t, txm.Start(testutils.Context(t))) - defer func() { assert.NoError(t, txm.Close()) }() + servicetest.Run(t, txm) t.Run("returns no error if started", func(t *testing.T) { err := txm.Reset(addr, false) diff --git a/core/internal/testutils/evmtest/evmtest.go b/core/internal/testutils/evmtest/evmtest.go index 423615145e5..e0a447a3274 100644 --- a/core/internal/testutils/evmtest/evmtest.go +++ b/core/internal/testutils/evmtest/evmtest.go @@ -15,6 +15,7 @@ import ( "github.com/stretchr/testify/require" "gopkg.in/guregu/null.v4" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink-common/pkg/types" commonmocks "github.com/smartcontractkit/chainlink/v2/common/types/mocks" @@ -36,7 +37,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/pg" "github.com/smartcontractkit/chainlink/v2/core/services/relay" evmrelay "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm" - "github.com/smartcontractkit/chainlink/v2/core/services/srvctest" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -118,7 +118,7 @@ func NewChainRelayExtOpts(t testing.TB, testopts TestChainOpts) legacyevm.ChainR } } if opts.MailMon == nil { - opts.MailMon = srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + opts.MailMon = servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) } if testopts.GasEstimator != nil { opts.GenGasEstimator = func(*big.Int) gas.EvmFeeEstimator { diff --git a/core/services/directrequest/delegate_test.go b/core/services/directrequest/delegate_test.go index 56c28e57458..2d5b9bef03b 100644 --- a/core/services/directrequest/delegate_test.go +++ b/core/services/directrequest/delegate_test.go @@ -14,6 +14,8 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/assets" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log" log_mocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log/mocks" @@ -31,7 +33,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/pipeline" pipeline_mocks "github.com/smartcontractkit/chainlink/v2/core/services/pipeline/mocks" evmrelay "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm" - "github.com/smartcontractkit/chainlink/v2/core/services/srvctest" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -43,7 +44,7 @@ func TestDelegate_ServicesForSpec(t *testing.T) { c.EVM[0].MinIncomingConfirmations = ptr[uint32](1) }) keyStore := cltest.NewKeyStore(t, db, cfg.Database()) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) relayerExtenders := evmtest.NewChainRelayExtenders(t, evmtest.TestChainOpts{DB: db, GeneralConfig: cfg, Client: ethClient, MailMon: mailMon, KeyStore: keyStore.Eth()}) lggr := logger.TestLogger(t) @@ -80,7 +81,7 @@ func NewDirectRequestUniverseWithConfig(t *testing.T, cfg chainlink.GeneralConfi runner := pipeline_mocks.NewRunner(t) broadcaster.On("AddDependents", 1) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) db := pgtest.NewSqlxDB(t) keyStore := cltest.NewKeyStore(t, db, cfg.Database()) diff --git a/core/services/feeds/service_test.go b/core/services/feeds/service_test.go index 271321a1169..bd0993825e2 100644 --- a/core/services/feeds/service_test.go +++ b/core/services/feeds/service_test.go @@ -9,8 +9,15 @@ import ( "time" "github.com/ethereum/go-ethereum/common" + "github.com/google/uuid" + "github.com/lib/pq" "github.com/pkg/errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "gopkg.in/guregu/null.v4" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/headtracker" "github.com/smartcontractkit/chainlink/v2/core/chains/legacyevm" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" @@ -36,13 +43,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/store/models" "github.com/smartcontractkit/chainlink/v2/core/utils" "github.com/smartcontractkit/chainlink/v2/core/utils/crypto" - - "github.com/google/uuid" - "github.com/lib/pq" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - "gopkg.in/guregu/null.v4" ) const FluxMonitorTestSpecTemplate = ` @@ -3465,9 +3465,7 @@ func Test_Service_StartStop(t *testing.T) { tt.beforeFunc(svc) } - require.NoError(t, svc.Start(testutils.Context(t))) - - svc.Close() + servicetest.Run(t, svc) }) } } diff --git a/core/services/fluxmonitorv2/flux_monitor_test.go b/core/services/fluxmonitorv2/flux_monitor_test.go index 1a14fb8bd0a..b13edcc12d8 100644 --- a/core/services/fluxmonitorv2/flux_monitor_test.go +++ b/core/services/fluxmonitorv2/flux_monitor_test.go @@ -21,6 +21,7 @@ import ( "github.com/jmoiron/sqlx" "github.com/smartcontractkit/chainlink-common/pkg/assets" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" txmgrcommon "github.com/smartcontractkit/chainlink/v2/common/txmgr" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log" logmocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log/mocks" @@ -701,7 +702,7 @@ func TestPollingDeviationChecker_BuffersLogs(t *testing.T) { Once(). Run(func(mock.Arguments) { readyToAssert.ItHappened() }) - require.NoError(t, fm.Start(testutils.Context(t))) + servicetest.Run(t, fm) var logBroadcasts []*logmocks.Broadcast @@ -724,8 +725,6 @@ func TestPollingDeviationChecker_BuffersLogs(t *testing.T) { logsAwaiter.ItHappened() readyToAssert.AwaitOrFail(t) - - fm.Close() } func TestFluxMonitor_TriggerIdleTimeThreshold(t *testing.T) { @@ -1049,8 +1048,7 @@ func TestFluxMonitor_IdleTimerResetsOnNewRound(t *testing.T) { idleDurationOccured := make(chan struct{}, 4) initialPollOccurred := make(chan struct{}, 1) - require.NoError(t, fm.Start(testutils.Context(t))) - t.Cleanup(func() { fm.Close() }) + servicetest.Run(t, fm) // Initial Poll roundState1 := flux_aggregator_wrapper.OracleRoundState{RoundId: 1, EligibleToSubmit: false, LatestSubmission: answerBigInt, StartedAt: now()} @@ -1169,11 +1167,9 @@ func TestFluxMonitor_RoundTimeoutCausesPoll_timesOutAtZero(t *testing.T) { require.NoError(t, fm.SetOracleAddress()) fm.ExportedRoundState(t) - require.NoError(t, fm.Start(testutils.Context(t))) + servicetest.Run(t, fm) g.Eventually(ch).Should(gomega.BeClosed()) - - fm.Close() } func TestFluxMonitor_UsesPreviousRoundStateOnStartup_RoundTimeout(t *testing.T) { @@ -1229,15 +1225,13 @@ func TestFluxMonitor_UsesPreviousRoundStateOnStartup_RoundTimeout(t *testing.T) Run(func(mock.Arguments) { close(chRoundState) }). Maybe() - require.NoError(t, fm.Start(testutils.Context(t))) + servicetest.Run(t, fm) if test.expectedToSubmit { g.Eventually(chRoundState).Should(gomega.BeClosed()) } else { g.Consistently(chRoundState).ShouldNot(gomega.BeClosed()) } - - require.NoError(t, fm.Close()) }) } } @@ -1310,8 +1304,7 @@ func TestFluxMonitor_UsesPreviousRoundStateOnStartup_IdleTimer(t *testing.T) { }). Maybe() - require.NoError(t, fm.Start(testutils.Context(t))) - t.Cleanup(func() { fm.Close() }) + servicetest.Run(t, fm) assert.Eventually(t, func() bool { return len(initialPollOccurred) == 1 }, 3*time.Second, 10*time.Millisecond) @@ -1385,7 +1378,7 @@ func TestFluxMonitor_RoundTimeoutCausesPoll_timesOutNotZero(t *testing.T) { Run(func(mock.Arguments) { close(chRoundState2) }). Once() - require.NoError(t, fm.Start(testutils.Context(t))) + servicetest.Run(t, fm) tm.logBroadcaster.On("WasAlreadyConsumed", mock.Anything, mock.Anything).Return(false, nil) tm.logBroadcaster.On("MarkConsumed", mock.Anything, mock.Anything).Return(nil) @@ -1401,7 +1394,6 @@ func TestFluxMonitor_RoundTimeoutCausesPoll_timesOutNotZero(t *testing.T) { g.Eventually(chRoundState2).Should(gomega.BeClosed()) time.Sleep(time.Duration(2*timeout) * time.Second) - require.NoError(t, fm.Close()) } func TestFluxMonitor_ConsumeLogBroadcast(t *testing.T) { @@ -1927,8 +1919,7 @@ func TestFluxMonitor_DrumbeatTicker(t *testing.T) { Return(flux_aggregator_wrapper.OracleRoundState{RoundId: 4, EligibleToSubmit: false, LatestSubmission: answerBigInt, StartedAt: now()}, nil). Maybe() - require.NoError(t, fm.Start(testutils.Context(t))) - defer func() { assert.NoError(t, fm.Close()) }() + servicetest.Run(t, fm) waitTime := 15 * time.Second interval := 50 * time.Millisecond diff --git a/core/services/functions/listener_test.go b/core/services/functions/listener_test.go index 0fcc9c65599..5020537bf61 100644 --- a/core/services/functions/listener_test.go +++ b/core/services/functions/listener_test.go @@ -19,6 +19,8 @@ import ( decryptionPlugin "github.com/smartcontractkit/tdh2/go/ocr2/decryptionplugin" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + log_mocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log/mocks" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" @@ -38,7 +40,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/types" evmrelay_mocks "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/types/mocks" s4_mocks "github.com/smartcontractkit/chainlink/v2/core/services/s4/mocks" - "github.com/smartcontractkit/chainlink/v2/core/services/srvctest" "github.com/smartcontractkit/chainlink/v2/core/services/synchronization" sync_mocks "github.com/smartcontractkit/chainlink/v2/core/services/synchronization/mocks" "github.com/smartcontractkit/chainlink/v2/core/services/synchronization/telem" @@ -81,7 +82,7 @@ func NewFunctionsListenerUniverse(t *testing.T, timeoutSec int, pruneFrequencySe ethClient := evmtest.NewEthClientMockWithDefaultChain(t) broadcaster := log_mocks.NewBroadcaster(t) broadcaster.On("AddDependents", 1) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) db := pgtest.NewSqlxDB(t) kst := cltest.NewKeyStore(t, db, cfg.Database()) @@ -175,9 +176,8 @@ func TestFunctionsListener_HandleOracleRequestV1_Success(t *testing.T) { close(doneCh) }).Return(nil) - require.NoError(t, uni.service.Start(testutils.Context(t))) + servicetest.Run(t, uni.service) <-doneCh - uni.service.Close() } func TestFunctionsListener_HandleOffchainRequest_Success(t *testing.T) { @@ -270,9 +270,8 @@ func TestFunctionsListener_HandleOracleRequestV1_ComputationError(t *testing.T) close(doneCh) }).Return(nil) - require.NoError(t, uni.service.Start(testutils.Context(t))) + servicetest.Run(t, uni.service) <-doneCh - uni.service.Close() } func TestFunctionsListener_HandleOracleRequestV1_ThresholdDecryptedSecrets(t *testing.T) { @@ -312,9 +311,8 @@ func TestFunctionsListener_HandleOracleRequestV1_ThresholdDecryptedSecrets(t *te close(doneCh) }).Return(nil) - require.NoError(t, uni.service.Start(testutils.Context(t))) + servicetest.Run(t, uni.service) <-doneCh - uni.service.Close() } func TestFunctionsListener_HandleOracleRequestV1_CBORTooBig(t *testing.T) { @@ -339,9 +337,8 @@ func TestFunctionsListener_HandleOracleRequestV1_CBORTooBig(t *testing.T) { close(doneCh) }).Return(nil) - require.NoError(t, uni.service.Start(testutils.Context(t))) + servicetest.Run(t, uni.service) <-doneCh - uni.service.Close() } func TestFunctionsListener_ReportSourceCodeDomains(t *testing.T) { @@ -395,9 +392,8 @@ func TestFunctionsListener_PruneRequests(t *testing.T) { doneCh <- true }) - require.NoError(t, uni.service.Start(testutils.Context(t))) + servicetest.Run(t, uni.service) <-doneCh - uni.service.Close() } func TestFunctionsListener_TimeoutRequests(t *testing.T) { @@ -411,9 +407,8 @@ func TestFunctionsListener_TimeoutRequests(t *testing.T) { doneCh <- true }) - require.NoError(t, uni.service.Start(testutils.Context(t))) + servicetest.Run(t, uni.service) <-doneCh - uni.service.Close() } func TestFunctionsListener_ORMDoesNotFreezeHandlersForever(t *testing.T) { @@ -434,7 +429,6 @@ func TestFunctionsListener_ORMDoesNotFreezeHandlersForever(t *testing.T) { ormCallExited.Done() }).Return(errors.New("timeout")) - require.NoError(t, uni.service.Start(testutils.Context(t))) + servicetest.Run(t, uni.service) ormCallExited.Wait() // should not freeze - uni.service.Close() } diff --git a/core/services/gateway/connector/connector_test.go b/core/services/gateway/connector/connector_test.go index 4001914524b..1c2c6d26b10 100644 --- a/core/services/gateway/connector/connector_test.go +++ b/core/services/gateway/connector/connector_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/gateway/connector" "github.com/smartcontractkit/chainlink/v2/core/services/gateway/connector/mocks" @@ -121,8 +121,7 @@ func TestGatewayConnector_CleanStartAndClose(t *testing.T) { handler.On("Start", mock.Anything).Return(nil) handler.On("Close").Return(nil) signer.On("Sign", mock.Anything).Return(nil, errors.New("cannot sign")) - require.NoError(t, connector.Start(testutils.Context(t))) - require.NoError(t, connector.Close()) + servicetest.Run(t, connector) } func TestGatewayConnector_NewAuthHeader_SignerError(t *testing.T) { diff --git a/core/services/gateway/gateway_test.go b/core/services/gateway/gateway_test.go index 5fad6315a31..74d689fffe1 100644 --- a/core/services/gateway/gateway_test.go +++ b/core/services/gateway/gateway_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/gateway" @@ -130,8 +131,7 @@ func TestGateway_CleanStartAndClose(t *testing.T) { lggr := logger.TestLogger(t) gateway, err := gateway.NewGatewayFromConfig(parseTOMLConfig(t, buildConfig("")), gateway.NewHandlerFactory(nil, lggr), lggr) require.NoError(t, err) - require.NoError(t, gateway.Start(testutils.Context(t))) - require.NoError(t, gateway.Close()) + servicetest.Run(t, gateway) } func requireJsonRPCResult(t *testing.T, response []byte, expectedId string, expectedResult string) { diff --git a/core/services/gateway/handlers/functions/handler.functions_test.go b/core/services/gateway/handlers/functions/handler.functions_test.go index f36b64709a2..1d6dd109625 100644 --- a/core/services/gateway/handlers/functions/handler.functions_test.go +++ b/core/services/gateway/handlers/functions/handler.functions_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/assets" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/gateway/api" @@ -97,8 +98,7 @@ func TestFunctionsHandler_CleanStartAndClose(t *testing.T) { handler, err := functions.NewFunctionsHandlerFromConfig(json.RawMessage("{}"), &config.DONConfig{}, nil, nil, logger.TestLogger(t)) require.NoError(t, err) - require.NoError(t, handler.Start(testutils.Context(t))) - require.NoError(t, handler.Close()) + servicetest.Run(t, handler) } func TestFunctionsHandler_HandleUserMessage_SecretsSet(t *testing.T) { diff --git a/core/services/gateway/integration_tests/gateway_integration_test.go b/core/services/gateway/integration_tests/gateway_integration_test.go index 310047950e6..415a8f67cf8 100644 --- a/core/services/gateway/integration_tests/gateway_integration_test.go +++ b/core/services/gateway/integration_tests/gateway_integration_test.go @@ -14,6 +14,7 @@ import ( "github.com/pelletier/go-toml/v2" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/gateway" @@ -119,7 +120,7 @@ func TestIntegration_Gateway_NoFullNodes_BasicConnectionAndMessage(t *testing.T) gatewayConfig := fmt.Sprintf(gatewayConfigTemplate, nodeKeys.Address) gateway, err := gateway.NewGatewayFromConfig(parseGatewayConfig(t, gatewayConfig), gateway.NewHandlerFactory(nil, lggr), lggr) require.NoError(t, err) - require.NoError(t, gateway.Start(testutils.Context(t))) + servicetest.Run(t, gateway) userPort, nodePort := gateway.GetUserPort(), gateway.GetNodePort() userUrl := fmt.Sprintf("http://localhost:%d/user", userPort) nodeUrl := fmt.Sprintf("ws://localhost:%d/node", nodePort) @@ -129,7 +130,7 @@ func TestIntegration_Gateway_NoFullNodes_BasicConnectionAndMessage(t *testing.T) connector, err := connector.NewGatewayConnector(parseConnectorConfig(t, nodeConfigTemplate, nodeKeys.Address, nodeUrl), client, client, utils.NewRealClock(), lggr) require.NoError(t, err) client.connector = connector - require.NoError(t, connector.Start(testutils.Context(t))) + servicetest.Run(t, connector) // Send requests until one of them reaches Connector gomega.NewGomegaWithT(t).Eventually(func() bool { @@ -144,7 +145,4 @@ func TestIntegration_Gateway_NoFullNodes_BasicConnectionAndMessage(t *testing.T) _, _ = httpClient.Do(req) // could initially return error if Gateway is not fully initialized yet return client.done.Load() }, testutils.WaitTimeout(t), testutils.TestInterval).Should(gomega.Equal(true)) - - require.NoError(t, connector.Close()) - require.NoError(t, gateway.Close()) } diff --git a/core/services/gateway/network/wsconnection_test.go b/core/services/gateway/network/wsconnection_test.go index 5fd8aa50e33..4ded4f40b10 100644 --- a/core/services/gateway/network/wsconnection_test.go +++ b/core/services/gateway/network/wsconnection_test.go @@ -9,6 +9,7 @@ import ( "github.com/gorilla/websocket" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/gateway/network" @@ -30,18 +31,17 @@ func (ssl *serverSideLogic) wsHandler(w http.ResponseWriter, r *http.Request) { } func TestWSConnectionWrapper_ClientReconnect(t *testing.T) { - ctx := testutils.Context(t) lggr := logger.TestLogger(t) // server ssl := &serverSideLogic{connWrapper: network.NewWSConnectionWrapper(lggr)} - require.NoError(t, ssl.connWrapper.Start(ctx)) + servicetest.Run(t, ssl.connWrapper) s := httptest.NewServer(http.HandlerFunc(ssl.wsHandler)) serverURL := "ws" + strings.TrimPrefix(s.URL, "http") defer s.Close() // client clientConnWrapper := network.NewWSConnectionWrapper(lggr) - require.NoError(t, clientConnWrapper.Start(ctx)) + servicetest.Run(t, clientConnWrapper) // connect, write a message, disconnect conn, _, err := websocket.DefaultDialer.Dial(serverURL, nil) @@ -64,8 +64,4 @@ func TestWSConnectionWrapper_ClientReconnect(t *testing.T) { require.NoError(t, writeErr) <-ssl.connWrapper.ReadChannel() // consumed by server conn.Close() - - ssl.connWrapper.Close() - clientConnWrapper.Close() - clientConnWrapper.Close() // safe to call Close() twice } diff --git a/core/services/job/runner_integration_test.go b/core/services/job/runner_integration_test.go index ef0458312bc..0223f1a10d5 100644 --- a/core/services/job/runner_integration_test.go +++ b/core/services/job/runner_integration_test.go @@ -23,6 +23,8 @@ import ( "github.com/stretchr/testify/require" "gopkg.in/guregu/null.v4" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" @@ -40,7 +42,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/ocrcommon" "github.com/smartcontractkit/chainlink/v2/core/services/pipeline" evmrelay "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm" - "github.com/smartcontractkit/chainlink/v2/core/services/srvctest" "github.com/smartcontractkit/chainlink/v2/core/services/telemetry" "github.com/smartcontractkit/chainlink/v2/core/services/webhook" "github.com/smartcontractkit/chainlink/v2/core/store/models" @@ -91,8 +92,7 @@ func TestRunner(t *testing.T) { _, placeHolderAddress := cltest.MustInsertRandomKey(t, keyStore.Eth()) - require.NoError(t, runner.Start(ctx)) - t.Cleanup(func() { assert.NoError(t, runner.Close()) }) + servicetest.Run(t, runner) t.Run("gets the election result winner", func(t *testing.T) { var httpURL string @@ -451,8 +451,7 @@ answer1 [type=median index=0]; _, err = keyStore.P2P().Create() assert.NoError(t, err) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, config.P2P(), config.OCR(), config.Database(), db, lggr) - require.NoError(t, pw.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, pw.Close()) }) + servicetest.Run(t, pw) sd := ocr.NewDelegate( db, jobORM, @@ -463,7 +462,7 @@ answer1 [type=median index=0]; legacyChains, lggr, config.Database(), - srvctest.Start(t, utils.NewMailboxMonitor(t.Name())), + servicetest.Run(t, utils.NewMailboxMonitor(t.Name())), ) _, err = sd.ServicesForSpec(jb) require.NoError(t, err) @@ -486,8 +485,7 @@ answer1 [type=median index=0]; lggr := logger.TestLogger(t) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, config.P2P(), config.OCR(), config.Database(), db, lggr) - require.NoError(t, pw.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, pw.Close()) }) + servicetest.Run(t, pw) sd := ocr.NewDelegate( db, jobORM, @@ -498,7 +496,7 @@ answer1 [type=median index=0]; legacyChains, lggr, config.Database(), - srvctest.Start(t, utils.NewMailboxMonitor(t.Name())), + servicetest.Run(t, utils.NewMailboxMonitor(t.Name())), ) _, err = sd.ServicesForSpec(jb) require.NoError(t, err) @@ -515,8 +513,7 @@ answer1 [type=median index=0]; lggr := logger.TestLogger(t) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, config.P2P(), config.OCR(), config.Database(), db, lggr) - require.NoError(t, pw.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, pw.Close()) }) + servicetest.Run(t, pw) sd := ocr.NewDelegate( db, jobORM, @@ -527,7 +524,7 @@ answer1 [type=median index=0]; legacyChains, lggr, config.Database(), - srvctest.Start(t, utils.NewMailboxMonitor(t.Name())), + servicetest.Run(t, utils.NewMailboxMonitor(t.Name())), ) _, err = sd.ServicesForSpec(jb) require.NoError(t, err) @@ -571,8 +568,7 @@ answer1 [type=median index=0]; lggr := logger.TestLogger(t) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, config.P2P(), config.OCR(), config.Database(), db, lggr) - require.NoError(t, pw.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, pw.Close()) }) + servicetest.Run(t, pw) sd := ocr.NewDelegate( db, jobORM, @@ -583,7 +579,7 @@ answer1 [type=median index=0]; legacyChains, lggr, config.Database(), - srvctest.Start(t, utils.NewMailboxMonitor(t.Name())), + servicetest.Run(t, utils.NewMailboxMonitor(t.Name())), ) jb.OCROracleSpec.CaptureEATelemetry = tc.jbCaptureEATelemetry @@ -616,8 +612,7 @@ answer1 [type=median index=0]; lggr := logger.TestLogger(t) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, config.P2P(), config.OCR(), config.Database(), db, lggr) - require.NoError(t, pw.Start(testutils.Context(t))) - t.Cleanup(func() { assert.NoError(t, pw.Close()) }) + servicetest.Run(t, pw) sd := ocr.NewDelegate( db, jobORM, @@ -628,7 +623,7 @@ answer1 [type=median index=0]; legacyChains, lggr, config.Database(), - srvctest.Start(t, utils.NewMailboxMonitor(t.Name())), + servicetest.Run(t, utils.NewMailboxMonitor(t.Name())), ) services, err := sd.ServicesForSpec(*jb) require.NoError(t, err) diff --git a/core/services/job/spawner_test.go b/core/services/job/spawner_test.go index 0ad76491438..d639ce859af 100644 --- a/core/services/job/spawner_test.go +++ b/core/services/job/spawner_test.go @@ -13,6 +13,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/loop" "github.com/smartcontractkit/chainlink-common/pkg/services" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/bridges" mocklp "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller/mocks" @@ -33,7 +34,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/relay" evmrelay "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm" evmrelayer "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm" - "github.com/smartcontractkit/chainlink/v2/core/services/srvctest" "github.com/smartcontractkit/chainlink/v2/core/utils" "github.com/smartcontractkit/chainlink/v2/plugins" ) @@ -128,7 +128,7 @@ func TestSpawner_CreateJobDeleteJob(t *testing.T) { serviceA2 := mocks.NewServiceCtx(t) serviceA1.On("Start", mock.Anything).Return(nil).Once() serviceA2.On("Start", mock.Anything).Return(nil).Once().Run(func(mock.Arguments) { eventuallyA.ItHappened() }) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) dA := ocr.NewDelegate(nil, orm, nil, nil, nil, monitoringEndpoint, legacyChains, logger.TestLogger(t), config.Database(), mailMon) delegateA := &delegate{jobA.Type, []job.ServiceCtx{serviceA1, serviceA2}, 0, make(chan struct{}), dA} @@ -187,7 +187,7 @@ func TestSpawner_CreateJobDeleteJob(t *testing.T) { lggr := logger.TestLogger(t) orm := NewTestORM(t, db, pipeline.NewORM(db, lggr, config.Database(), config.JobPipeline().MaxSuccessfulRuns()), bridges.NewORM(db, lggr, config.Database()), keyStore, config.Database()) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) d := ocr.NewDelegate(nil, orm, nil, nil, nil, monitoringEndpoint, legacyChains, logger.TestLogger(t), config.Database(), mailMon) delegateA := &delegate{jobA.Type, []job.ServiceCtx{serviceA1, serviceA2}, 0, nil, d} spawner := job.NewSpawner(orm, config.Database(), noopChecker{}, map[job.Type]job.Delegate{ @@ -221,7 +221,7 @@ func TestSpawner_CreateJobDeleteJob(t *testing.T) { lggr := logger.TestLogger(t) orm := NewTestORM(t, db, pipeline.NewORM(db, lggr, config.Database(), config.JobPipeline().MaxSuccessfulRuns()), bridges.NewORM(db, lggr, config.Database()), keyStore, config.Database()) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) d := ocr.NewDelegate(nil, orm, nil, nil, nil, monitoringEndpoint, legacyChains, logger.TestLogger(t), config.Database(), mailMon) delegateA := &delegate{jobA.Type, []job.ServiceCtx{serviceA1, serviceA2}, 0, nil, d} spawner := job.NewSpawner(orm, config.Database(), noopChecker{}, map[job.Type]job.Delegate{ @@ -299,7 +299,7 @@ func TestSpawner_CreateJobDeleteJob(t *testing.T) { jobOCR2VRF := makeOCR2VRFJobSpec(t, keyStore, config, address, chain.ID(), 2) orm := NewTestORM(t, db, pipeline.NewORM(db, lggr, config.Database(), config.JobPipeline().MaxSuccessfulRuns()), bridges.NewORM(db, lggr, config.Database()), keyStore, config.Database()) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) processConfig := plugins.NewRegistrarConfig(loop.GRPCOpts{}, func(name string) (*plugins.RegisteredLoop, error) { return nil, nil }) ocr2DelegateConfig := ocr2.NewDelegateConfig(config.OCR2(), config.Mercury(), config.Threshold(), config.Insecure(), config.JobPipeline(), config.Database(), processConfig) diff --git a/core/services/keeper/registry1_1_synchronizer_test.go b/core/services/keeper/registry1_1_synchronizer_test.go index 031b7a59074..fb0b1866c41 100644 --- a/core/services/keeper/registry1_1_synchronizer_test.go +++ b/core/services/keeper/registry1_1_synchronizer_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" logmocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log/mocks" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" @@ -217,8 +218,7 @@ func Test_RegistrySynchronizer1_1_ConfigSetLog(t *testing.T) { upkeepConfig1_1, 0) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) var registry keeper.Registry require.NoError(t, db.Get(®istry, `SELECT * FROM keeper_registries`)) @@ -266,8 +266,7 @@ func Test_RegistrySynchronizer1_1_KeepersUpdatedLog(t *testing.T) { upkeepConfig1_1, 0) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) var registry keeper.Registry require.NoError(t, db.Get(®istry, `SELECT * FROM keeper_registries`)) @@ -313,8 +312,7 @@ func Test_RegistrySynchronizer1_1_UpkeepCanceledLog(t *testing.T) { upkeepConfig1_1, 3) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { require.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 3) @@ -352,8 +350,7 @@ func Test_RegistrySynchronizer1_1_UpkeepRegisteredLog(t *testing.T) { upkeepConfig1_1, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) @@ -396,8 +393,7 @@ func Test_RegistrySynchronizer1_1_UpkeepPerformedLog(t *testing.T) { upkeepConfig1_1, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) diff --git a/core/services/keeper/registry1_2_synchronizer_test.go b/core/services/keeper/registry1_2_synchronizer_test.go index e7d8d6a48a2..b7456ad94e4 100644 --- a/core/services/keeper/registry1_2_synchronizer_test.go +++ b/core/services/keeper/registry1_2_synchronizer_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" logmocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log/mocks" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" @@ -237,8 +238,7 @@ func Test_RegistrySynchronizer1_2_ConfigSetLog(t *testing.T) { 2, 0) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) var registry keeper.Registry require.NoError(t, db.Get(®istry, `SELECT * FROM keeper_registries`)) @@ -290,8 +290,7 @@ func Test_RegistrySynchronizer1_2_KeepersUpdatedLog(t *testing.T) { 2, 0) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) var registry keeper.Registry require.NoError(t, db.Get(®istry, `SELECT * FROM keeper_registries`)) @@ -342,8 +341,7 @@ func Test_RegistrySynchronizer1_2_UpkeepCanceledLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { require.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 3) @@ -382,8 +380,7 @@ func Test_RegistrySynchronizer1_2_UpkeepRegisteredLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) @@ -427,8 +424,7 @@ func Test_RegistrySynchronizer1_2_UpkeepPerformedLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) @@ -482,8 +478,7 @@ func Test_RegistrySynchronizer1_2_UpkeepGasLimitSetLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) @@ -535,8 +530,7 @@ func Test_RegistrySynchronizer1_2_UpkeepReceivedLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) @@ -578,8 +572,7 @@ func Test_RegistrySynchronizer1_2_UpkeepMigratedLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { require.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 3) diff --git a/core/services/keeper/registry1_3_synchronizer_test.go b/core/services/keeper/registry1_3_synchronizer_test.go index a0522fd717e..6e3be4ea785 100644 --- a/core/services/keeper/registry1_3_synchronizer_test.go +++ b/core/services/keeper/registry1_3_synchronizer_test.go @@ -12,19 +12,20 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" - registry1_3 "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/keeper_registry_wrapper1_3" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" - "github.com/smartcontractkit/chainlink/v2/core/utils" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" logmocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log/mocks" evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types" + registry1_3 "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/keeper_registry_wrapper1_3" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/evmtest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keeper" + "github.com/smartcontractkit/chainlink/v2/core/utils" ) var registryConfig1_3 = registry1_3.Config{ @@ -242,8 +243,7 @@ func Test_RegistrySynchronizer1_3_ConfigSetLog(t *testing.T) { 2, 0) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) var registry keeper.Registry require.NoError(t, db.Get(®istry, `SELECT * FROM keeper_registries`)) @@ -295,8 +295,7 @@ func Test_RegistrySynchronizer1_3_KeepersUpdatedLog(t *testing.T) { 2, 0) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) var registry keeper.Registry require.NoError(t, db.Get(®istry, `SELECT * FROM keeper_registries`)) @@ -347,8 +346,7 @@ func Test_RegistrySynchronizer1_3_UpkeepCanceledLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { require.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 3) @@ -387,8 +385,7 @@ func Test_RegistrySynchronizer1_3_UpkeepRegisteredLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) @@ -432,8 +429,7 @@ func Test_RegistrySynchronizer1_3_UpkeepPerformedLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) @@ -487,8 +483,7 @@ func Test_RegistrySynchronizer1_3_UpkeepGasLimitSetLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) @@ -540,8 +535,7 @@ func Test_RegistrySynchronizer1_3_UpkeepReceivedLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) @@ -583,8 +577,7 @@ func Test_RegistrySynchronizer1_3_UpkeepMigratedLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { require.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 3) @@ -625,8 +618,7 @@ func Test_RegistrySynchronizer1_3_UpkeepPausedLog_UpkeepUnpausedLog(t *testing.T 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { require.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 3) @@ -695,8 +687,7 @@ func Test_RegistrySynchronizer1_3_UpkeepCheckDataUpdatedLog(t *testing.T) { 2, 1) - require.NoError(t, synchronizer.Start(testutils.Context(t))) - defer func() { assert.NoError(t, synchronizer.Close()) }() + servicetest.Run(t, synchronizer) cltest.WaitForCount(t, db, "keeper_registries", 1) cltest.WaitForCount(t, db, "upkeep_registrations", 1) diff --git a/core/services/keeper/registry_synchronizer_helper_test.go b/core/services/keeper/registry_synchronizer_helper_test.go index 966366b1069..5ba60db3962 100644 --- a/core/services/keeper/registry_synchronizer_helper_test.go +++ b/core/services/keeper/registry_synchronizer_helper_test.go @@ -10,6 +10,8 @@ import ( "github.com/jmoiron/sqlx" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log" logmocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/log/mocks" @@ -21,7 +23,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/job" "github.com/smartcontractkit/chainlink/v2/core/services/keeper" evmrelay "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm" - "github.com/smartcontractkit/chainlink/v2/core/services/srvctest" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -72,7 +73,7 @@ func setupRegistrySync(t *testing.T, version keeper.RegistryVersion) ( })).Maybe().Return(func() {}) lbMock.On("IsConnected").Return(true).Maybe() - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) orm := keeper.NewORM(db, logger.TestLogger(t), ch.Config().Database()) synchronizer := keeper.NewRegistrySynchronizer(keeper.RegistrySynchronizerOptions{ diff --git a/core/services/keeper/upkeep_executer_test.go b/core/services/keeper/upkeep_executer_test.go index 7bbecafa22d..123b1dc0de1 100644 --- a/core/services/keeper/upkeep_executer_test.go +++ b/core/services/keeper/upkeep_executer_test.go @@ -15,6 +15,7 @@ import ( "github.com/jmoiron/sqlx" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/gas" @@ -88,8 +89,7 @@ func setup(t *testing.T, estimator gas.EvmFeeEstimator, overrideFn func(c *chain lggr := logger.TestLogger(t) executer := keeper.NewUpkeepExecuter(job, orm, jpv2.Pr, ethClient, ch.HeadBroadcaster(), ch.GasEstimator(), lggr, ch.Config().Keeper(), job.KeeperSpec.FromAddress.Address()) upkeep := cltest.MustInsertUpkeepForRegistry(t, db, ch.Config().Database(), registry) - require.NoError(t, executer.Start(testutils.Context(t))) - t.Cleanup(func() { executer.Close() }) + servicetest.Run(t, executer) return db, cfg, ethClient, executer, registry, upkeep, job, jpv2, txm, keyStore, ch, orm } diff --git a/core/services/nurse_test.go b/core/services/nurse_test.go index 4e68501b74b..79f57d91235 100644 --- a/core/services/nurse_test.go +++ b/core/services/nurse_test.go @@ -128,7 +128,6 @@ func TestNurse(t *testing.T) { n2, err := nrse.totalProfileBytes() require.NoError(t, err) require.Greater(t, n2, uint64(0)) - } func profileExists(t *testing.T, nrse *Nurse, typ string) bool { diff --git a/core/services/ocr/config_overrider_test.go b/core/services/ocr/config_overrider_test.go index 245d6348765..acd5245e19b 100644 --- a/core/services/ocr/config_overrider_test.go +++ b/core/services/ocr/config_overrider_test.go @@ -14,9 +14,9 @@ import ( ocrtypes "github.com/smartcontractkit/libocr/offchainreporting/types" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/mocks" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ethkey" "github.com/smartcontractkit/chainlink/v2/core/services/ocr" @@ -72,7 +72,7 @@ func TestIntegration_OCRConfigOverrider_EntersHibernation(t *testing.T) { Run(checkFlagsAddress(t, uni.contractAddress)). Return([]bool{true, true}, nil) - require.NoError(t, uni.overrider.Start(testutils.Context(t))) + servicetest.Run(t, uni.overrider) // not hibernating initially require.Nil(t, uni.overrider.ConfigOverride()) @@ -102,7 +102,7 @@ func Test_OCRConfigOverrider(t *testing.T) { Run(checkFlagsAddress(t, uni.contractAddress)). Return([]bool{true, true}, nil) - require.NoError(t, uni.overrider.Start(testutils.Context(t))) + servicetest.Run(t, uni.overrider) // not hibernating initially require.Nil(t, uni.overrider.ConfigOverride()) @@ -130,7 +130,7 @@ func Test_OCRConfigOverrider(t *testing.T) { Run(checkFlagsAddress(t, uni.contractAddress)). Return([]bool{true, false}, nil) - require.NoError(t, uni.overrider.Start(testutils.Context(t))) + servicetest.Run(t, uni.overrider) // initially enters hibernation expectedOverride := &ocrtypes.ConfigOverride{AlphaPPB: math.MaxUint64, DeltaC: uni.overrider.DeltaCFromAddress} diff --git a/core/services/ocr/contract_tracker_test.go b/core/services/ocr/contract_tracker_test.go index 5684219cf16..af65f330d66 100644 --- a/core/services/ocr/contract_tracker_test.go +++ b/core/services/ocr/contract_tracker_test.go @@ -15,6 +15,8 @@ import ( "github.com/smartcontractkit/libocr/gethwrappers/offchainaggregator" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting/types" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + commonmocks "github.com/smartcontractkit/chainlink/v2/common/mocks" evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" evmconfig "github.com/smartcontractkit/chainlink/v2/core/chains/evm/config" @@ -29,7 +31,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/ocr" ocrmocks "github.com/smartcontractkit/chainlink/v2/core/services/ocr/mocks" - "github.com/smartcontractkit/chainlink/v2/core/services/srvctest" "github.com/smartcontractkit/chainlink/v2/core/utils" ) @@ -83,7 +84,7 @@ func newContractTrackerUni(t *testing.T, opts ...interface{}) (uni contractTrack uni.hb = commonmocks.NewHeadBroadcaster[*evmtypes.Head, common.Hash](t) uni.ec = evmtest.NewEthClientMock(t) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) db := pgtest.NewSqlxDB(t) uni.tracker = ocr.NewOCRContractTracker( contract, @@ -148,13 +149,12 @@ func Test_OCRContractTracker_LatestBlockHeight(t *testing.T) { uni.db.On("LoadLatestRoundRequested").Return(offchainaggregator.OffchainAggregatorRoundRequested{}, nil) uni.lb.On("Register", uni.tracker, mock.Anything).Return(func() {}) - require.NoError(t, uni.tracker.Start(testutils.Context(t))) + servicetest.Run(t, uni.tracker) l, err := uni.tracker.LatestBlockHeight(testutils.Context(t)) require.NoError(t, err) assert.Equal(t, uint64(42), l) - require.NoError(t, uni.tracker.Close()) }) } diff --git a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store_test.go b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store_test.go index 138b9ffd782..7108e1b64c4 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evmregistry/v21/upkeepstate/store_test.go @@ -14,6 +14,7 @@ import ( ocr2keepers "github.com/smartcontractkit/chainlink-automation/pkg/v3/types" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/logger" @@ -346,7 +347,7 @@ func TestUpkeepStateStore_SetSelectIntegration(t *testing.T) { scanner := &mockScanner{} store := NewUpkeepStateStore(orm, lggr, scanner) - require.NoError(t, store.Start(ctx)) + servicetest.Run(t, store) t.Cleanup(func() { t.Log("cleaning up database") @@ -379,8 +380,6 @@ func TestUpkeepStateStore_SetSelectIntegration(t *testing.T) { observedLogs.TakeAll() require.Equal(t, 0, observedLogs.Len()) - - require.NoError(t, store.Close()) }) } } @@ -467,7 +466,7 @@ func TestUpkeepStateStore_Service(t *testing.T) { store.retention = 500 * time.Millisecond store.cleanCadence = 100 * time.Millisecond - assert.NoError(t, store.Start(ctx), "no error from starting service") + servicetest.Run(t, store) // add a value to set up the test require.NoError(t, store.SetUpkeepState(ctx, ocr2keepers.CheckResult{ @@ -493,8 +492,6 @@ func TestUpkeepStateStore_Service(t *testing.T) { values, err = store.SelectByWorkIDs(ctx, "0x2") require.NoError(t, err, "no error from selecting states") require.Equal(t, []ocr2keepers.UpkeepState{ocr2keepers.UnknownState}, values, "selected values should match expected") - - assert.NoError(t, store.Close(), "no error from closing service") } func createUpkeepIDForTest(v int64) ocr2keepers.UpkeepIdentifier { diff --git a/core/services/ocrcommon/peer_wrapper_test.go b/core/services/ocrcommon/peer_wrapper_test.go index 854ecb153ea..dbe22523728 100644 --- a/core/services/ocrcommon/peer_wrapper_test.go +++ b/core/services/ocrcommon/peer_wrapper_test.go @@ -9,6 +9,7 @@ import ( p2ppeer "github.com/libp2p/go-libp2p-core/peer" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/configtest" @@ -52,9 +53,8 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { }) pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), cfg.Database(), db, logger.TestLogger(t)) - require.NoError(t, pw.Start(testutils.Context(t)), "foo") + servicetest.Run(t, pw) require.Equal(t, k.PeerID(), pw.PeerID) - require.NoError(t, pw.Close()) }) t.Run("with one p2p key and mismatching P2P.PeerID returns error", func(t *testing.T) { @@ -89,9 +89,8 @@ func Test_SingletonPeerWrapper_Start(t *testing.T) { pw := ocrcommon.NewSingletonPeerWrapper(keyStore, cfg.P2P(), cfg.OCR(), cfg.Database(), db, logger.TestLogger(t)) - require.NoError(t, pw.Start(testutils.Context(t)), "foo") + servicetest.Run(t, pw) require.Equal(t, k2.PeerID(), pw.PeerID) - require.NoError(t, pw.Close()) }) t.Run("with multiple p2p keys and mismatching P2P.PeerID returns error", func(t *testing.T) { diff --git a/core/services/ocrcommon/run_saver_test.go b/core/services/ocrcommon/run_saver_test.go index 73697d181bc..7bfe60f2a06 100644 --- a/core/services/ocrcommon/run_saver_test.go +++ b/core/services/ocrcommon/run_saver_test.go @@ -4,9 +4,8 @@ import ( "testing" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/pipeline" "github.com/smartcontractkit/chainlink/v2/core/services/pipeline/mocks" @@ -20,7 +19,7 @@ func TestRunSaver(t *testing.T) { 1000, 100, ) - require.NoError(t, rs.Start(testutils.Context(t))) + servicetest.Run(t, rs) for i := 0; i < 100; i++ { d := i pipelineRunner.On("InsertFinishedRun", mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -31,5 +30,4 @@ func TestRunSaver(t *testing.T) { Once() rs.Save(&pipeline.Run{ID: int64(i)}) } - require.NoError(t, rs.Close()) } diff --git a/core/services/ocrcommon/telemetry.go b/core/services/ocrcommon/telemetry.go index 18080fe22b6..5fbda456088 100644 --- a/core/services/ocrcommon/telemetry.go +++ b/core/services/ocrcommon/telemetry.go @@ -99,7 +99,7 @@ func (e *EnhancedTelemetryService[T]) Start(context.Context) error { func (e *EnhancedTelemetryService[T]) Close() error { return e.StopOnce("EnhancedTelemetryService", func() error { - e.chDone <- struct{}{} + close(e.chDone) e.lggr.Infof("Stopping enhanced telemetry service for job %d", e.job.ID) return nil }) diff --git a/core/services/ocrcommon/telemetry_test.go b/core/services/ocrcommon/telemetry_test.go index ae58e89d22e..9c90eea180a 100644 --- a/core/services/ocrcommon/telemetry_test.go +++ b/core/services/ocrcommon/telemetry_test.go @@ -14,11 +14,11 @@ import ( "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink-common/pkg/types/mercury" mercuryv1 "github.com/smartcontractkit/chainlink-common/pkg/types/mercury/v1" mercuryv2 "github.com/smartcontractkit/chainlink-common/pkg/types/mercury/v2" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/job" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/ethkey" @@ -213,7 +213,7 @@ func TestSendEATelemetry(t *testing.T) { lggr, _ := logger.TestLoggerObserved(t, zap.WarnLevel) doneCh := make(chan struct{}) enhancedTelemService := NewEnhancedTelemetryService(&jb, enhancedTelemChan, doneCh, monitoringEndpoint, lggr.Named("Enhanced Telemetry Mercury")) - require.NoError(t, enhancedTelemService.Start(testutils.Context(t))) + servicetest.Run(t, enhancedTelemService) trrs := pipeline.TaskRunResults{ pipeline.TaskRunResult{ Task: &pipeline.BridgeTask{ @@ -324,7 +324,7 @@ func TestCollectAndSend(t *testing.T) { doneCh := make(chan struct{}) enhancedTelemService := NewEnhancedTelemetryService(&jb, enhancedTelemChan, doneCh, monitoringEndpoint, lggr.Named("Enhanced Telemetry")) - require.NoError(t, enhancedTelemService.Start(testutils.Context(t))) + servicetest.Run(t, enhancedTelemService) finalResult := &pipeline.FinalResult{ Values: []interface{}{"123456"}, AllErrors: nil, @@ -574,7 +574,7 @@ func TestCollectMercuryEnhancedTelemetryV1(t *testing.T) { lggr: lggr, monitoringEndpoint: monitoringEndpoint, } - require.NoError(t, e.Start(testutils.Context(t))) + servicetest.Run(t, &e) wg.Add(1) @@ -690,7 +690,7 @@ func TestCollectMercuryEnhancedTelemetryV2(t *testing.T) { lggr: lggr, monitoringEndpoint: monitoringEndpoint, } - require.NoError(t, e.Start(testutils.Context(t))) + servicetest.Run(t, &e) wg.Add(1) diff --git a/core/services/pg/event_broadcaster_test.go b/core/services/pg/event_broadcaster_test.go index 41dcbb0176f..e8a4a1086db 100644 --- a/core/services/pg/event_broadcaster_test.go +++ b/core/services/pg/event_broadcaster_test.go @@ -9,8 +9,8 @@ import ( "github.com/onsi/gomega" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest/heavyweight" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/pg" ) @@ -19,8 +19,7 @@ func TestEventBroadcaster(t *testing.T) { config, _ := heavyweight.FullTestDBNoFixturesV2(t, nil) eventBroadcaster := pg.NewEventBroadcaster(config.Database().URL(), 0, 0, logger.TestLogger(t), uuid.New()) - require.NoError(t, eventBroadcaster.Start(testutils.Context(t))) - t.Cleanup(func() { require.NoError(t, eventBroadcaster.Close()) }) + servicetest.Run(t, eventBroadcaster) t.Run("doesn't broadcast unrelated events (no payload filter)", func(t *testing.T) { sub, err := eventBroadcaster.Subscribe("foo", "") diff --git a/core/services/promreporter/prom_reporter_test.go b/core/services/promreporter/prom_reporter_test.go index 54e3a5d3fab..1cebba2faf9 100644 --- a/core/services/promreporter/prom_reporter_test.go +++ b/core/services/promreporter/prom_reporter_test.go @@ -7,10 +7,11 @@ import ( "time" "github.com/jmoiron/sqlx" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + "github.com/smartcontractkit/chainlink/v2/core/chains/evm/gas" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/txmgr" @@ -76,8 +77,7 @@ func Test_PromReporter_OnNewLongestChain(t *testing.T) { }). Return() - require.NoError(t, reporter.Start(testutils.Context(t))) - defer func() { assert.NoError(t, reporter.Close()) }() + servicetest.Run(t, reporter) head := newHead() reporter.OnNewLongestChain(testutils.Context(t), &head) @@ -107,8 +107,7 @@ func Test_PromReporter_OnNewLongestChain(t *testing.T) { }). Return() reporter := promreporter.NewPromReporter(db.DB, newLegacyChainContainer(t, db), logger.TestLogger(t), backend, 10*time.Millisecond) - require.NoError(t, reporter.Start(testutils.Context(t))) - defer func() { assert.NoError(t, reporter.Close()) }() + servicetest.Run(t, reporter) etx := cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, 0, fromAddress) cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, 1, fromAddress) @@ -143,8 +142,7 @@ func Test_PromReporter_OnNewLongestChain(t *testing.T) { subscribeCalls.Add(1) }). Return() - require.NoError(t, reporter.Start(testutils.Context(t))) - defer func() { assert.NoError(t, reporter.Close()) }() + servicetest.Run(t, reporter) head := newHead() reporter.OnNewLongestChain(testutils.Context(t), &head) diff --git a/core/services/relay/evm/config_poller_test.go b/core/services/relay/evm/config_poller_test.go index 0a433c3bc54..3409c2f1591 100644 --- a/core/services/relay/evm/config_poller_test.go +++ b/core/services/relay/evm/config_poller_test.go @@ -7,8 +7,6 @@ import ( "time" "github.com/ethereum/go-ethereum" - "github.com/smartcontractkit/libocr/gethwrappers2/ocrconfigurationstoreevmsimple" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" @@ -22,12 +20,14 @@ import ( "github.com/stretchr/testify/require" "github.com/smartcontractkit/libocr/gethwrappers2/ocr2aggregator" + "github.com/smartcontractkit/libocr/gethwrappers2/ocrconfigurationstoreevmsimple" testoffchainaggregator2 "github.com/smartcontractkit/libocr/gethwrappers2/testocr2aggregator" "github.com/smartcontractkit/libocr/offchainreporting2/reportingplugin/median" confighelper2 "github.com/smartcontractkit/libocr/offchainreporting2plus/confighelper" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" ocrtypes2 "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" evmClientMocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" @@ -85,11 +85,9 @@ func TestConfigPoller(t *testing.T) { db := pgtest.NewSqlxDB(t) cfg := pgtest.NewQConfig(false) ethClient = evmclient.NewSimulatedBackendClient(t, b, testutils.SimulatedChainID) - ctx := testutils.Context(t) lorm := logpoller.NewORM(testutils.SimulatedChainID, db, lggr, cfg) lp = logpoller.NewLogPoller(lorm, ethClient, lggr, 100*time.Millisecond, false, 1, 2, 2, 1000) - require.NoError(t, lp.Start(ctx)) - t.Cleanup(func() { lp.Close() }) + servicetest.Run(t, lp) } t.Run("LatestConfig errors if there is no config in logs and config store is unconfigured", func(t *testing.T) { diff --git a/core/services/relay/evm/functions/config_poller_test.go b/core/services/relay/evm/functions/config_poller_test.go index 085f0c6e317..a5e5c1f8058 100644 --- a/core/services/relay/evm/functions/config_poller_test.go +++ b/core/services/relay/evm/functions/config_poller_test.go @@ -20,8 +20,7 @@ import ( confighelper2 "github.com/smartcontractkit/libocr/offchainreporting2plus/confighelper" ocrtypes2 "github.com/smartcontractkit/libocr/offchainreporting2plus/types" - functionsConfig "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/functions/config" - "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/testhelpers" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller" @@ -29,6 +28,8 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" "github.com/smartcontractkit/chainlink/v2/core/logger" + functionsConfig "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/functions/config" + "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/testhelpers" "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm" "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/functions" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -78,11 +79,9 @@ func runTest(t *testing.T, pluginType functions.FunctionsPluginType, expectedDig ethClient := evmclient.NewSimulatedBackendClient(t, b, big.NewInt(1337)) defer ethClient.Close() lggr := logger.TestLogger(t) - ctx := testutils.Context(t) lorm := logpoller.NewORM(big.NewInt(1337), db, lggr, cfg) lp := logpoller.NewLogPoller(lorm, ethClient, lggr, 100*time.Millisecond, false, 1, 2, 2, 1000) - defer lp.Close() - require.NoError(t, lp.Start(ctx)) + servicetest.Run(t, lp) configPoller, err := functions.NewFunctionsConfigPoller(pluginType, lp, lggr) require.NoError(t, err) require.NoError(t, configPoller.UpdateRoutes(ocrAddress, ocrAddress)) diff --git a/core/services/relay/evm/functions/logpoller_wrapper_test.go b/core/services/relay/evm/functions/logpoller_wrapper_test.go index 2108e822d5e..9df285b4c25 100644 --- a/core/services/relay/evm/functions/logpoller_wrapper_test.go +++ b/core/services/relay/evm/functions/logpoller_wrapper_test.go @@ -12,11 +12,11 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" evmclimocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client/mocks" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller" lpmocks "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller/mocks" "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/functions/generated/functions_coordinator" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/functions/config" "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/types" @@ -95,13 +95,12 @@ func TestLogPollerWrapper_SingleSubscriberEmptyEvents(t *testing.T) { subscriber := newSubscriber(1) lpWrapper.SubscribeToUpdates("mock_subscriber", subscriber) - require.NoError(t, lpWrapper.Start(testutils.Context(t))) + servicetest.Run(t, lpWrapper) subscriber.updates.Wait() reqs, resps, err := lpWrapper.LatestEvents() require.NoError(t, err) require.Equal(t, 0, len(reqs)) require.Equal(t, 0, len(resps)) - lpWrapper.Close() } func TestLogPollerWrapper_ErrorOnZeroAddresses(t *testing.T) { @@ -111,10 +110,9 @@ func TestLogPollerWrapper_ErrorOnZeroAddresses(t *testing.T) { client.On("CallContract", mock.Anything, mock.Anything, mock.Anything).Return(addr(t, "00"), nil) - require.NoError(t, lpWrapper.Start(testutils.Context(t))) + servicetest.Run(t, lpWrapper) _, _, err := lpWrapper.LatestEvents() require.Error(t, err) - lpWrapper.Close() } func TestLogPollerWrapper_LatestEvents_ReorgHandling(t *testing.T) { @@ -135,7 +133,7 @@ func TestLogPollerWrapper_LatestEvents_ReorgHandling(t *testing.T) { // On the 3rd query, the original request log appears again lp.On("Logs", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return([]logpoller.Log{mockedLog}, nil).Once() - require.NoError(t, lpWrapper.Start(testutils.Context(t))) + servicetest.Run(t, lpWrapper) subscriber.updates.Wait() oracleRequests, _, err := lpWrapper.LatestEvents() diff --git a/core/services/relay/evm/mercury/helpers_test.go b/core/services/relay/evm/mercury/helpers_test.go index 3a58a25a557..59e0e587813 100644 --- a/core/services/relay/evm/mercury/helpers_test.go +++ b/core/services/relay/evm/mercury/helpers_test.go @@ -17,6 +17,7 @@ import ( "github.com/smartcontractkit/libocr/offchainreporting2plus/chains/evmutil" ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" evmclient "github.com/smartcontractkit/chainlink/v2/core/chains/evm/client" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/logpoller" "github.com/smartcontractkit/chainlink/v2/core/gethwrappers/llo-feeds/generated/verifier" @@ -167,13 +168,11 @@ func SetupTH(t *testing.T, feedID common.Hash) TestHarness { cfg := pgtest.NewQConfig(false) ethClient := evmclient.NewSimulatedBackendClient(t, b, big.NewInt(1337)) lggr := logger.TestLogger(t) - ctx := testutils.Context(t) lorm := logpoller.NewORM(big.NewInt(1337), db, lggr, cfg) lp := logpoller.NewLogPoller(lorm, ethClient, lggr, 100*time.Millisecond, false, 1, 2, 2, 1000) eventBroadcaster := pgmocks.NewEventBroadcaster(t) subscription := pgmocks.NewSubscription(t) - require.NoError(t, lp.Start(ctx)) - t.Cleanup(func() { lp.Close() }) + servicetest.Run(t, lp) eventBroadcaster.On("Subscribe", "evm.insert_on_logs", "").Return(subscription, nil) diff --git a/core/services/relay/evm/mercury/wsrpc/cache/cache_set_test.go b/core/services/relay/evm/mercury/wsrpc/cache/cache_set_test.go index 4e19c7b56de..7d754b8326e 100644 --- a/core/services/relay/evm/mercury/wsrpc/cache/cache_set_test.go +++ b/core/services/relay/evm/mercury/wsrpc/cache/cache_set_test.go @@ -3,21 +3,19 @@ package cache import ( "testing" - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/logger" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" + "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" + "github.com/smartcontractkit/chainlink/v2/core/logger" ) func Test_CacheSet(t *testing.T) { lggr := logger.TestLogger(t) cs := newCacheSet(lggr, Config{}) ctx := testutils.Context(t) - require.NoError(t, cs.Start(ctx)) - t.Cleanup(func() { - assert.NoError(t, cs.Close()) - }) + servicetest.Run(t, cs) t.Run("Get", func(t *testing.T) { c := &mockClient{} diff --git a/core/services/relay/evm/mercury/wsrpc/client_test.go b/core/services/relay/evm/mercury/wsrpc/client_test.go index 9b0100a3cdd..f265d54879c 100644 --- a/core/services/relay/evm/mercury/wsrpc/client_test.go +++ b/core/services/relay/evm/mercury/wsrpc/client_test.go @@ -8,11 +8,12 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/csakey" "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/mercury/wsrpc/cache" - mocks "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/mercury/wsrpc/mocks" + "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/mercury/wsrpc/mocks" "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/mercury/wsrpc/pb" ) @@ -162,7 +163,7 @@ func Test_Client_LatestReport(t *testing.T) { // simulate start without dialling require.NoError(t, c.StartOnce("Mock WSRPC Client", func() error { return nil })) var err error - require.NoError(t, cacheSet.Start(ctx)) + servicetest.Run(t, cacheSet) c.cache, err = cacheSet.Get(ctx, c) require.NoError(t, err) @@ -200,7 +201,7 @@ func Test_Client_LatestReport(t *testing.T) { // simulate start without dialling require.NoError(t, c.StartOnce("Mock WSRPC Client", func() error { return nil })) var err error - require.NoError(t, cacheSet.Start(ctx)) + servicetest.Run(t, cacheSet) c.cache, err = cacheSet.Get(ctx, c) require.NoError(t, err) diff --git a/core/services/srvctest/servicetest.go b/core/services/srvctest/servicetest.go deleted file mode 100644 index ee888a46fa6..00000000000 --- a/core/services/srvctest/servicetest.go +++ /dev/null @@ -1,18 +0,0 @@ -package srvctest - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/services" -) - -// Start is test helper to automatically Start/Close a ServiceCtx along with a test. -func Start[S services.ServiceCtx](tb testing.TB, s S) S { - require.NoError(tb, s.Start(testutils.Context(tb))) - tb.Cleanup(func() { assert.NoError(tb, s.Close()) }) - return s -} diff --git a/core/services/synchronization/telemetry_ingress_batch_client_test.go b/core/services/synchronization/telemetry_ingress_batch_client_test.go index 6dd9d401a80..c4f6417131d 100644 --- a/core/services/synchronization/telemetry_ingress_batch_client_test.go +++ b/core/services/synchronization/telemetry_ingress_batch_client_test.go @@ -9,8 +9,8 @@ import ( "github.com/onsi/gomega" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/csakey" @@ -37,7 +37,7 @@ func TestTelemetryIngressBatchClient_HappyPath(t *testing.T) { serverPubKeyHex := "33333333333" sendInterval := time.Millisecond * 5 telemIngressClient := synchronization.NewTestTelemetryIngressBatchClient(t, url, serverPubKeyHex, csaKeystore, false, telemClient, sendInterval, false) - require.NoError(t, telemIngressClient.Start(testutils.Context(t))) + servicetest.Run(t, telemIngressClient) // Create telemetry payloads for different contracts telemPayload1 := synchronization.TelemPayload{ @@ -100,7 +100,4 @@ func TestTelemetryIngressBatchClient_HappyPath(t *testing.T) { g.Eventually(func() []uint32 { return []uint32{contractCounter1.Load(), contractCounter2.Load(), contractCounter3.Load()} }).Should(gomega.Equal([]uint32{3, 2, 1})) - - // Client should shut down - telemIngressClient.Close() } diff --git a/core/services/synchronization/telemetry_ingress_client_test.go b/core/services/synchronization/telemetry_ingress_client_test.go index 5a0cc23ecd0..55be107b977 100644 --- a/core/services/synchronization/telemetry_ingress_client_test.go +++ b/core/services/synchronization/telemetry_ingress_client_test.go @@ -9,8 +9,8 @@ import ( "github.com/onsi/gomega" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/keystore/keys/csakey" @@ -35,8 +35,7 @@ func TestTelemetryIngressClient_Send_HappyPath(t *testing.T) { url := &url.URL{} serverPubKeyHex := "33333333333" telemIngressClient := synchronization.NewTestTelemetryIngressClient(t, url, serverPubKeyHex, csaKeystore, false, telemClient) - require.NoError(t, telemIngressClient.Start(testutils.Context(t))) - defer func() { assert.NoError(t, telemIngressClient.Close()) }() + servicetest.Run(t, telemIngressClient) // Create the telemetry payload telemetry := []byte("101010") diff --git a/core/services/vrf/delegate_test.go b/core/services/vrf/delegate_test.go index 3c297026004..d957e3c721e 100644 --- a/core/services/vrf/delegate_test.go +++ b/core/services/vrf/delegate_test.go @@ -6,7 +6,15 @@ import ( "testing" "time" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" "github.com/jmoiron/sqlx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + + "github.com/smartcontractkit/chainlink-common/pkg/services/servicetest" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/chains/evm/assets" @@ -32,7 +40,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/pipeline" evmrelay "github.com/smartcontractkit/chainlink/v2/core/services/relay/evm" "github.com/smartcontractkit/chainlink/v2/core/services/signatures/secp256k1" - "github.com/smartcontractkit/chainlink/v2/core/services/srvctest" "github.com/smartcontractkit/chainlink/v2/core/services/vrf" vrf_mocks "github.com/smartcontractkit/chainlink/v2/core/services/vrf/mocks" "github.com/smartcontractkit/chainlink/v2/core/services/vrf/solidity_cross_tests" @@ -40,13 +47,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/services/vrf/vrfcommon" "github.com/smartcontractkit/chainlink/v2/core/testdata/testspecs" "github.com/smartcontractkit/chainlink/v2/core/utils" - - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" ) type vrfUniverse struct { @@ -149,7 +149,7 @@ func setup(t *testing.T) (vrfUniverse, *v1.Listener, job.Job) { cfg := configtest.NewTestGeneralConfig(t) vuni := buildVrfUni(t, db, cfg) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) vd := vrf.NewDelegate( db, @@ -176,8 +176,7 @@ func setup(t *testing.T) (vrfUniverse, *v1.Listener, job.Job) { go func() { listener.RunHeadListener(func() {}) }() - t.Cleanup(func() { listener.Stop(t) }) - require.NoError(t, listener.Start(testutils.Context(t))) + servicetest.Run(t, listener) return vuni, listener, jb } @@ -674,7 +673,7 @@ func Test_VRFV2PlusServiceFailsWhenVRFOwnerProvided(t *testing.T) { cfg := configtest.NewTestGeneralConfig(t) vuni := buildVrfUni(t, db, cfg) - mailMon := srvctest.Start(t, utils.NewMailboxMonitor(t.Name())) + mailMon := servicetest.Run(t, utils.NewMailboxMonitor(t.Name())) vd := vrf.NewDelegate( db, diff --git a/core/services/vrf/v1/listener_v1_test_helpers.go b/core/services/vrf/v1/listener_v1_test_helpers.go index e9adde35b58..f9532bf83e6 100644 --- a/core/services/vrf/v1/listener_v1_test_helpers.go +++ b/core/services/vrf/v1/listener_v1_test_helpers.go @@ -3,6 +3,8 @@ package v1 import ( "testing" "time" + + "github.com/stretchr/testify/assert" ) func (lsn *Listener) SetReqAdded(fn func()) { @@ -10,7 +12,7 @@ func (lsn *Listener) SetReqAdded(fn func()) { } func (lsn *Listener) Stop(t *testing.T) { - lsn.ChStop <- struct{}{} + assert.NoError(t, lsn.Close()) select { case <-lsn.WaitOnStop: case <-time.After(time.Second): diff --git a/core/web/jobs_controller_test.go b/core/web/jobs_controller_test.go index 1ce4fd08a36..3beee88c2eb 100644 --- a/core/web/jobs_controller_test.go +++ b/core/web/jobs_controller_test.go @@ -380,6 +380,7 @@ func TestJobController_Create_HappyPath(t *testing.T) { func TestJobsController_Create_WebhookSpec(t *testing.T) { app := cltest.NewApplicationEVMDisabled(t) require.NoError(t, app.Start(testutils.Context(t))) + t.Cleanup(func() { assert.NoError(t, app.Stop()) }) _, fetchBridge := cltest.MustCreateBridge(t, app.GetSqlxDB(), cltest.BridgeOpts{}, app.GetConfig().Database()) _, submitBridge := cltest.MustCreateBridge(t, app.GetSqlxDB(), cltest.BridgeOpts{}, app.GetConfig().Database())