forked from cosmos/ibc-go
-
Notifications
You must be signed in to change notification settings - Fork 7
/
testsuite.go
339 lines (286 loc) · 11.6 KB
/
testsuite.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package testsuite
import (
"context"
"e2e/testconfig"
"fmt"
"io/ioutil"
"strings"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
dockerclient "github.com/docker/docker/client"
"github.com/strangelove-ventures/ibctest"
"github.com/strangelove-ventures/ibctest/broadcast"
"github.com/strangelove-ventures/ibctest/chain/cosmos"
"github.com/strangelove-ventures/ibctest/ibc"
"github.com/strangelove-ventures/ibctest/test"
"github.com/strangelove-ventures/ibctest/testreporter"
"github.com/stretchr/testify/suite"
"go.uber.org/zap"
"go.uber.org/zap/zaptest"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
feetypes "github.com/cosmos/ibc-go/v4/modules/apps/29-fee/types"
)
const (
// ChainARelayerName is the name given to the relayer wallet on ChainA
ChainARelayerName = "rlyA"
// ChainBRelayerName is the name given to the relayer wallet on ChainB
ChainBRelayerName = "rlyB"
)
// E2ETestSuite has methods and functionality which can be shared among all test suites.
type E2ETestSuite struct {
suite.Suite
grpcClients map[string]GRPCClients
paths map[string]path
logger *zap.Logger
DockerClient *dockerclient.Client
network string
startRelayerFn func(relayer ibc.Relayer)
}
// GRPCClients holds a reference to any GRPC clients that are needed by the tests.
// These should typically be used for query clients only. If we need to make changes, we should
// use E2ETestSuite.BroadcastMessages to broadcast transactions instead.
type GRPCClients struct {
FeeQueryClient feetypes.QueryClient
}
// path is a pairing of two chains which will be used in a test.
type path struct {
chainA, chainB *cosmos.CosmosChain
}
// newPath returns a path built from the given chains.
func newPath(chainA, chainB *cosmos.CosmosChain) path {
return path{
chainA: chainA,
chainB: chainB,
}
}
// GetRelayerUsers returns two ibctest.User instances which can be used for the relayer users
// on the two chains.
func (s *E2ETestSuite) GetRelayerUsers(ctx context.Context, chainOpts ...testconfig.ChainOptionConfiguration) (*ibctest.User, *ibctest.User) {
chainA, chainB := s.GetChains(chainOpts...)
chainAAccountBytes, err := chainA.GetAddress(ctx, ChainARelayerName)
s.Require().NoError(err)
chainBAccountBytes, err := chainB.GetAddress(ctx, ChainBRelayerName)
s.Require().NoError(err)
chainARelayerUser := ibctest.User{
Address: chainAAccountBytes,
KeyName: ChainARelayerName,
}
chainBRelayerUser := ibctest.User{
Address: chainBAccountBytes,
KeyName: ChainBRelayerName,
}
return &chainARelayerUser, &chainBRelayerUser
}
// SetupChainsRelayerAndChannel create two chains, a relayer, establishes a connection and creates a channel
// using the given channel options. The relayer returned by this function has not yet started. It should be started
// with E2ETestSuite.StartRelayer if needed.
// This should be called at the start of every test, unless fine grained control is required.
func (s *E2ETestSuite) SetupChainsRelayerAndChannel(ctx context.Context, channelOpts ...func(*ibc.CreateChannelOptions)) (ibc.Relayer, ibc.ChannelOutput) {
chainA, chainB := s.GetChains()
home, err := ioutil.TempDir("", "")
s.Require().NoError(err)
r := newCosmosRelayer(s.T(), testconfig.FromEnv(), s.logger, s.DockerClient, s.network)
pathName := fmt.Sprintf("%s-path", s.T().Name())
pathName = strings.ReplaceAll(pathName, "/", "-")
ic := ibctest.NewInterchain().
AddChain(chainA).
AddChain(chainB).
AddRelayer(r, "r").
AddLink(ibctest.InterchainLink{
Chain1: chainA,
Chain2: chainB,
Relayer: r,
Path: pathName,
})
channelOptions := ibc.DefaultChannelOpts()
for _, opt := range channelOpts {
opt(&channelOptions)
}
eRep := s.getRelayerExecReporter()
s.Require().NoError(ic.Build(ctx, eRep, ibctest.InterchainBuildOptions{
TestName: s.T().Name(),
HomeDir: home,
Client: s.DockerClient,
NetworkID: s.network,
CreateChannelOpts: channelOptions,
}))
s.startRelayerFn = func(relayer ibc.Relayer) {
err := relayer.StartRelayer(ctx, eRep, pathName)
s.Require().NoError(err, fmt.Sprintf("failed to start relayer: %s", err))
s.T().Cleanup(func() {
if !s.T().Failed() {
if err := relayer.StopRelayer(ctx, eRep); err != nil {
s.T().Logf("error stopping relayer: %v", err)
}
}
})
// wait for relayer to start.
time.Sleep(time.Second * 10)
}
s.initGRPCClients(chainA)
s.initGRPCClients(chainB)
chainAChannels, err := r.GetChannels(ctx, eRep, chainA.Config().ChainID)
s.Require().NoError(err)
return r, chainAChannels[len(chainAChannels)-1]
}
// GetChains returns two chains that can be used in a test. The pair returned
// is unique to the current test being run. Note: this function does not create containers.
func (s *E2ETestSuite) GetChains(chainOpts ...testconfig.ChainOptionConfiguration) (*cosmos.CosmosChain, *cosmos.CosmosChain) {
if s.paths == nil {
s.paths = map[string]path{}
}
path, ok := s.paths[s.T().Name()]
if ok {
return path.chainA, path.chainB
}
chainOptions := testconfig.DefaultChainOptions()
for _, opt := range chainOpts {
opt(&chainOptions)
}
chainA, chainB := s.createCosmosChains(chainOptions)
path = newPath(chainA, chainB)
s.paths[s.T().Name()] = path
return path.chainA, path.chainB
}
// BroadcastMessages broadcasts the provided messages to the given chain and signs them on behalf of the provided user.
// Once the broadcast response is returned, we wait for a few blocks to be created on both chain A and chain B.
func (s *E2ETestSuite) BroadcastMessages(ctx context.Context, chain *cosmos.CosmosChain, user broadcast.User, msgs ...sdk.Msg) (sdk.TxResponse, error) {
broadcaster := cosmos.NewBroadcaster(s.T(), chain)
resp, err := ibctest.BroadcastTx(ctx, broadcaster, user, msgs...)
if err != nil {
return sdk.TxResponse{}, err
}
chainA, chainB := s.GetChains()
err = test.WaitForBlocks(ctx, 2, chainA, chainB)
return resp, err
}
// GetRelayerWallets returns the relayer wallets associated with the chains.
func (s *E2ETestSuite) GetRelayerWallets(relayer ibc.Relayer) (ibc.RelayerWallet, ibc.RelayerWallet, error) {
chainA, chainB := s.GetChains()
chainARelayerWallet, ok := relayer.GetWallet(chainA.Config().ChainID)
if !ok {
return ibc.RelayerWallet{}, ibc.RelayerWallet{}, fmt.Errorf("unable to find chain A relayer wallet")
}
chainBRelayerWallet, ok := relayer.GetWallet(chainB.Config().ChainID)
if !ok {
return ibc.RelayerWallet{}, ibc.RelayerWallet{}, fmt.Errorf("unable to find chain B relayer wallet")
}
return chainARelayerWallet, chainBRelayerWallet, nil
}
// RecoverRelayerWallets adds the corresponding relayer address to the keychain of the chain.
// This is useful if commands executed on the chains expect the relayer information to present in the keychain.
func (s *E2ETestSuite) RecoverRelayerWallets(ctx context.Context, relayer ibc.Relayer) error {
chainARelayerWallet, chainBRelayerWallet, err := s.GetRelayerWallets(relayer)
if err != nil {
return err
}
chainA, chainB := s.GetChains()
if err := chainA.RecoverKey(ctx, ChainARelayerName, chainARelayerWallet.Mnemonic); err != nil {
return fmt.Errorf("could not recover relayer wallet on chain A: %s", err)
}
if err := chainB.RecoverKey(ctx, ChainBRelayerName, chainBRelayerWallet.Mnemonic); err != nil {
return fmt.Errorf("could not recover relayer wallet on chain B: %s", err)
}
return nil
}
// StartRelayer starts the given relayer.
func (s *E2ETestSuite) StartRelayer(relayer ibc.Relayer) {
if s.startRelayerFn == nil {
panic("cannot start relayer before it is created!")
}
s.startRelayerFn(relayer)
}
// CreateUserOnChainA creates a user with the given amount of funds on chain A.
func (s *E2ETestSuite) CreateUserOnChainA(ctx context.Context, amount int64) *ibctest.User {
chainA, _ := s.GetChains()
return ibctest.GetAndFundTestUsers(s.T(), ctx, strings.ReplaceAll(s.T().Name(), " ", "-"), amount, chainA)[0]
}
// CreateUserOnChainB creates a user with the given amount of funds on chain B.
func (s *E2ETestSuite) CreateUserOnChainB(ctx context.Context, amount int64) *ibctest.User {
_, chainB := s.GetChains()
return ibctest.GetAndFundTestUsers(s.T(), ctx, strings.ReplaceAll(s.T().Name(), " ", "-"), amount, chainB)[0]
}
// GetChainANativeBalance gets the balance of a given user on chain A.
func (s *E2ETestSuite) GetChainANativeBalance(ctx context.Context, user *ibctest.User) (int64, error) {
chainA, _ := s.GetChains()
return GetNativeChainBalance(ctx, chainA, user)
}
// GetChainBNativeBalance gets the balance of a given user on chain B.
func (s *E2ETestSuite) GetChainBNativeBalance(ctx context.Context, user *ibctest.User) (int64, error) {
_, chainB := s.GetChains()
return GetNativeChainBalance(ctx, chainB, user)
}
// GetChainGRCPClients gets the GRPC clients associated with the given chain.
func (s *E2ETestSuite) GetChainGRCPClients(chain ibc.Chain) GRPCClients {
cs, ok := s.grpcClients[chain.Config().ChainID]
s.Require().True(ok, "chain %s does not have GRPC clients", chain.Config().ChainID)
return cs
}
// initGRPCClients establishes GRPC clients with the given chain.
// The created GRPCClients can be retrieved with GetChainGRCPClients.
func (s *E2ETestSuite) initGRPCClients(chain *cosmos.CosmosChain) {
// Create a connection to the gRPC server.
grpcConn, err := grpc.Dial(
chain.GetHostGRPCAddress(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
s.Require().NoError(err)
s.T().Cleanup(func() {
if err := grpcConn.Close(); err != nil {
s.T().Logf("failed closing GRPC connection to chain %s: %s", chain.Config().ChainID, err)
}
})
if s.grpcClients == nil {
s.grpcClients = make(map[string]GRPCClients)
}
s.grpcClients[chain.Config().ChainID] = GRPCClients{
FeeQueryClient: feetypes.NewQueryClient(grpcConn),
}
}
// AssertValidTxResponse verifies that an sdk.TxResponse
// has non-empty values.
func (s *E2ETestSuite) AssertValidTxResponse(resp sdk.TxResponse) {
respLogsMsg := resp.Logs.String()
s.Require().NotEqual(int64(0), resp.GasUsed, respLogsMsg)
s.Require().NotEqual(int64(0), resp.GasWanted, respLogsMsg)
s.Require().NotEmpty(resp.Events, respLogsMsg)
s.Require().NotEmpty(resp.Data, respLogsMsg)
}
// createCosmosChains creates two separate chains in docker containers.
// test and can be retrieved with GetChains.
func (s *E2ETestSuite) createCosmosChains(chainOptions testconfig.ChainOptions) (*cosmos.CosmosChain, *cosmos.CosmosChain) {
ctx := context.Background()
client, network := ibctest.DockerSetup(s.T())
s.logger = zap.NewExample()
s.DockerClient = client
s.network = network
logger := zaptest.NewLogger(s.T())
// TODO(chatton): allow for controller over number of validators and full nodes.
chainA := cosmos.NewCosmosChain(s.T().Name(), *chainOptions.ChainAConfig, 1, 0, logger)
chainB := cosmos.NewCosmosChain(s.T().Name(), *chainOptions.ChainBConfig, 1, 0, logger)
s.T().Cleanup(func() {
if !s.T().Failed() {
for _, c := range []*cosmos.CosmosChain{chainA, chainB} {
if err := c.Cleanup(ctx); err != nil {
s.T().Logf("Chain cleanup for %s failed: %v", c.Config().ChainID, err)
}
}
}
})
return chainA, chainB
}
// getRelayerExecReporter returns a testreporter.RelayerExecReporter instances
// using the current test's testing.T.
func (s *E2ETestSuite) getRelayerExecReporter() *testreporter.RelayerExecReporter {
rep := testreporter.NewNopReporter()
return rep.RelayerExecReporter(s.T())
}
// GetNativeChainBalance returns the balance of a specific user on a chain using the native denom.
func GetNativeChainBalance(ctx context.Context, chain ibc.Chain, user *ibctest.User) (int64, error) {
bal, err := chain.GetBalance(ctx, user.Bech32Address(chain.Config().Bech32Prefix), chain.Config().Denom)
if err != nil {
return -1, err
}
return bal, nil
}