Skip to content

Commit

Permalink
Added Clock. Made recent tests using Clock (smartcontractkit#9603)
Browse files Browse the repository at this point in the history
Co-authored-by: Morgan Kuphal <[email protected]>
  • Loading branch information
Andrei Smirnov and KuphJr authored Jun 16, 2023
1 parent 49d9c2e commit 82ed1c0
Show file tree
Hide file tree
Showing 18 changed files with 154 additions and 203 deletions.
15 changes: 0 additions & 15 deletions core/internal/cltest/mocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 +69,6 @@ func (mes *MockSubscription) Unsubscribe() {
close(mes.Errors)
}

// InstantClock an InstantClock
type InstantClock struct{}

// Now returns the current local time
func (InstantClock) Now() time.Time {
return time.Now()
}

// After return channel of time
func (InstantClock) After(_ time.Duration) <-chan time.Time {
c := make(chan time.Time, 100)
c <- time.Now()
return c
}

// RendererMock a mock renderer
type RendererMock struct {
Renders []interface{}
Expand Down
14 changes: 14 additions & 0 deletions core/internal/testutils/testutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package testutils

import (
"context"
"crypto/ecdsa"
"crypto/rand"
"flag"
"fmt"
Expand Down Expand Up @@ -65,6 +66,19 @@ func NewAddressPtr() *common.Address {
return &a
}

// NewPrivateKeyAndAddress returns a new private key and the corresponding address
func NewPrivateKeyAndAddress(t testing.TB) (*ecdsa.PrivateKey, common.Address) {
privateKey, err := crypto.GenerateKey()
require.NoError(t, err)

publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
require.True(t, ok)

address := crypto.PubkeyToAddress(*publicKeyECDSA)
return privateKey, address
}

// NewRandomPositiveInt64 returns a (non-cryptographically secure) random positive int64
func NewRandomPositiveInt64() int64 {
id := mrand.Int63()
Expand Down
43 changes: 0 additions & 43 deletions core/services/gateway/common/mocks/clock.go

This file was deleted.

19 changes: 0 additions & 19 deletions core/services/gateway/common/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,10 @@ package common

import (
"encoding/binary"
"time"

"golang.org/x/exp/slices"
)

// An easily-mockable clock interface.
//
//go:generate mockery --quiet --name Clock --output ./mocks/ --case=underscore
type Clock interface {
Now() time.Time
}

type realClock struct {
}

func NewRealClock() Clock {
return &realClock{}
}

func (*realClock) Now() time.Time {
return time.Now()
}

func Uint32ToBytes(val uint32) []byte {
result := make([]byte, 4)
binary.BigEndian.PutUint32(result, val)
Expand Down
5 changes: 2 additions & 3 deletions core/services/gateway/connectionmanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (

"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/api"
gw_common "github.com/smartcontractkit/chainlink/v2/core/services/gateway/common"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/config"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/handlers"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/network"
Expand All @@ -35,7 +34,7 @@ type connectionManager struct {
config *config.ConnectionManagerConfig
dons map[string]*donConnectionManager
wsServer network.WebSocketServer
clock gw_common.Clock
clock utils.Clock
connAttempts map[string]*connAttempt
connAttemptCounter uint64
connAttemptsMu sync.Mutex
Expand Down Expand Up @@ -66,7 +65,7 @@ type connAttempt struct {
timestamp uint32
}

func NewConnectionManager(gwConfig *config.GatewayConfig, clock gw_common.Clock, lggr logger.Logger) (ConnectionManager, error) {
func NewConnectionManager(gwConfig *config.GatewayConfig, clock utils.Clock, lggr logger.Logger) (ConnectionManager, error) {
codec := &api.JsonRPCCodec{}
dons := make(map[string]*donConnectionManager)
for _, donConfig := range gwConfig.Dons {
Expand Down
9 changes: 5 additions & 4 deletions core/services/gateway/connectionmanager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package gateway_test

import (
"testing"
"time"

"github.com/stretchr/testify/require"

"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway"
common_mocks "github.com/smartcontractkit/chainlink/v2/core/services/gateway/common/mocks"
"github.com/smartcontractkit/chainlink/v2/core/utils"
)

const defaultConfig = `
Expand Down Expand Up @@ -36,7 +37,7 @@ func TestConnectionManager_NewConnectionManager_ValidConfig(t *testing.T) {

tomlConfig := parseTOMLConfig(t, defaultConfig)

_, err := gateway.NewConnectionManager(tomlConfig, common_mocks.NewClock(t), logger.TestLogger(t))
_, err := gateway.NewConnectionManager(tomlConfig, utils.NewFixedClock(time.Now()), logger.TestLogger(t))
require.NoError(t, err)
}

Expand Down Expand Up @@ -68,7 +69,7 @@ Address = "0x68902d681c28119f9b2531473a417088bf008e59"
fullConfig := `
[nodeServerConfig]
Path = "/node"` + config
_, err := gateway.NewConnectionManager(parseTOMLConfig(t, fullConfig), common_mocks.NewClock(t), logger.TestLogger(t))
_, err := gateway.NewConnectionManager(parseTOMLConfig(t, fullConfig), utils.NewFixedClock(time.Now()), logger.TestLogger(t))
require.Error(t, err)
})
}
Expand All @@ -77,7 +78,7 @@ Path = "/node"` + config
func TestConnectionManager_StartHandshake_TooShort(t *testing.T) {
t.Parallel()

mgr, err := gateway.NewConnectionManager(parseTOMLConfig(t, defaultConfig), common_mocks.NewClock(t), logger.TestLogger(t))
mgr, err := gateway.NewConnectionManager(parseTOMLConfig(t, defaultConfig), utils.NewFixedClock(time.Now()), logger.TestLogger(t))
require.NoError(t, err)

_, _, err = mgr.StartHandshake([]byte("ab"))
Expand Down
5 changes: 2 additions & 3 deletions core/services/gateway/connector/connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (

"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/api"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/common"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/network"
"github.com/smartcontractkit/chainlink/v2/core/services/job"
"github.com/smartcontractkit/chainlink/v2/core/utils"
Expand Down Expand Up @@ -49,7 +48,7 @@ type gatewayConnector struct {

config *ConnectorConfig
codec api.Codec
clock common.Clock
clock utils.Clock
nodeAddress []byte
signer Signer
handler GatewayConnectorHandler
Expand All @@ -66,7 +65,7 @@ type gatewayState struct {
wsClient network.WebSocketClient
}

func NewGatewayConnector(config *ConnectorConfig, signer Signer, handler GatewayConnectorHandler, clock common.Clock, lggr logger.Logger) (GatewayConnector, error) {
func NewGatewayConnector(config *ConnectorConfig, signer Signer, handler GatewayConnectorHandler, clock utils.Clock, lggr logger.Logger) (GatewayConnector, error) {
if signer == nil || handler == nil || clock == nil {
return nil, errors.New("nil dependency")
}
Expand Down
13 changes: 6 additions & 7 deletions core/services/gateway/connector/connector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import (
"github.com/stretchr/testify/require"

"github.com/smartcontractkit/chainlink/v2/core/logger"
common_mocks "github.com/smartcontractkit/chainlink/v2/core/services/gateway/common/mocks"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/connector"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/connector/mocks"
"github.com/smartcontractkit/chainlink/v2/core/utils"
)

const defaultConfig = `
Expand All @@ -36,13 +36,13 @@ func parseTOMLConfig(t *testing.T, tomlConfig string) *connector.ConnectorConfig
return &cfg
}

func newTestConnector(t *testing.T, config *connector.ConnectorConfig) (connector.GatewayConnector, *mocks.Signer, *mocks.GatewayConnectorHandler, *common_mocks.Clock) {
func newTestConnector(t *testing.T, config *connector.ConnectorConfig) (connector.GatewayConnector, *mocks.Signer, *mocks.GatewayConnectorHandler) {
signer := mocks.NewSigner(t)
handler := mocks.NewGatewayConnectorHandler(t)
clock := common_mocks.NewClock(t)
clock := utils.NewFixedClock(time.Now())
connector, err := connector.NewGatewayConnector(config, signer, handler, clock, logger.TestLogger(t))
require.NoError(t, err)
return connector, signer, handler, clock
return connector, signer, handler
}

func TestGatewayConnector_NewGatewayConnector_ValidConfig(t *testing.T) {
Expand Down Expand Up @@ -88,7 +88,7 @@ URL = "ws://localhost:8081/node"

signer := mocks.NewSigner(t)
handler := mocks.NewGatewayConnectorHandler(t)
clock := common_mocks.NewClock(t)
clock := utils.NewFixedClock(time.Now())
for name, config := range invalidCases {
config := config
t.Run(name, func(t *testing.T) {
Expand All @@ -101,8 +101,7 @@ URL = "ws://localhost:8081/node"
func TestGatewayConnector_NewAuthHeader_SignerError(t *testing.T) {
t.Parallel()

connector, signer, _, clock := newTestConnector(t, parseTOMLConfig(t, defaultConfig))
clock.On("Now").Return(time.Now())
connector, signer, _ := newTestConnector(t, parseTOMLConfig(t, defaultConfig))
signer.On("Sign", mock.Anything).Return(nil, errors.New("cannot sign"))

url, err := url.Parse("ws://localhost:8081/node")
Expand Down
3 changes: 1 addition & 2 deletions core/services/gateway/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (

"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/api"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/common"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/config"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/handlers"
gw_net "github.com/smartcontractkit/chainlink/v2/core/services/gateway/network"
Expand All @@ -34,7 +33,7 @@ type gateway struct {
func NewGatewayFromConfig(config *config.GatewayConfig, lggr logger.Logger) (Gateway, error) {
codec := &api.JsonRPCCodec{}
httpServer := gw_net.NewHttpServer(&config.UserServerConfig, lggr)
connMgr, err := NewConnectionManager(config, common.NewRealClock(), lggr)
connMgr, err := NewConnectionManager(config, utils.NewRealClock(), lggr)
if err != nil {
return nil, err
}
Expand Down
3 changes: 1 addition & 2 deletions core/services/ocr2/plugins/functions/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"github.com/smartcontractkit/chainlink/v2/core/gethwrappers/generated/ocr2dr_oracle"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services/functions"
gw_common "github.com/smartcontractkit/chainlink/v2/core/services/gateway/common"
"github.com/smartcontractkit/chainlink/v2/core/services/gateway/connector"
"github.com/smartcontractkit/chainlink/v2/core/services/job"
"github.com/smartcontractkit/chainlink/v2/core/services/keystore"
Expand Down Expand Up @@ -107,7 +106,7 @@ func NewConnector(gwcCfg *connector.ConnectorConfig, ethKeystore keystore.Eth, c
signerKey := enabledKeys[idx].ToEcdsaPrivKey()

handler := functions.NewFunctionsConnectorHandler(signerKey, lggr)
connector, err := connector.NewGatewayConnector(gwcCfg, handler, handler, gw_common.NewRealClock(), lggr)
connector, err := connector.NewGatewayConnector(gwcCfg, handler, handler, utils.NewRealClock(), lggr)
if err != nil {
return nil, err
}
Expand Down
5 changes: 3 additions & 2 deletions core/services/ocr2/plugins/s4/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"testing"
"time"

"github.com/smartcontractkit/chainlink/v2/core/internal/cltest"
"github.com/smartcontractkit/chainlink/v2/core/internal/testutils"
"github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest"
"github.com/smartcontractkit/chainlink/v2/core/logger"
Expand Down Expand Up @@ -358,7 +359,7 @@ func TestS4Integration_RandomState(t *testing.T) {
nUsers := 100
users := make([]user, nUsers)
for i := 0; i < nUsers; i++ {
pk, _, addr := generateCryptoEntity(t)
pk, addr := testutils.NewPrivateKeyAndAddress(t)
users[i] = user{pk, utils.NewBig(addr.Big())}
}

Expand All @@ -372,7 +373,7 @@ func TestS4Integration_RandomState(t *testing.T) {
Version: uint64(rand.Intn(don.size)),
Confirmed: rand.Intn(2) == 0,
Expiration: time.Now().UTC().Add(time.Minute).UnixMilli(),
Payload: mustRandomBytes(t, 64),
Payload: cltest.MustRandomBytes(t, 64),
}
env := &s4_svc.Envelope{
Address: common.BytesToAddress(user.address.Bytes()).Bytes(),
Expand Down
5 changes: 3 additions & 2 deletions core/services/ocr2/plugins/s4/messages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"
"time"

"github.com/smartcontractkit/chainlink/v2/core/internal/testutils"
"github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/s4"
s4_svc "github.com/smartcontractkit/chainlink/v2/core/services/s4"

Expand Down Expand Up @@ -66,9 +67,9 @@ func Test_VerifySignature(t *testing.T) {
require.Error(t, err)

t.Run("address with leading zeros", func(t *testing.T) {
pk, _, addr := generateCryptoEntity(t)
pk, addr := testutils.NewPrivateKeyAndAddress(t)
for addr[0] != 0 {
pk, _, addr = generateCryptoEntity(t)
pk, addr = testutils.NewPrivateKeyAndAddress(t)
}
rows := generateTestRows(t, 1, time.Minute)
rows[0].Address = addr.Big().Bytes()
Expand Down
Loading

0 comments on commit 82ed1c0

Please sign in to comment.