-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
simulated_backend.go
72 lines (64 loc) · 2.58 KB
/
simulated_backend.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package cltest
import (
"sync"
"testing"
"time"
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
"github.com/ethereum/go-ethereum/core"
uuid "github.com/satori/go.uuid"
"github.com/stretchr/testify/require"
"github.com/smartcontractkit/chainlink/core/chains/evm/client"
coreconfig "github.com/smartcontractkit/chainlink/core/config"
"github.com/smartcontractkit/chainlink/core/internal/testutils"
"github.com/smartcontractkit/chainlink/core/logger"
"github.com/smartcontractkit/chainlink/core/services/pg"
"github.com/smartcontractkit/chainlink/core/utils"
)
func NewSimulatedBackend(t *testing.T, alloc core.GenesisAlloc, gasLimit uint32) *backends.SimulatedBackend {
backend := backends.NewSimulatedBackend(alloc, uint64(gasLimit))
// NOTE: Make sure to finish closing any application/client before
// backend.Close or they can hang
t.Cleanup(func() {
logger.TestLogger(t).ErrorIfFn(backend.Close, "Error closing simulated backend")
})
return backend
}
// NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain is like NewApplicationWithConfigAndKeyOnSimulatedBlockchain
// but cfg should be v2, and configtest.NewGeneralConfigSimulated used to include the simulated chain (testutils.SimulatedChainID).
func NewApplicationWithConfigV2AndKeyOnSimulatedBlockchain(
t testing.TB,
cfg coreconfig.GeneralConfig,
backend *backends.SimulatedBackend,
flagsAndDeps ...interface{},
) *TestApplication {
if bid := backend.Blockchain().Config().ChainID; bid.Cmp(testutils.SimulatedChainID) != 0 {
t.Fatalf("expected backend chain ID to be %s but it was %s", testutils.SimulatedChainID.String(), bid.String())
}
defID := cfg.DefaultChainID()
require.Zero(t, defID.Cmp(testutils.SimulatedChainID))
chainID := utils.NewBig(testutils.SimulatedChainID)
client := client.NewSimulatedBackendClient(t, backend, testutils.SimulatedChainID)
eventBroadcaster := pg.NewEventBroadcaster(cfg.DatabaseURL(), 0, 0, logger.TestLogger(t), uuid.NewV4())
flagsAndDeps = append(flagsAndDeps, client, eventBroadcaster, chainID)
// app.Stop() will call client.Close on the simulated backend
return NewApplicationWithConfigAndKey(t, cfg, flagsAndDeps...)
}
// Mine forces the simulated backend to produce a new block every 2 seconds
func Mine(backend *backends.SimulatedBackend, blockTime time.Duration) (stopMining func()) {
timer := time.NewTicker(blockTime)
chStop := make(chan struct{})
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
for {
select {
case <-timer.C:
backend.Commit()
case <-chStop:
wg.Done()
return
}
}
}()
return func() { close(chStop); timer.Stop(); wg.Wait() }
}