Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions core/bridges/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,34 +165,40 @@ func TestBridgeCache_Response(t *testing.T) {
t.Run("async upserts bridge response", func(t *testing.T) {
t.Parallel()

// A short tick so the test does not wait out the 5 s default.
const upsertInterval = 50 * time.Millisecond
mORM := new(mocks.ORM)
lggr, _ := logger.NewLogger()
cache := bridges.NewCache(mORM, lggr, bridges.DefaultUpsertInterval)
cache := bridges.NewCache(mORM, lggr, upsertInterval)

t.Cleanup(func() {
require.NoError(t, cache.Close())
})

chBulkUpsertCalled := make(chan struct{}, 1)
// Register the expectation before Start: the 50 ms tick can fire right away.
mORM.On("BulkUpsertBridgeResponse", mock.Anything, mock.Anything).Return(nil).Run(func(_ mock.Arguments) {
// Non-blocking: the short tick can upsert more than once.
select {
case chBulkUpsertCalled <- struct{}{}:
default:
}
})

require.NoError(t, cache.Start(t.Context()))

ctx := t.Context()
dotID := "test"
specID := int32(42)
expected := []byte("test")
chBulkUpsertCalled := make(chan struct{}, 1)

mORM.On("BulkUpsertBridgeResponse", mock.Anything, mock.Anything).Return(nil).Run(func(_ mock.Arguments) {
chBulkUpsertCalled <- struct{}{}
})

require.NoError(t, cache.UpsertBridgeResponse(ctx, dotID, specID, expected))

response, err := cache.GetCachedResponse(ctx, dotID, specID, time.Second)

require.NoError(t, err)
assert.Equal(t, expected, response)

timer := time.NewTimer(2 * bridges.DefaultUpsertInterval)
timer := time.NewTimer(2 * bridges.DefaultUpsertInterval) // generous bound; the upsert normally lands within ~50 ms

select {
case <-chBulkUpsertCalled:
Expand Down
3 changes: 3 additions & 0 deletions core/capabilities/ccip/launcher/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ func TestIntegration_Launcher(t *testing.T) {
uni,
uni.CapReg.Address().String(),
registrysyncer.NewORM(db, lggr),
// The DON is added to the registry after the initial sync, so without a
// short tick the test waits out the 12 s default.
registrysyncer.WithTickInterval(100*time.Millisecond),
)
require.NoError(t, err)

Expand Down
11 changes: 8 additions & 3 deletions core/capabilities/ccip/ocrimpls/contract_transmitter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ import (
"github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest"
)

// blockTick is how often the tests mine a block while polling, and how often the
// head tracker samples heads. The tx confirmer needs several new blocks before it
// writes a receipt, so this sets how long those tests take.
const blockTick = 100 * time.Millisecond

func Test_ContractTransmitter_TransmitWithoutSignatures(t *testing.T) {
t.Parallel()
type testCase struct {
Expand Down Expand Up @@ -159,7 +164,7 @@ func testTransmitter(
receipt, err := uni.simClient.TransactionReceipt(ctx, common.BytesToHash(txHash))
require.NoError(c, err)
txStatus = receipt.Status
}, testutils.WaitTimeout(t), 1*time.Second)
}, testutils.WaitTimeout(t), blockTick)

// wait for receipt to be written to the db
require.EventuallyWithT(t, func(c *assert.CollectT) {
Expand All @@ -168,7 +173,7 @@ func testTransmitter(
err := uni.db.GetContext(ctx, &count, `SELECT count(*) as cnt FROM evm.receipts LIMIT 1`)
require.NoError(c, err)
require.Equal(c, uint32(1), count)
}, testutils.WaitTimeout(t), 2*time.Second)
}, testutils.WaitTimeout(t), blockTick)

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

Expand Down Expand Up @@ -716,7 +721,7 @@ func (t *TestHeadTrackerConfig) MaxBufferSize() uint32 {

// SamplingInterval implements config.HeadTracker.
func (t *TestHeadTrackerConfig) SamplingInterval() time.Duration {
return 1 * time.Second
return blockTick
}

func (t *TestHeadTrackerConfig) PersistenceEnabled() bool {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,9 @@ func TestRegistrationCheckTrafficVolume(t *testing.T) {
t.Parallel()
synctest.Test(t, func(t *testing.T) {
ctx := t.Context()
lggr := logger.Test(t)
// The publisher logs every registration at debug (~43 MB across all
// cases) and this test only asserts on dispatcher counts.
lggr := logger.Nop()
dispatcher := newCountingDispatcher()

capDonMembers := generatePeers(t, tc.capDonSize)
Expand Down
22 changes: 19 additions & 3 deletions core/cmd/shell_local_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"flag"
"math/big"
"net"
"net/url"
"os"
"strconv"
Expand All @@ -20,6 +21,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/urfave/cli"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc"

commonkeystore "github.com/smartcontractkit/chainlink-common/keystore"
"github.com/smartcontractkit/chainlink-common/pkg/beholder"
Expand Down Expand Up @@ -599,6 +601,20 @@ func TestShell_BeforeNode(t *testing.T) {
}
}

// startFakeOTLPEndpoint starts a gRPC server with no OTLP services and returns its address. Exports get a
// non-retryable Unimplemented reply. With nothing listening, Beholder's final metrics flush on close retries
// "connection refused" for 10 s.
func startFakeOTLPEndpoint(t *testing.T) string {
t.Helper()
var lc net.ListenConfig
lis, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0")
require.NoError(t, err)
srv := grpc.NewServer()
go func() { _ = srv.Serve(lis) }()
t.Cleanup(srv.Stop)
return lis.Addr().String()
}

func TestShell_BeholderLifecycle(t *testing.T) {
testutils.SkipShortDB(t)
rawDBURL, ok := os.LookupEnv("CL_DATABASE_URL")
Expand Down Expand Up @@ -654,7 +670,7 @@ func TestShell_BeholderLifecycle(t *testing.T) {
shell, c := newShell(t, func(c *chainlink.Config, s *chainlink.Secrets) {
trueVal := true
c.Telemetry.Enabled = &trueVal
endpoint := "localhost:4317"
endpoint := startFakeOTLPEndpoint(t)
c.Telemetry.Endpoint = &endpoint
c.Telemetry.InsecureConnection = &trueVal
}, nil)
Expand All @@ -676,7 +692,7 @@ func TestShell_BeholderLifecycle(t *testing.T) {
shell, c := newShell(t, func(c *chainlink.Config, s *chainlink.Secrets) {
trueVal := true
c.Telemetry.Enabled = &trueVal
endpoint := "localhost:4317"
endpoint := startFakeOTLPEndpoint(t)
c.Telemetry.Endpoint = &endpoint
c.Telemetry.InsecureConnection = &trueVal
c.Telemetry.LogStreamingEnabled = &trueVal
Expand All @@ -694,7 +710,7 @@ func TestShell_BeholderLifecycle(t *testing.T) {
shell, c := newShell(t, func(c *chainlink.Config, s *chainlink.Secrets) {
trueVal := true
c.Telemetry.Enabled = &trueVal
endpoint := "localhost:4317"
endpoint := startFakeOTLPEndpoint(t)
c.Telemetry.Endpoint = &endpoint
c.Telemetry.InsecureConnection = &trueVal
c.Telemetry.LogStreamingEnabled = &trueVal
Expand Down
25 changes: 22 additions & 3 deletions core/internal/cltest/cltest.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"go.uber.org/zap/zapcore"

ocrtypes "github.com/smartcontractkit/libocr/offchainreporting/types"
"github.com/smartcontractkit/libocr/offchainreporting2plus/ocr3_1types"
Expand Down Expand Up @@ -252,6 +253,18 @@ func NewApplicationWithConfigAndKey(t testing.TB, c chainlink.GeneralConfig, fla
}

// NewApplicationWithConfig creates a New TestApplication with specified test config.
// appLogLevel is the level for the logger of an application that a test did not
// give one. It follows the config (Info unless the test sets [Log] Level), not
// Debug: the EVM services alone print thousands of debug lines per second, and each
// line costs encoding, a stack lookup and the test output lock. Set
// CL_TEST_DEBUG_LOGS=1 to get debug output back when chasing a failure.
func appLogLevel(cfg chainlink.GeneralConfig) zapcore.Level {
if os.Getenv("CL_TEST_DEBUG_LOGS") != "" {
return zapcore.DebugLevel
}
return cfg.Log().Level()
}

// This should only be used in full integration tests. For controller tests, see NewApplicationEVMDisabled.
func NewApplicationWithConfig(t testing.TB, cfg chainlink.GeneralConfig, flagsAndDeps ...any) *TestApplication {
t.Helper()
Expand All @@ -268,7 +281,7 @@ func NewApplicationWithConfig(t testing.TB, cfg chainlink.GeneralConfig, flagsAn
}
}
if lggr == nil {
lggr = logger.TestLogger(t)
lggr = logger.TestLogger(t, appLogLevel(cfg))
}

var auditLogger audit.Logger
Expand Down Expand Up @@ -385,7 +398,7 @@ func NewApplicationWithConfig(t testing.TB, cfg chainlink.GeneralConfig, flagsAn
}
}
}
keyStore := keystore.NewInMemory(ds, commonkeystore.FastScryptParams, lggr.Infof)
keyStore := keystore.NewInMemory(ds, TestScryptParams, lggr.Infof)
require.NoError(t, keyStore.Unlock(ctx, Password))
logPubKeys(t, keyStore)

Expand Down Expand Up @@ -793,10 +806,16 @@ func (ta *TestApplication) NewAuthenticatingShell(prompter cmd.Prompter) *cmd.Sh
return client
}

// TestScryptParams is the cheapest scrypt cost (N=2^4) for test keystores.
// The keyring is re-encrypted on every key add, so FastScryptParams (N=2^14,
// ~16 MB per call) was a measurable share of CPU in suites that start many
// apps. Tests of encryption itself should use real params.
var TestScryptParams = commonkeystore.ScryptParams{N: 1 << 4, P: 1}

// NewKeyStore returns a new, unlocked keystore
func NewKeyStore(t testing.TB, ds sqlutil.DataSource) keystore.Master {
ctx := t.Context()
keystore := keystore.NewInMemory(ds, commonkeystore.FastScryptParams, logger.TestLogger(t).Infof)
keystore := keystore.NewInMemory(ds, TestScryptParams, logger.TestLogger(t).Infof)
require.NoError(t, keystore.Unlock(ctx, Password))
logPubKeys(t, keystore)
return keystore
Expand Down
1 change: 1 addition & 0 deletions core/internal/features/ocr2/features_ocr2_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ name = "bootstrap"
relay = "evm"
schemaVersion = 1
contractID = "%s"
contractConfigTrackerPollInterval = "1s"
[relayConfig]
chainID = 1337
fromBlock = %d
Expand Down
1 change: 1 addition & 0 deletions core/internal/features/ocr2/features_ocr2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ relay = "evm"
schemaVersion = 1
forwardingAllowed = true
contractID = "%s"
contractConfigTrackerPollInterval = "1s"
[relayConfig]
chainID = 1337
`, ocrContractAddress)
Expand Down
5 changes: 3 additions & 2 deletions core/internal/testutils/pgtest/txdb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,9 @@ func TestTxDBDriver(t *testing.T) {
cancel()
// BeginTx spawns separate goroutine that rollbacks the tx and tries to close underlying connection, unless
// db driver says that connection is still active.
// This approach is not ideal, but there is no better way to wait for independent goroutine to complete
time.Sleep(time.Second * 10)
// This approach is not ideal, but there is no better way to wait for independent goroutine to complete.
// The goroutine runs as soon as the context is cancelled, so a second is ample.
time.Sleep(time.Second)
ensureValuesPresent(t, db)
})
}
23 changes: 15 additions & 8 deletions core/services/gateway/network/httpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,12 @@ func TestHTTPClient_Send(t *testing.T) {
name: "context canceled due to timeout passed in request",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(10 * time.Second)
w.WriteHeader(http.StatusOK)
_, err2 := w.Write([]byte("success"))
assert.NoError(t, err2)
// Hold the response until the client gives up. A fixed sleep would
// make server.Close wait for the full duration.
select {
case <-r.Context().Done():
case <-time.After(10 * time.Second):
}
}))
},
request: HTTPRequest{
Expand All @@ -110,10 +112,12 @@ func TestHTTPClient_Send(t *testing.T) {
name: "context canceled due to default timeout",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(10 * time.Second)
w.WriteHeader(http.StatusOK)
_, err2 := w.Write([]byte("success"))
assert.NoError(t, err2)
// Hold the response until the client gives up. A fixed sleep would
// make server.Close wait for the full duration.
select {
case <-r.Context().Done():
case <-time.After(10 * time.Second):
}
}))
},
request: HTTPRequest{
Expand All @@ -122,6 +126,9 @@ func TestHTTPClient_Send(t *testing.T) {
Headers: map[string]string{},
Body: nil,
},
configOption: func(hc *HTTPClientConfig) {
hc.DefaultTimeout = 200 * time.Millisecond
},
expectedError: context.DeadlineExceeded,
},
{
Expand Down
35 changes: 31 additions & 4 deletions core/services/job/job_orm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import (
"context"
"database/sql"
"fmt"
"slices"
"testing"
"time"

"github.com/ethereum/go-ethereum/common"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -1563,13 +1565,16 @@ func Test_FindPipelineRunIDsByJobID(t *testing.T) {
jobs[j] = jb
}

// Runs are spread across the jobs in turn so their ids interleave.
toInsert := make([]job.Job, 0, 2500)
for i, j := 0, 0; i < 2500; i++ {
mustInsertPipelineRun(t, pipelineORM, jobs[j])
toInsert = append(toInsert, jobs[j])
j++
if j == len(jobs)-1 {
j = 0
}
}
mustInsertPipelineRuns(t, db, toInsert)

t.Run("with no pipeline runs", func(t *testing.T) {
ctx := t.Context()
Expand Down Expand Up @@ -1609,9 +1614,7 @@ func Test_FindPipelineRunIDsByJobID(t *testing.T) {
assert.Equal(t, int64(67*(len(jobs)-1)), runIDs[12]-runIDs[79])
})

for range 2100 {
mustInsertPipelineRun(t, pipelineORM, jb)
}
mustInsertPipelineRuns(t, db, slices.Repeat([]job.Job{jb}, 2100))

// There is a COUNT query which doesn't run unless the query for the most recent 1000 rows
// returns empty. This can happen if the job id being requested hasn't run in a while,
Expand Down Expand Up @@ -1878,6 +1881,30 @@ func Test_CountPipelineRunsByJobID(t *testing.T) {
})
}

// mustInsertPipelineRuns inserts one running pipeline run per entry of jobs in a single
// statement, so ids follow the order of jobs. Use it instead of looping over
// mustInsertPipelineRun when a test needs thousands of rows.
func mustInsertPipelineRuns(t *testing.T, db *sqlx.DB, jobs []job.Job) {
t.Helper()

now := time.Now()
runs := make([]pipeline.Run, len(jobs))
for i, j := range jobs {
runs[i] = pipeline.Run{
PipelineSpecID: j.PipelineSpecID,
PruningKey: j.ID,
State: pipeline.RunStatusRunning,
Outputs: jsonserializable.JSONSerializable{Valid: false},
AllErrors: pipeline.RunErrors{},
CreatedAt: now.Add(time.Duration(i) * time.Microsecond),
FinishedAt: null.Time{},
}
}
_, err := db.NamedExecContext(t.Context(), `INSERT INTO pipeline_runs (pipeline_spec_id, pruning_key, meta, all_errors, fatal_errors, inputs, outputs, created_at, finished_at, state)
VALUES (:pipeline_spec_id, :pruning_key, :meta, :all_errors, :fatal_errors, :inputs, :outputs, :created_at, :finished_at, :state)`, runs)
require.NoError(t, err)
}

func mustInsertPipelineRun(t *testing.T, orm pipeline.ORM, j job.Job) pipeline.Run {
t.Helper()
ctx := t.Context()
Expand Down
2 changes: 1 addition & 1 deletion core/services/ocr2/plugins/llo/don_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ func runDONBench(t *testing.T, version lloconfig.PluginVersion, salt int64, donI

bootstrapCSAKey := csakey.MustNewV2XXXTestingOnly(big.NewInt(salt - 1))
bootstrapNodePort := freeport.GetOne(t)
appBootstrap, bootstrapPeerID, _, bootstrapKb, _ := setupNode(t, bootstrapNodePort, fmt.Sprintf("bootstrap_llo_bench_%s", version), backend, bootstrapCSAKey, func(c *chainlink.Config) {
appBootstrap, bootstrapPeerID, _, bootstrapKb := setupNode(t, bootstrapNodePort, fmt.Sprintf("bootstrap_llo_bench_%s", version), backend, bootstrapCSAKey, func(c *chainlink.Config) {
c.Log.Level = new(logLevel)
onP2PHost(c)
})
Expand Down
Loading
Loading