From caeef08b727fddec1fb09f32c4b8fa298e622261 Mon Sep 17 00:00:00 2001 From: skosito Date: Sat, 20 Apr 2024 04:05:36 +0200 Subject: [PATCH] Fix cli test suites --- app/app.go | 3 + testutil/network/network_config.go | 70 -------- testutil/network/network_setup.go | 195 ++++++++++++++++----- testutil/network/util.go | 65 +++++-- x/crosschain/client/querytests/cli_test.go | 63 +++---- x/crosschain/client/querytests/suite.go | 1 + x/observer/client/querytests/cli_test.go | 63 +++---- 7 files changed, 244 insertions(+), 216 deletions(-) delete mode 100644 testutil/network/network_config.go diff --git a/app/app.go b/app/app.go index 7eb29180d9..301b9fb348 100644 --- a/app/app.go +++ b/app/app.go @@ -115,6 +115,7 @@ import ( fungiblekeeper "github.com/zeta-chain/zetacore/x/fungible/keeper" fungibletypes "github.com/zeta-chain/zetacore/x/fungible/types" + nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" observermodule "github.com/zeta-chain/zetacore/x/observer" @@ -776,6 +777,8 @@ func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // Register new tendermint queries routes from grpc-gateway. tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + // Register node gRPC service for grpc-gateway. + nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // Register legacy and grpc-gateway routes for all modules. ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) diff --git a/testutil/network/network_config.go b/testutil/network/network_config.go deleted file mode 100644 index 8755912098..0000000000 --- a/testutil/network/network_config.go +++ /dev/null @@ -1,70 +0,0 @@ -package network - -import ( - "fmt" - "time" - - "github.com/zeta-chain/zetacore/cmd/zetacored/config" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - tmdb "github.com/cometbft/cometbft-db" - - "github.com/zeta-chain/zetacore/app" -) - -// 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() Config { - encoding := app.MakeEncodingConfig() - - return Config{ - Codec: encoding.Codec, - TxConfig: encoding.TxConfig, - LegacyAmino: encoding.Amino, - InterfaceRegistry: encoding.InterfaceRegistry, - AccountRetriever: authtypes.AccountRetriever{}, - AppConstructor: func(val Validator) servertypes.Application { - return app.New( - val.Ctx.Logger, tmdb.NewMemDB(), nil, true, map[int64]bool{}, val.Ctx.Config.RootDir, 0, - encoding, - simtestutil.EmptyAppOptions{}, - baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.AppConfig.Pruning)), - baseapp.SetMinGasPrices(val.AppConfig.MinGasPrices), - baseapp.SetChainID("athens_8888-2"), - ) - }, - GenesisState: app.ModuleBasics.DefaultGenesis(encoding.Codec), - TimeoutCommit: 2 * time.Second, - ChainID: "athens_8888-2", - NumOfValidators: 10, - Mnemonics: []string{ - "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow", - "hand inmate canvas head lunar naive increase recycle dog ecology inhale december wide bubble hockey dice worth gravity ketchup feed balance parent secret orchard", - "cool little feel apple shoulder member menu owner sure update combine execute copper candy orient record pioneer wet vapor junior quiz choice topic logic", - "result guess around primary tissue tiger witness tired canyon clog gift field merry tribe honey popular bring cargo cricket crew hand arrow quantum broom", - "canyon impact autumn parrot sister roof father wing valve result matrix subject step similar actor effort lake comic patch moral lobster charge veteran barely", - "pulp false tongue shield brave broom hurdle attract laugh taxi victory budget fox spirit abstract inside avoid win more cigar perfect opera attract clump", - "idea oxygen faculty harsh citizen section group carbon waste symbol village inspire slim acquire grab donate champion diary north come kitchen emotion dance melody", - "tortoise wife false victory define seek frequent nasty answer wire erosion thumb scrub seek cluster state analyst addict antique panic century image radar agree", - "bacon weird jazz control lumber pottery install parrot paper range license flip gadget cargo armor they pioneer media ordinary agent adjust primary doll access", - "muffin market delay mutual abandon swamp order orbit rose easy sunny retire autumn weekend involve pelican elbow gesture current chicken stock theme antique fringe", - }, - BondDenom: config.BaseDenom, - MinGasPrices: fmt.Sprintf("0.000006%s", config.BaseDenom), - 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{}, - } -} diff --git a/testutil/network/network_setup.go b/testutil/network/network_setup.go index 5328659b2a..7cb0c8f2fc 100644 --- a/testutil/network/network_setup.go +++ b/testutil/network/network_setup.go @@ -15,29 +15,41 @@ import ( "testing" "time" - "cosmossdk.io/math" - tmlog "github.com/cometbft/cometbft/libs/log" "github.com/cometbft/cometbft/node" tmclient "github.com/cometbft/cometbft/rpc/client" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/cmd/zetacored/config" "google.golang.org/grpc" + "cosmossdk.io/math" + tmlog "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" srvconfig "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" - + pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + _ "github.com/cosmos/cosmos-sdk/x/auth" + _ "github.com/cosmos/cosmos-sdk/x/auth/tx/config" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + _ "github.com/cosmos/cosmos-sdk/x/bank" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + _ "github.com/cosmos/cosmos-sdk/x/consensus" "github.com/cosmos/cosmos-sdk/x/genutil" + _ "github.com/cosmos/cosmos-sdk/x/params" + _ "github.com/cosmos/cosmos-sdk/x/staking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -46,7 +58,16 @@ var lock = new(sync.Mutex) // AppConstructor defines a function which accepts a network configuration and // creates an ABCI Application to provide to Tendermint. -type AppConstructor = func(val Validator) servertypes.Application +type ( + AppConstructor = func(val ValidatorI) servertypes.Application + TestFixtureFactory = func() TestFixture +) + +type TestFixture struct { + AppConstructor AppConstructor + GenesisState map[string]json.RawMessage + EncodingConfig moduletestutil.TestEncodingConfig +} // Config defines the necessary configuration used to bootstrap and start an // in-process local testing network. @@ -61,7 +82,7 @@ type Config struct { GenesisState map[string]json.RawMessage // custom genesis state to provide TimeoutCommit time.Duration // the consensus commitment timeout ChainID string // the network chain-id - NumOfValidators int // the total number of validators to create and bond + NumValidators int // the total number of validators to create and bond Mnemonics []string // custom user-provided validator operator mnemonics BondDenom string // the staking bond denomination MinGasPrices string // the minimum gas prices each validator will accept @@ -79,6 +100,39 @@ type Config struct { PrintMnemonic bool // print the mnemonic of first validator as log output for testing } +// DefaultConfig returns a sane default configuration suitable for nearly all +// testing requirements. +func DefaultConfig(factory TestFixtureFactory) Config { + fixture := factory() + + return Config{ + Codec: fixture.EncodingConfig.Codec, + TxConfig: fixture.EncodingConfig.TxConfig, + LegacyAmino: fixture.EncodingConfig.Amino, + InterfaceRegistry: fixture.EncodingConfig.InterfaceRegistry, + AccountRetriever: authtypes.AccountRetriever{}, + AppConstructor: fixture.AppConstructor, + GenesisState: fixture.GenesisState, + TimeoutCommit: 2 * time.Second, + ChainID: "athens_8888-2", + NumValidators: 2, + BondDenom: config.BaseDenom, + MinGasPrices: fmt.Sprintf("0.000006%s", config.BaseDenom), + 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, + Mnemonics: []string{ + "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow", + "hand inmate canvas head lunar naive increase recycle dog ecology inhale december wide bubble hockey dice worth gravity ketchup feed balance parent secret orchard", + }, + } +} + type ( // Network defines a local in-process testing network using SimApp. It can be // configured to start any number of validators, each with its own RPC and API @@ -116,25 +170,41 @@ type ( ValAddress sdk.ValAddress RPCClient tmclient.Client + app servertypes.Application tmNode *node.Node api *api.Server grpc *grpc.Server grpcWeb *http.Server } -) -// Logger is a network logger interface that exposes testnet-level Log() methods for an in-process testing network -// This is not to be confused with logging that may happen at an individual node or validator level -type Logger interface { - Log(args ...interface{}) - Logf(format string, args ...interface{}) -} + // ValidatorI expose a validator's context and configuration + ValidatorI interface { + GetCtx() *server.Context + GetAppConfig() *srvconfig.Config + } + + // Logger is a network logger interface that exposes testnet-level Log() methods for an in-process testing network + // This is not to be confused with logging that may happen at an individual node or validator level + Logger interface { + Log(args ...interface{}) + Logf(format string, args ...interface{}) + } +) var ( - _ Logger = (*testing.T)(nil) - _ Logger = (*CLILogger)(nil) + _ Logger = (*testing.T)(nil) + _ Logger = (*CLILogger)(nil) + _ ValidatorI = Validator{} ) +func (v Validator) GetCtx() *server.Context { + return v.Ctx +} + +func (v Validator) GetAppConfig() *srvconfig.Config { + return v.AppConfig +} + // CLILogger wraps a cobra.Command and provides command logging methods. type CLILogger struct { cmd *cobra.Command @@ -164,15 +234,15 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { network := &Network{ Logger: l, BaseDir: baseDir, - Validators: make([]*Validator, cfg.NumOfValidators), + Validators: make([]*Validator, cfg.NumValidators), Config: cfg, } l.Logf("preparing test network with chain-id \"%s\"\n", cfg.ChainID) - monikers := make([]string, cfg.NumOfValidators) - nodeIDs := make([]string, cfg.NumOfValidators) - valPubKeys := make([]cryptotypes.PubKey, cfg.NumOfValidators) + monikers := make([]string, cfg.NumValidators) + nodeIDs := make([]string, cfg.NumValidators) + valPubKeys := make([]cryptotypes.PubKey, cfg.NumValidators) var ( genAccounts []authtypes.GenesisAccount @@ -183,7 +253,7 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { buf := bufio.NewReader(os.Stdin) // generate private keys, node IDs, and initial transactions - for i := 0; i < cfg.NumOfValidators; i++ { + for i := 0; i < cfg.NumValidators; i++ { appCfg := srvconfig.DefaultConfig() appCfg.Pruning = cfg.PruningStrategy appCfg.MinGasPrices = cfg.MinGasPrices @@ -261,12 +331,12 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { clientDir := filepath.Join(network.BaseDir, nodeDirName, "simcli") gentxsDir := filepath.Join(network.BaseDir, "gentxs") - err := os.MkdirAll(filepath.Join(nodeDir, "config"), 0o755) // #nosec G301 + err := os.MkdirAll(filepath.Join(nodeDir, "config"), 0o755) if err != nil { return nil, err } - err = os.MkdirAll(clientDir, 0o755) // #nosec G301 + err = os.MkdirAll(clientDir, 0o755) if err != nil { return nil, err } @@ -356,8 +426,8 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { valPubKeys[i], sdk.NewCoin(cfg.BondDenom, cfg.BondedTokens), stakingtypes.NewDescription(nodeDirName, "", "", "", ""), - stakingtypes.NewCommissionRates(commission, sdk.OneDec(), sdk.OneDec()), - sdk.OneInt(), + stakingtypes.NewCommissionRates(commission, math.LegacyOneDec(), math.LegacyOneDec()), + math.OneInt(), ) if err != nil { return nil, err @@ -399,7 +469,6 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { if err != nil { return nil, err } - srvconfig.WriteConfigFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg) clientCtx := client.Context{}. @@ -411,7 +480,11 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { WithCodec(cfg.Codec). WithLegacyAmino(cfg.LegacyAmino). WithTxConfig(cfg.TxConfig). - WithAccountRetriever(cfg.AccountRetriever) + WithAccountRetriever(cfg.AccountRetriever). + WithNodeURI(tmCfg.RPC.ListenAddress) + + // Provide ChainID here since we can't modify it in the Comet config. + ctx.Viper.Set(flags.FlagChainID, cfg.ChainID) network.Validators[i] = &Validator{ AppConfig: appCfg, @@ -468,12 +541,27 @@ func (n *Network) LatestHeight() (int64, error) { return 0, errors.New("no validators available") } - status, err := n.Validators[0].RPCClient.Status(context.Background()) - if err != nil { - return 0, err - } + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + + timeout := time.NewTimer(time.Second * 5) + defer timeout.Stop() - return status.SyncInfo.LatestBlockHeight, nil + var latestHeight int64 + val := n.Validators[0] + queryClient := tmservice.NewServiceClient(val.ClientCtx) + + for { + select { + case <-timeout.C: + return latestHeight, errors.New("timeout exceeded waiting for block") + case <-ticker.C: + res, err := queryClient.GetLatestBlock(context.Background(), &tmservice.GetLatestBlockRequest{}) + if err == nil && res != nil { + return res.SdkBlock.Header.Height, nil + } + } + } } // WaitForHeight performs a blocking check where it waits for a block to be @@ -498,25 +586,43 @@ func (n *Network) WaitForHeightWithTimeout(h int64, t time.Duration) (int64, err var latestHeight int64 val := n.Validators[0] + queryClient := tmservice.NewServiceClient(val.ClientCtx) for { select { case <-timeout.C: return latestHeight, errors.New("timeout exceeded waiting for block") case <-ticker.C: - status, err := val.RPCClient.Status(context.Background()) - if err == nil && status != nil { - latestHeight = status.SyncInfo.LatestBlockHeight + + res, err := queryClient.GetLatestBlock(context.Background(), &tmservice.GetLatestBlockRequest{}) + if err == nil && res != nil { + latestHeight = res.GetSdkBlock().Header.Height if latestHeight >= h { return latestHeight, nil } - } else if err != nil { - fmt.Printf("error trying to fetch block height: %v\n", err) } } } } +// RetryForBlocks will wait for the next block and execute the function provided. +// It will do this until the function returns a nil error or until the number of +// blocks has been reached. +func (n *Network) RetryForBlocks(retryFunc func() error, blocks int) error { + for i := 0; i < blocks; i++ { + n.WaitForNextBlock() + err := retryFunc() + if err == nil { + return nil + } + // we've reached the last block to wait, return the error + if i == blocks-1 { + return err + } + } + return nil +} + // WaitForNextBlock waits for the next block to be committed, returning an error // upon failure. func (n *Network) WaitForNextBlock() error { @@ -533,19 +639,6 @@ func (n *Network) WaitForNextBlock() error { return err } -func (n *Network) WaitForNBlocks(numberOfBlocks int64) error { - lastBlock, err := n.LatestHeight() - if err != nil { - return err - } - _, err = n.WaitForHeightWithTimeout(lastBlock+numberOfBlocks, time.Duration(10*numberOfBlocks)*time.Second) - if err != nil { - return err - } - - return err -} - // Cleanup removes the root testing (temporary) directory and stops both the // Tendermint and API services. It allows other callers to create and start // test networks. This method must be called when a test is finished, typically @@ -573,6 +666,12 @@ func (n *Network) Cleanup() { _ = v.grpcWeb.Close() } } + + if v.app != nil { + if err := v.app.Close(); err != nil { + n.Logger.Log("failed to stop validator ABCI application", "err", err) + } + } } // Give a brief pause for things to finish closing in other processes. Hopefully this helps with the address-in-use errors. diff --git a/testutil/network/util.go b/testutil/network/util.go index 03175249d4..3d1a6a4b8b 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -2,17 +2,17 @@ package network import ( "encoding/json" + "fmt" "os" "path/filepath" "time" - tmos "github.com/cometbft/cometbft/libs/os" "github.com/cometbft/cometbft/node" "github.com/cometbft/cometbft/p2p" pvm "github.com/cometbft/cometbft/privval" "github.com/cometbft/cometbft/proxy" "github.com/cometbft/cometbft/rpc/client/local" - "github.com/cometbft/cometbft/types" + tmtypes "github.com/cometbft/cometbft/types" tmtime "github.com/cometbft/cometbft/types/time" "github.com/cosmos/cosmos-sdk/server/api" @@ -39,9 +39,11 @@ func startInProcess(cfg Config, val *Validator) error { } app := cfg.AppConstructor(*val) + val.app = app + genDocProvider := node.DefaultGenesisDocProviderFunc(tmCfg) - tmNode, err := node.NewNode( + tmNode, err := node.NewNode( //resleak:notresource tmCfg, pvm.LoadOrGenFilePV(tmCfg.PrivValidatorKeyFile(), tmCfg.PrivValidatorStateFile()), nodeKey, @@ -58,7 +60,6 @@ func startInProcess(cfg Config, val *Validator) error { if err := tmNode.Start(); err != nil { return err } - val.tmNode = tmNode if val.RPCAddress != "" { @@ -117,7 +118,7 @@ func startInProcess(cfg Config, val *Validator) error { func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error { genTime := tmtime.Now() - for i := 0; i < cfg.NumOfValidators; i++ { + for i := 0; i < cfg.NumValidators; i++ { tmCfg := vals[i].Ctx.Config nodeDir := filepath.Join(outputDir, vals[i].Moniker, "simd") @@ -129,7 +130,7 @@ func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error { initCfg := genutiltypes.NewInitConfig(cfg.ChainID, gentxsDir, vals[i].NodeID, vals[i].PubKey) genFile := tmCfg.GenesisFile() - genDoc, err := types.GenesisDocFromFile(genFile) + genDoc, err := tmtypes.GenesisDocFromFile(genFile) if err != nil { return err } @@ -141,7 +142,7 @@ func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error { } // overwrite each validator's genesis file to have a canonical genesis time - if err := genutil.ExportGenesisFileWithTime(genFile, cfg.ChainID, nil, appState, genTime); err != nil { + if err := ExportGenesisFileWithTimeAndConsensusParams(genFile, cfg.ChainID, nil, appState, genTime, *genDoc.ConsensusParams); err != nil { return err } } @@ -149,6 +150,25 @@ func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error { return nil } +func ExportGenesisFileWithTimeAndConsensusParams( + genFile, chainID string, validators []tmtypes.GenesisValidator, + appState json.RawMessage, genTime time.Time, consensusParams tmtypes.ConsensusParams, +) error { + genDoc := tmtypes.GenesisDoc{ + GenesisTime: genTime, + ChainID: chainID, + Validators: validators, + AppState: appState, + ConsensusParams: &consensusParams, + } + + if err := genDoc.ValidateAndComplete(); err != nil { + return err + } + + return genDoc.SaveAs(genFile) +} + func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, genFiles []string) error { // set the accounts in the genesis state var authGenState authtypes.GenesisState @@ -174,14 +194,30 @@ func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalance return err } - genDoc := types.GenesisDoc{ + genDoc := tmtypes.GenesisDoc{ + ConsensusParams: &tmtypes.ConsensusParams{ + Block: tmtypes.BlockParams{ + MaxBytes: 200000, + MaxGas: 2000000, + }, + Evidence: tmtypes.EvidenceParams{ + MaxAgeNumBlocks: 302400, + MaxAgeDuration: 504 * time.Hour, // 3 weeks is the max duration + MaxBytes: 10000, + }, + Validator: tmtypes.ValidatorParams{ + PubKeyTypes: []string{ + tmtypes.ABCIPubKeyTypeEd25519, + }, + }, + }, ChainID: cfg.ChainID, AppState: appGenStateJSON, Validators: nil, } // generate empty genesis files for each validator and save - for i := 0; i < cfg.NumOfValidators; i++ { + for i := 0; i < cfg.NumValidators; i++ { if err := genDoc.SaveAs(genFiles[i]); err != nil { return err } @@ -191,16 +227,13 @@ func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalance } func writeFile(name string, dir string, contents []byte) error { - writePath := filepath.Join(dir) //nolint:gocritic - file := filepath.Join(writePath, name) + file := filepath.Join(dir, name) - err := tmos.EnsureDir(writePath, 0o755) - if err != nil { - return err + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("could not create directory %q: %w", dir, err) } - err = os.WriteFile(file, contents, 0600) - if err != nil { + if err := os.WriteFile(file, contents, 0o644); err != nil { //nolint: gosec return err } diff --git a/x/crosschain/client/querytests/cli_test.go b/x/crosschain/client/querytests/cli_test.go index d07c461dea..ca7a115d8b 100644 --- a/x/crosschain/client/querytests/cli_test.go +++ b/x/crosschain/client/querytests/cli_test.go @@ -1,65 +1,46 @@ package querytests import ( - "fmt" "testing" - "time" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" servertypes "github.com/cosmos/cosmos-sdk/server/types" pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + "github.com/cosmos/cosmos-sdk/types/module/testutil" tmdb "github.com/cometbft/cometbft-db" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/suite" "github.com/zeta-chain/zetacore/app" - "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/testutil/network" ) func TestCLIQuerySuite(t *testing.T) { - cfg := CliTestConfig() + cfg := network.DefaultConfig(NewTestNetworkFixture) suite.Run(t, NewCLITestSuite(cfg)) } -func CliTestConfig() network.Config { +func NewTestNetworkFixture() network.TestFixture { encoding := app.MakeEncodingConfig() - return network.Config{ - Codec: encoding.Codec, - TxConfig: encoding.TxConfig, - LegacyAmino: encoding.Amino, - InterfaceRegistry: encoding.InterfaceRegistry, - AccountRetriever: authtypes.AccountRetriever{}, - AppConstructor: func(val network.Validator) servertypes.Application { - return app.New( - val.Ctx.Logger, tmdb.NewMemDB(), nil, true, map[int64]bool{}, val.Ctx.Config.RootDir, 0, - encoding, - simtestutil.EmptyAppOptions{}, - baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.AppConfig.Pruning)), - baseapp.SetMinGasPrices(val.AppConfig.MinGasPrices), - baseapp.SetChainID("athens_8888-2"), - ) - }, - GenesisState: app.ModuleBasics.DefaultGenesis(encoding.Codec), - TimeoutCommit: 2 * time.Second, - ChainID: "athens_8888-2", - NumOfValidators: 2, - Mnemonics: []string{ - "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow", - "hand inmate canvas head lunar naive increase recycle dog ecology inhale december wide bubble hockey dice worth gravity ketchup feed balance parent secret orchard", + appCtr := func(val network.ValidatorI) servertypes.Application { + return app.New( + val.GetCtx().Logger, tmdb.NewMemDB(), nil, true, map[int64]bool{}, val.GetCtx().Config.RootDir, 0, + encoding, + simtestutil.EmptyAppOptions{}, + baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)), + baseapp.SetMinGasPrices(val.GetAppConfig().MinGasPrices), + baseapp.SetChainID("athens_8888-2"), + ) + } + + return network.TestFixture{ + AppConstructor: appCtr, + GenesisState: app.ModuleBasics.DefaultGenesis(encoding.Codec), + EncodingConfig: testutil.TestEncodingConfig{ + InterfaceRegistry: encoding.InterfaceRegistry, + Codec: encoding.Codec, + TxConfig: encoding.TxConfig, + Amino: encoding.Amino, }, - BondDenom: config.BaseDenom, - MinGasPrices: fmt.Sprintf("0.000006%s", config.BaseDenom), - 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{}, } } diff --git a/x/crosschain/client/querytests/suite.go b/x/crosschain/client/querytests/suite.go index 156d2772cf..7fcc87f65e 100644 --- a/x/crosschain/client/querytests/suite.go +++ b/x/crosschain/client/querytests/suite.go @@ -32,6 +32,7 @@ func (s *CliTestSuite) Setconfig() { config.SetAddressVerifier(app.VerifyAddressFormat) config.Seal() } + func (s *CliTestSuite) SetupSuite() { s.T().Log("setting up integration test suite") s.Setconfig() diff --git a/x/observer/client/querytests/cli_test.go b/x/observer/client/querytests/cli_test.go index d07c461dea..ca7a115d8b 100644 --- a/x/observer/client/querytests/cli_test.go +++ b/x/observer/client/querytests/cli_test.go @@ -1,65 +1,46 @@ package querytests import ( - "fmt" "testing" - "time" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" servertypes "github.com/cosmos/cosmos-sdk/server/types" pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + "github.com/cosmos/cosmos-sdk/types/module/testutil" tmdb "github.com/cometbft/cometbft-db" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/suite" "github.com/zeta-chain/zetacore/app" - "github.com/zeta-chain/zetacore/cmd/zetacored/config" "github.com/zeta-chain/zetacore/testutil/network" ) func TestCLIQuerySuite(t *testing.T) { - cfg := CliTestConfig() + cfg := network.DefaultConfig(NewTestNetworkFixture) suite.Run(t, NewCLITestSuite(cfg)) } -func CliTestConfig() network.Config { +func NewTestNetworkFixture() network.TestFixture { encoding := app.MakeEncodingConfig() - return network.Config{ - Codec: encoding.Codec, - TxConfig: encoding.TxConfig, - LegacyAmino: encoding.Amino, - InterfaceRegistry: encoding.InterfaceRegistry, - AccountRetriever: authtypes.AccountRetriever{}, - AppConstructor: func(val network.Validator) servertypes.Application { - return app.New( - val.Ctx.Logger, tmdb.NewMemDB(), nil, true, map[int64]bool{}, val.Ctx.Config.RootDir, 0, - encoding, - simtestutil.EmptyAppOptions{}, - baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.AppConfig.Pruning)), - baseapp.SetMinGasPrices(val.AppConfig.MinGasPrices), - baseapp.SetChainID("athens_8888-2"), - ) - }, - GenesisState: app.ModuleBasics.DefaultGenesis(encoding.Codec), - TimeoutCommit: 2 * time.Second, - ChainID: "athens_8888-2", - NumOfValidators: 2, - Mnemonics: []string{ - "race draft rival universe maid cheese steel logic crowd fork comic easy truth drift tomorrow eye buddy head time cash swing swift midnight borrow", - "hand inmate canvas head lunar naive increase recycle dog ecology inhale december wide bubble hockey dice worth gravity ketchup feed balance parent secret orchard", + appCtr := func(val network.ValidatorI) servertypes.Application { + return app.New( + val.GetCtx().Logger, tmdb.NewMemDB(), nil, true, map[int64]bool{}, val.GetCtx().Config.RootDir, 0, + encoding, + simtestutil.EmptyAppOptions{}, + baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)), + baseapp.SetMinGasPrices(val.GetAppConfig().MinGasPrices), + baseapp.SetChainID("athens_8888-2"), + ) + } + + return network.TestFixture{ + AppConstructor: appCtr, + GenesisState: app.ModuleBasics.DefaultGenesis(encoding.Codec), + EncodingConfig: testutil.TestEncodingConfig{ + InterfaceRegistry: encoding.InterfaceRegistry, + Codec: encoding.Codec, + TxConfig: encoding.TxConfig, + Amino: encoding.Amino, }, - BondDenom: config.BaseDenom, - MinGasPrices: fmt.Sprintf("0.000006%s", config.BaseDenom), - 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{}, } }