From 8c806a06fce7838527b549399dfd4775c9b0a933 Mon Sep 17 00:00:00 2001 From: Callum Waters Date: Thu, 22 Feb 2024 13:48:44 +0100 Subject: [PATCH] chore: switch from cosmos-sdk/network to testnode package (#3118) Closes: https://github.com/celestiaorg/celestia-app/issues/829 This refactors the three tests we have that use the CLI commands: `mint`, `blob` and `blobstream` to use the `testnode` package instead of `cosmos-sdk`'s `network` package. The motivating reason for this is that cosmos-sdk's network package doesn't support initialising the `ConsensusParams` in the genesis file which we need to set the app version correctly --------- Co-authored-by: Rootul P --- test/testground/network/consensus_node.go | 2 +- test/util/genesis/accounts.go | 8 +- test/util/genesis/document.go | 2 +- test/util/network/network.go | 154 --------------------- test/util/testnode/config.go | 5 +- test/util/testnode/network.go | 22 ++- test/util/testnode/node_interaction_api.go | 21 ++- test/util/testnode/rpc_client.go | 35 ++++- test/util/testnode/utils.go | 2 +- x/blob/client/testutil/integration_test.go | 45 +++--- x/blobstream/client/query_test.go | 8 +- x/blobstream/client/suite_test.go | 32 ++--- x/mint/client/testutil/grpc_test.go | 23 +-- x/mint/client/testutil/suite_test.go | 54 +++----- x/upgrade/legacy_test.go | 4 - 15 files changed, 139 insertions(+), 278 deletions(-) delete mode 100644 test/util/network/network.go diff --git a/test/testground/network/consensus_node.go b/test/testground/network/consensus_node.go index 662fb604c5..b8c1b5a1fa 100644 --- a/test/testground/network/consensus_node.go +++ b/test/testground/network/consensus_node.go @@ -202,7 +202,7 @@ func (cn *ConsensusNode) StartNode(ctx context.Context, baseDir string) error { } cn.cmtNode = tmNode - cctx := testnode.NewContext(ctx, cn.kr, ucfg.TmConfig, cn.params.ChainID) + cctx := testnode.NewContext(ctx, cn.kr, ucfg.TmConfig, cn.params.ChainID, ucfg.AppConfig.API.Address) cctx, stopNode, err := testnode.StartNode(tmNode, cctx) cn.stopFuncs = append(cn.stopFuncs, stopNode) diff --git a/test/util/genesis/accounts.go b/test/util/genesis/accounts.go index bb485c9098..a702524a3c 100644 --- a/test/util/genesis/accounts.go +++ b/test/util/genesis/accounts.go @@ -15,6 +15,10 @@ import ( "github.com/tendermint/tendermint/crypto" ) +const ( + DefaultInitialBalance = 1e15 // 1 billion TIA +) + type Account struct { Name string InitialTokens int64 @@ -55,9 +59,9 @@ func NewDefaultValidator(name string) Validator { return Validator{ Account: Account{ Name: name, - InitialTokens: 999_999_999_999_999_999, + InitialTokens: DefaultInitialBalance, }, - Stake: 99_999_999_999_999_999, // save some tokens for fees + Stake: DefaultInitialBalance / 2, // save some tokens for fees ConsensusKey: GenerateEd25519(NewSeed(r)), NetworkKey: GenerateEd25519(NewSeed(r)), } diff --git a/test/util/genesis/document.go b/test/util/genesis/document.go index a60fa01d5b..56220795a2 100644 --- a/test/util/genesis/document.go +++ b/test/util/genesis/document.go @@ -99,7 +99,7 @@ func accountsToSDKTypes(addrs []string, pubkeys []cryptotypes.PubKey) ([]banktyp pubKey := pubkeys[i] balances := sdk.NewCoins( - sdk.NewCoin(appconsts.BondDenom, sdk.NewInt(999_999_999_999_999_999)), + sdk.NewCoin(appconsts.BondDenom, sdk.NewInt(DefaultInitialBalance)), ) genBals[i] = banktypes.Balance{Address: addr, Coins: balances.Sort()} diff --git a/test/util/network/network.go b/test/util/network/network.go deleted file mode 100644 index 8149c55141..0000000000 --- a/test/util/network/network.go +++ /dev/null @@ -1,154 +0,0 @@ -package network - -import ( - "fmt" - "strings" - "testing" - "time" - - "github.com/celestiaorg/celestia-app/app" - "github.com/celestiaorg/celestia-app/app/encoding" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - pruningtypes "github.com/cosmos/cosmos-sdk/pruning/types" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/testutil/network" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - tmrand "github.com/tendermint/tendermint/libs/rand" - tmdb "github.com/tendermint/tm-db" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" -) - -func New(t *testing.T, config network.Config, genAccNames ...string) *network.Network { - kr := keyring.NewInMemory(config.Codec) - - // add genesis accounts - genAuthAccs := make([]authtypes.GenesisAccount, len(genAccNames)) - genBalances := make([]banktypes.Balance, len(genAccNames)) - for i, name := range genAccNames { - a, b := newGenAccout(kr, name, 1000000000000) - genAuthAccs[i] = a - genBalances[i] = b - } - - config, err := addGenAccounts(config, genAuthAccs, genBalances) - if err != nil { - panic(err) - } - - tmpDir := t.TempDir() - - net, err := network.New(t, tmpDir, config) - if err != nil { - panic(err) - } - - net.Validators[0].ClientCtx.Keyring = kr - - return net -} - -// GRPCConn creates and connects a grpc client to the first validator in the -// network. The resulting grpc client connection is stored in the client context -func GRPCConn(net *network.Network) error { - nodeGRPCAddr := strings.Replace(net.Validators[0].AppConfig.GRPC.Address, "0.0.0.0", "localhost", 1) - conn, err := grpc.Dial(nodeGRPCAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) - net.Validators[0].ClientCtx.GRPCClient = conn - return err -} - -// DefaultConfig will initialize config for the network with custom application, -// genesis and single validator. All other parameters are inherited from -// cosmos-sdk/testutil/network.DefaultConfig -func DefaultConfig() network.Config { - encCfg := encoding.MakeConfig(app.ModuleEncodingRegisters...) - - return network.Config{ - Codec: encCfg.Codec, - TxConfig: encCfg.TxConfig, - LegacyAmino: encCfg.Amino, - InterfaceRegistry: encCfg.InterfaceRegistry, - AccountRetriever: authtypes.AccountRetriever{}, - AppConstructor: func(val network.Validator) servertypes.Application { - return app.New( - val.Ctx.Logger, tmdb.NewMemDB(), nil, true, 0, - encCfg, 0, - simapp.EmptyAppOptions{}, - baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.AppConfig.Pruning)), - baseapp.SetMinGasPrices(val.AppConfig.MinGasPrices), - ) - }, - GenesisState: app.ModuleBasics.DefaultGenesis(encCfg.Codec), - TimeoutCommit: 2 * time.Second, - ChainID: "chain-" + tmrand.Str(6), - NumValidators: 1, - BondDenom: app.BondDenom, - MinGasPrices: fmt.Sprintf("0.000006%s", app.BondDenom), - AccountTokens: sdk.TokensFromConsensusPower(1000, sdk.DefaultPowerReduction), - StakingTokens: sdk.TokensFromConsensusPower(500, sdk.DefaultPowerReduction), - BondedTokens: sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction), - PruningStrategy: pruningtypes.PruningOptionNothing, - CleanupDir: true, - SigningAlgo: string(hd.Secp256k1Type), - KeyringOptions: []keyring.Option{}, - PrintMnemonic: false, - } -} - -func addGenAccounts(cfg network.Config, genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance) (network.Config, error) { - // set the accounts in the genesis state - var authGenState authtypes.GenesisState - cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[authtypes.ModuleName], &authGenState) - - accounts, err := authtypes.PackAccounts(genAccounts) - if err != nil { - return cfg, err - } - - authGenState.Accounts = append(authGenState.Accounts, accounts...) - cfg.GenesisState[authtypes.ModuleName] = cfg.Codec.MustMarshalJSON(&authGenState) - - // set the balances in the genesis state - var bankGenState banktypes.GenesisState - cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[banktypes.ModuleName], &bankGenState) - - bankGenState.Balances = append(bankGenState.Balances, genBalances...) - cfg.GenesisState[banktypes.ModuleName] = cfg.Codec.MustMarshalJSON(&bankGenState) - - return cfg, nil -} - -func newGenAccout(kr keyring.Keyring, name string, amount int64) (authtypes.GenesisAccount, banktypes.Balance) { - info, _, err := kr.NewMnemonic(name, keyring.English, "", "", hd.Secp256k1) - if err != nil { - panic(err) - } - - // create coin - balances := sdk.NewCoins( - sdk.NewCoin(fmt.Sprintf("%stoken", app.BondDenom), sdk.NewInt(amount)), - sdk.NewCoin(app.BondDenom, sdk.NewInt(amount)), - ) - - addr, err := info.GetAddress() - if err != nil { - panic(err) - } - - bal := banktypes.Balance{ - Address: addr.String(), - Coins: balances.Sort(), - } - - pub, err := info.GetPubKey() - if err != nil { - panic(err) - } - - return authtypes.NewBaseAccount(addr, pub, 0, 0), bal -} diff --git a/test/util/testnode/config.go b/test/util/testnode/config.go index 38461d490d..1aaff08ded 100644 --- a/test/util/testnode/config.go +++ b/test/util/testnode/config.go @@ -17,6 +17,7 @@ const ( kibibyte = 1024 // bytes mebibyte = 1_048_576 // bytes DefaultValidatorAccountName = "validator" + DefaultInitialBalance = genesis.DefaultInitialBalance ) type UniversalTestingConfig struct { @@ -83,7 +84,7 @@ func (c *Config) WithTimeoutCommit(d time.Duration) *Config { // WithFundedAccounts sets the genesis accounts and returns the Config. func (c *Config) WithFundedAccounts(accounts ...string) *Config { c.Genesis = c.Genesis.WithAccounts( - genesis.NewAccounts(999999999999999999, accounts...)..., + genesis.NewAccounts(DefaultInitialBalance, accounts...)..., ) return c } @@ -153,5 +154,7 @@ func DefaultTendermintConfig() *tmconfig.Config { // chosen only as an arbitrary large number). tmCfg.RPC.MaxBodyBytes = 200 * mebibyte + tmCfg.RPC.TimeoutBroadcastTxCommit = time.Minute + return tmCfg } diff --git a/test/util/testnode/network.go b/test/util/testnode/network.go index 22a2e9400f..7452c19801 100644 --- a/test/util/testnode/network.go +++ b/test/util/testnode/network.go @@ -32,18 +32,26 @@ func NewNetwork(t testing.TB, cfg *Config) (cctx Context, rpcAddr, grpcAddr stri tmNode, app, err := NewCometNode(baseDir, &cfg.UniversalTestingConfig) require.NoError(t, err) - cctx = NewContext(context.Background(), cfg.Genesis.Keyring(), tmCfg, cfg.Genesis.ChainID) - - cctx, stopNode, err := StartNode(tmNode, cctx) - require.NoError(t, err) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(func() { + cancel() + }) appCfg := cfg.AppConfig appCfg.GRPC.Address = fmt.Sprintf("127.0.0.1:%d", mustGetFreePort()) appCfg.API.Address = fmt.Sprintf("tcp://127.0.0.1:%d", mustGetFreePort()) + cctx = NewContext(ctx, cfg.Genesis.Keyring(), tmCfg, cfg.Genesis.ChainID, appCfg.API.Address) + + cctx, stopNode, err := StartNode(tmNode, cctx) + require.NoError(t, err) + cctx, cleanupGRPC, err := StartGRPCServer(app, appCfg, cctx) require.NoError(t, err) + apiServer, err := StartAPIServer(app, *appCfg, cctx) + require.NoError(t, err) + t.Cleanup(func() { t.Log("tearing down testnode") err := stopNode() @@ -58,6 +66,12 @@ func NewNetwork(t testing.TB, cfg *Config) (cctx Context, rpcAddr, grpcAddr stri // failing the test. t.Logf("error when cleaning up GRPC %v", err) } + err = apiServer.Close() + if err != nil { + // the test has already completed so just log the error instead of + // failing the test. + t.Logf("error when closing API server %v", err) + } }) return cctx, tmCfg.RPC.ListenAddress, appCfg.GRPC.Address diff --git a/test/util/testnode/node_interaction_api.go b/test/util/testnode/node_interaction_api.go index b6f3fb5fee..17e2e32df3 100644 --- a/test/util/testnode/node_interaction_api.go +++ b/test/util/testnode/node_interaction_api.go @@ -34,9 +34,10 @@ const ( type Context struct { rootCtx context.Context client.Context + apiAddress string } -func NewContext(goCtx context.Context, kr keyring.Keyring, tmCfg *tmconfig.Config, chainID string) Context { +func NewContext(goCtx context.Context, kr keyring.Keyring, tmCfg *tmconfig.Config, chainID, apiAddress string) Context { ecfg := encoding.MakeConfig(app.ModuleEncodingRegisters...) cctx := client.Context{}. WithKeyring(kr). @@ -48,7 +49,7 @@ func NewContext(goCtx context.Context, kr keyring.Keyring, tmCfg *tmconfig.Confi WithTxConfig(ecfg.TxConfig). WithAccountRetriever(authtypes.AccountRetriever{}) - return Context{rootCtx: goCtx, Context: cctx} + return Context{rootCtx: goCtx, Context: cctx, apiAddress: apiAddress} } func (c *Context) GoContext() context.Context { @@ -96,13 +97,19 @@ func (c *Context) WaitForHeightWithTimeout(h int64, t time.Duration) (int64, err ctx, cancel := context.WithTimeout(c.rootCtx, t) defer cancel() - var latestHeight int64 + var ( + latestHeight int64 + err error + ) for { select { case <-ctx.Done(): - return latestHeight, fmt.Errorf("timeout (%v) exceeded waiting for network to reach height", t) + if c.rootCtx.Err() != nil { + return latestHeight, c.rootCtx.Err() + } + return latestHeight, fmt.Errorf("timeout (%v) exceeded waiting for network to reach height %d. Got to height %d", t, h, latestHeight) case <-ticker.C: - latestHeight, err := c.LatestHeight() + latestHeight, err = c.LatestHeight() if err != nil { return 0, err } @@ -313,3 +320,7 @@ func (c *Context) HeightForTimestamp(timestamp time.Time) (int64, error) { } return 0, fmt.Errorf("could not find block with timestamp after %v", timestamp) } + +func (c *Context) APIAddress() string { + return c.apiAddress +} diff --git a/test/util/testnode/rpc_client.go b/test/util/testnode/rpc_client.go index ac7266e052..7c51163f77 100644 --- a/test/util/testnode/rpc_client.go +++ b/test/util/testnode/rpc_client.go @@ -4,10 +4,14 @@ import ( "os" "path" "strings" + "time" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/server/api" srvconfig "github.com/cosmos/cosmos-sdk/server/config" srvgrpc "github.com/cosmos/cosmos-sdk/server/grpc" srvtypes "github.com/cosmos/cosmos-sdk/server/types" + "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/rpc/client/local" "google.golang.org/grpc" @@ -56,13 +60,23 @@ func StartGRPCServer(app srvtypes.Application, appCfg *srvconfig.Config, cctx Co // Add the tendermint queries service in the gRPC router. app.RegisterTendermintService(cctx.Context) + if a, ok := app.(srvtypes.ApplicationQueryService); ok { + a.RegisterNodeService(cctx.Context) + } + grpcSrv, err := srvgrpc.StartGRPCServer(cctx.Context, app, appCfg.GRPC) if err != nil { return Context{}, emptycleanup, err } nodeGRPCAddr := strings.Replace(appCfg.GRPC.Address, "0.0.0.0", "localhost", 1) - conn, err := grpc.Dial(nodeGRPCAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.Dial( + nodeGRPCAddr, + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithDefaultCallOptions( + grpc.ForceCodec(codec.NewProtoCodec(cctx.InterfaceRegistry).GRPCCodec()), + ), + ) if err != nil { return Context{}, emptycleanup, err } @@ -99,3 +113,22 @@ func removeDir(rootDir string) error { } return os.RemoveAll(rootDir) } + +func StartAPIServer(app srvtypes.Application, appCfg srvconfig.Config, cctx Context) (*api.Server, error) { + apiSrv := api.New(cctx.Context, log.NewNopLogger()) + app.RegisterAPIRoutes(apiSrv, appCfg.API) + errCh := make(chan error) + go func() { + if err := apiSrv.Start(appCfg); err != nil { + errCh <- err + } + }() + + select { + case err := <-errCh: + return nil, err + + case <-time.After(srvtypes.ServerStartTime): // assume server started successfully + } + return apiSrv, nil +} diff --git a/test/util/testnode/utils.go b/test/util/testnode/utils.go index 45ef967d39..affde57b98 100644 --- a/test/util/testnode/utils.go +++ b/test/util/testnode/utils.go @@ -72,7 +72,7 @@ func FundKeyringAccounts(accounts ...string) (keyring.Keyring, []banktypes.Balan for i, addr := range addresses { balances := sdk.NewCoins( - sdk.NewCoin(appconsts.BondDenom, sdk.NewInt(99999999999999999)), + sdk.NewCoin(appconsts.BondDenom, sdk.NewInt(DefaultInitialBalance)), ) genBalances[i] = banktypes.Balance{Address: addr.String(), Coins: balances.Sort()} diff --git a/x/blob/client/testutil/integration_test.go b/x/blob/client/testutil/integration_test.go index db95ad396f..b9a7a0195b 100644 --- a/x/blob/client/testutil/integration_test.go +++ b/x/blob/client/testutil/integration_test.go @@ -8,18 +8,16 @@ import ( "testing" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - cosmosnet "github.com/cosmos/cosmos-sdk/testutil/network" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/celestiaorg/celestia-app/pkg/appconsts" "github.com/celestiaorg/celestia-app/x/blob/types" - "github.com/celestiaorg/celestia-app/test/util/network" "github.com/celestiaorg/celestia-app/test/util/testnode" paycli "github.com/celestiaorg/celestia-app/x/blob/client/cli" appns "github.com/celestiaorg/go-square/namespace" @@ -32,9 +30,8 @@ const username = "test" type IntegrationTestSuite struct { suite.Suite - cfg cosmosnet.Config - network *cosmosnet.Network - kr keyring.Keyring + cfg *testnode.Config + ctx testnode.Context } // Create a .json file for testing @@ -60,28 +57,22 @@ func createTestFile(t testing.TB, s string, isValid bool) *os.File { return fp } -func NewIntegrationTestSuite(cfg cosmosnet.Config) *IntegrationTestSuite { +func NewIntegrationTestSuite(cfg *testnode.Config) *IntegrationTestSuite { return &IntegrationTestSuite{cfg: cfg} } func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") + s.cfg.WithFundedAccounts(username) - net := network.New(s.T(), s.cfg, username) - s.network = net - s.kr = net.Validators[0].ClientCtx.Keyring - _, err := s.network.WaitForHeight(1) - s.Require().NoError(err) -} + s.ctx, _, _ = testnode.NewNetwork(s.T(), s.cfg) -func (s *IntegrationTestSuite) TearDownSuite() { - s.T().Log("tearing down integration test suite") - s.network.Cleanup() + _, err := s.ctx.WaitForHeight(1) + s.Require().NoError(err) } func (s *IntegrationTestSuite) TestSubmitPayForBlob() { require := s.Require() - validator := s.network.Validators[0] hexBlob := "0204033704032c0b162109000908094d425837422c2116" @@ -116,7 +107,7 @@ func (s *IntegrationTestSuite) TestSubmitPayForBlob() { hexBlob, fmt.Sprintf("--from=%s", username), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(2))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(appconsts.BondDenom, sdk.NewInt(1000))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), }, expectErr: false, @@ -128,7 +119,7 @@ func (s *IntegrationTestSuite) TestSubmitPayForBlob() { args: []string{ fmt.Sprintf("--from=%s", username), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(2))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(appconsts.BondDenom, sdk.NewInt(1000))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", paycli.FlagFileInput, validPropFile.Name()), }, @@ -141,7 +132,7 @@ func (s *IntegrationTestSuite) TestSubmitPayForBlob() { args: []string{ fmt.Sprintf("--from=%s", username), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(2))).String()), + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(appconsts.BondDenom, sdk.NewInt(1000))).String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", paycli.FlagFileInput, invalidPropFile.Name()), }, @@ -153,19 +144,17 @@ func (s *IntegrationTestSuite) TestSubmitPayForBlob() { for _, tc := range testCases { tc := tc - require.NoError(s.network.WaitForNextBlock()) + require.NoError(s.ctx.WaitForNextBlock()) s.Run(tc.name, func() { cmd := paycli.CmdPayForBlob() - clientCtx := validator.ClientCtx - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) + out, err := clitestutil.ExecTestCLICmd(s.ctx.Context, cmd, tc.args) if tc.expectErr { require.Error(err) return } require.NoError(err, "test: %s\noutput: %s", tc.name, out.String()) - err = clientCtx.Codec.UnmarshalJSON(out.Bytes(), tc.respType) + err = s.ctx.Codec.UnmarshalJSON(out.Bytes(), tc.respType) require.NoError(err, out.String(), "test: %s, output\n:", tc.name, out.String()) txResp := tc.respType.(*sdk.TxResponse) @@ -187,10 +176,10 @@ func (s *IntegrationTestSuite) TestSubmitPayForBlob() { } // wait for the tx to be indexed - s.Require().NoError(s.network.WaitForNextBlock()) + s.Require().NoError(s.ctx.WaitForNextBlock()) // attempt to query for the transaction using the tx's hash - res, err := testnode.QueryWithoutProof(clientCtx, txResp.TxHash) + res, err := testnode.QueryWithoutProof(s.ctx.Context, txResp.TxHash) require.NoError(err) require.Equal(abci.CodeTypeOK, res.TxResult.Code) }) @@ -201,5 +190,5 @@ func TestIntegrationTestSuite(t *testing.T) { if testing.Short() { t.Skip("skipping integration test in short mode.") } - suite.Run(t, NewIntegrationTestSuite(network.DefaultConfig())) + suite.Run(t, NewIntegrationTestSuite(testnode.DefaultConfig())) } diff --git a/x/blobstream/client/query_test.go b/x/blobstream/client/query_test.go index 8f9d87a7b8..0d00d6a9ce 100644 --- a/x/blobstream/client/query_test.go +++ b/x/blobstream/client/query_test.go @@ -2,15 +2,15 @@ package client_test import ( "testing" + "time" "github.com/celestiaorg/celestia-app/x/blobstream/client" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" ) func (s *CLITestSuite) TestQueryAttestationByNonce() { - _, err := s.network.WaitForHeight(402) + _, err := s.cctx.WaitForHeightWithTimeout(402, 2*time.Minute) s.Require().NoError(err) - val := s.network.Validators[0] testCases := []struct { name string nonce string @@ -46,9 +46,7 @@ func (s *CLITestSuite) TestQueryAttestationByNonce() { for _, tc := range testCases { s.T().Run(tc.name, func(t *testing.T) { cmd := client.CmdQueryAttestationByNonce() - clientCtx := val.ClientCtx - - _, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, []string{tc.nonce}) + _, err := clitestutil.ExecTestCLICmd(s.cctx.Context, cmd, []string{tc.nonce}) if tc.expectErr { s.Assert().Error(err) } else { diff --git a/x/blobstream/client/suite_test.go b/x/blobstream/client/suite_test.go index 327a2ce440..7fffabfcc5 100644 --- a/x/blobstream/client/suite_test.go +++ b/x/blobstream/client/suite_test.go @@ -2,52 +2,38 @@ package client_test import ( "testing" - "time" - "github.com/celestiaorg/celestia-app/test/util/network" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - cosmosnet "github.com/cosmos/cosmos-sdk/testutil/network" + "github.com/celestiaorg/celestia-app/test/util/testnode" "github.com/stretchr/testify/suite" tmrand "github.com/tendermint/tendermint/libs/rand" ) type CLITestSuite struct { suite.Suite - cfg cosmosnet.Config - network *cosmosnet.Network - kr keyring.Keyring + cfg *testnode.Config + cctx testnode.Context } func (s *CLITestSuite) SetupSuite() { if testing.Short() { s.T().Skip("skipping Blobstream CLI tests in short mode.") } - s.T().Log("setting up Blobstream CLI test suite") - cfg := network.DefaultConfig() - cfg.EnableTMLogging = false - cfg.MinGasPrices = "0utia" - cfg.NumValidators = 1 - cfg.TimeoutCommit = time.Millisecond - s.cfg = cfg + cfg := testnode.DefaultConfig() numAccounts := 120 accounts := make([]string, numAccounts) for i := 0; i < numAccounts; i++ { accounts[i] = tmrand.Str(20) } + cfg.WithFundedAccounts(accounts...) - net := network.New(s.T(), cfg, accounts...) + s.cfg = cfg + s.cctx, _, _ = testnode.NewNetwork(s.T(), cfg) - s.network = net - s.kr = net.Validators[0].ClientCtx.Keyring - _, err := s.network.WaitForHeight(2) + height, err := s.cctx.WaitForHeight(2) s.Require().NoError(err) -} - -func (s *CLITestSuite) TearDownSuite() { - s.T().Log("tearing down Blobstream CLI test suite") - s.network.Cleanup() + s.T().Log("waited for height", height) } func TestBlobstreamCLI(t *testing.T) { diff --git a/x/mint/client/testutil/grpc_test.go b/x/mint/client/testutil/grpc_test.go index a2959c2f3a..343b72fa86 100644 --- a/x/mint/client/testutil/grpc_test.go +++ b/x/mint/client/testutil/grpc_test.go @@ -2,6 +2,7 @@ package testutil import ( "fmt" + "strings" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" @@ -9,12 +10,14 @@ import ( "github.com/gogo/protobuf/proto" - minttypes "github.com/celestiaorg/celestia-app/x/mint/types" + "github.com/celestiaorg/celestia-app/test/util/testnode" + mint "github.com/celestiaorg/celestia-app/x/mint/types" ) func (s *IntegrationTestSuite) TestQueryGRPC() { - val := s.network.Validators[0] - baseURL := val.APIAddress + baseURL := s.cctx.APIAddress() + baseURL = strings.Replace(baseURL, "tcp", "http", 1) + expectedAnnualProvision := mint.InitialInflationRateAsDec().MulInt(sdk.NewInt(testnode.DefaultInitialBalance)) testCases := []struct { name string url string @@ -26,8 +29,8 @@ func (s *IntegrationTestSuite) TestQueryGRPC() { "gRPC request inflation rate", fmt.Sprintf("%s/cosmos/mint/v1beta1/inflation_rate", baseURL), map[string]string{}, - &minttypes.QueryInflationRateResponse{}, - &minttypes.QueryInflationRateResponse{ + &mint.QueryInflationRateResponse{}, + &mint.QueryInflationRateResponse{ InflationRate: sdk.NewDecWithPrec(8, 2), }, }, @@ -37,17 +40,17 @@ func (s *IntegrationTestSuite) TestQueryGRPC() { map[string]string{ grpctypes.GRPCBlockHeightHeader: "1", }, - &minttypes.QueryAnnualProvisionsResponse{}, - &minttypes.QueryAnnualProvisionsResponse{ - AnnualProvisions: sdk.NewDec(40_000_000), + &mint.QueryAnnualProvisionsResponse{}, + &mint.QueryAnnualProvisionsResponse{ + AnnualProvisions: expectedAnnualProvision, }, }, } for _, tc := range testCases { - resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { + resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) - s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(resp, tc.respType)) + s.Require().NoError(s.cctx.Context.Codec.UnmarshalJSON(resp, tc.respType)) s.Require().Equal(tc.expected.String(), tc.respType.String()) }) } diff --git a/x/mint/client/testutil/suite_test.go b/x/mint/client/testutil/suite_test.go index 358af056c5..54ffb83066 100644 --- a/x/mint/client/testutil/suite_test.go +++ b/x/mint/client/testutil/suite_test.go @@ -10,43 +10,32 @@ import ( tmcli "github.com/tendermint/tendermint/libs/cli" "github.com/celestiaorg/celestia-app/x/mint/client/cli" - minttypes "github.com/celestiaorg/celestia-app/x/mint/types" + mint "github.com/celestiaorg/celestia-app/x/mint/types" "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" + sdk "github.com/cosmos/cosmos-sdk/types" - appnetwork "github.com/celestiaorg/celestia-app/test/util/network" - "github.com/cosmos/cosmos-sdk/testutil/network" + "github.com/celestiaorg/celestia-app/test/util/testnode" ) type IntegrationTestSuite struct { suite.Suite - cfg network.Config - network *network.Network + cfg *testnode.Config + cctx testnode.Context } -func NewIntegrationTestSuite(cfg network.Config) *IntegrationTestSuite { +func NewIntegrationTestSuite(cfg *testnode.Config) *IntegrationTestSuite { return &IntegrationTestSuite{cfg: cfg} } func (s *IntegrationTestSuite) SetupSuite() { s.T().Log("setting up x/mint integration test suite") - genesisState := s.cfg.GenesisState - var mintData minttypes.GenesisState - s.Require().NoError(s.cfg.Codec.UnmarshalJSON(genesisState[minttypes.ModuleName], &mintData)) + s.cctx, _, _ = testnode.NewNetwork(s.T(), s.cfg) - var err error - s.network, err = network.New(s.T(), s.T().TempDir(), s.cfg) + _, err := s.cctx.WaitForHeight(1) s.Require().NoError(err) - - _, err = s.network.WaitForHeight(1) - s.Require().NoError(err) -} - -func (s *IntegrationTestSuite) TearDownSuite() { - s.T().Log("tearing down x/mint integration test suite") - s.network.Cleanup() } func (s *IntegrationTestSuite) jsonArgs() []string { @@ -54,15 +43,13 @@ func (s *IntegrationTestSuite) jsonArgs() []string { } func (s *IntegrationTestSuite) textArgs() []string { - return []string{fmt.Sprintf("--%s=1", flags.FlagHeight), fmt.Sprintf("--%s=json", tmcli.OutputFlag)} + return []string{fmt.Sprintf("--%s=1", flags.FlagHeight), fmt.Sprintf("--%s=text", tmcli.OutputFlag)} } // TestGetCmdQueryInflationRate tests that the CLI query command for inflation // rate returns the correct value. This test assumes that the initial inflation // rate is 0.08. func (s *IntegrationTestSuite) TestGetCmdQueryInflationRate() { - val := s.network.Validators[0] - testCases := []struct { name string args []string @@ -85,9 +72,8 @@ func (s *IntegrationTestSuite) TestGetCmdQueryInflationRate() { s.Run(tc.name, func() { cmd := cli.GetCmdQueryInflationRate() - clientCtx := val.ClientCtx - got, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) + got, err := clitestutil.ExecTestCLICmd(s.cctx.Context, cmd, tc.args) s.Require().NoError(err) s.Require().Equal(tc.want, strings.TrimSpace(got.String())) }) @@ -100,8 +86,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryInflationRate() { // // TODO assert that total supply is 500_000_000 utia. func (s *IntegrationTestSuite) TestGetCmdQueryAnnualProvisions() { - val := s.network.Validators[0] - testCases := []struct { name string args []string @@ -110,25 +94,23 @@ func (s *IntegrationTestSuite) TestGetCmdQueryAnnualProvisions() { { name: "json output", args: s.jsonArgs(), - want: `40000000.000000000000000000`, }, { name: "text output", args: s.textArgs(), - want: `40000000.000000000000000000`, }, } + expectedAnnualProvision := mint.InitialInflationRateAsDec().MulInt(sdk.NewInt(testnode.DefaultInitialBalance)) for _, tc := range testCases { tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryAnnualProvisions() - clientCtx := val.ClientCtx - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) + out, err := clitestutil.ExecTestCLICmd(s.cctx.Context, cmd, tc.args) s.Require().NoError(err) - s.Require().Equal(tc.want, strings.TrimSpace(out.String())) + + s.Require().Equal(expectedAnnualProvision.String(), strings.TrimSpace(out.String())) }) } } @@ -137,8 +119,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryAnnualProvisions() { // returns the same time that is set in the genesis state. The CLI command to // query genesis time looks like: `celestia-appd query mint genesis-time` func (s *IntegrationTestSuite) TestGetCmdQueryGenesisTime() { - val := s.network.Validators[0] - testCases := []struct { name string args []string @@ -158,9 +138,7 @@ func (s *IntegrationTestSuite) TestGetCmdQueryGenesisTime() { s.Run(tc.name, func() { cmd := cli.GetCmdQueryGenesisTime() - clientCtx := val.ClientCtx - - out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) + out, err := clitestutil.ExecTestCLICmd(s.cctx.Context, cmd, tc.args) s.Require().NoError(err) trimmed := strings.TrimSpace(out.String()) @@ -185,6 +163,6 @@ func TestMintIntegrationTestSuite(t *testing.T) { if testing.Short() { t.Skip("skipping TestMintIntegrationTestSuite in short mode.") } - cfg := appnetwork.DefaultConfig() + cfg := testnode.DefaultConfig() suite.Run(t, NewIntegrationTestSuite(cfg)) } diff --git a/x/upgrade/legacy_test.go b/x/upgrade/legacy_test.go index dc17b4e890..4aa8796c0a 100644 --- a/x/upgrade/legacy_test.go +++ b/x/upgrade/legacy_test.go @@ -69,12 +69,8 @@ func (s *LegacyUpgradeTestSuite) SetupSuite() { accounts[i] = tmrand.Str(9) } - tmCfg := testnode.DefaultTendermintConfig() - tmCfg.Consensus.TimeoutCommit = 3 * time.Second - cfg := testnode.DefaultConfig(). WithFundedAccounts(accounts...). - WithTendermintConfig(tmCfg). WithModifiers(genesis.ImmediateProposals(s.ecfg.Codec)) cctx, _, _ := testnode.NewNetwork(t, cfg)