Skip to content

Commit

Permalink
chore!: Refactor x/bank CLI Tests (cosmos#12706)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderbez authored Aug 3, 2022
1 parent 7103587 commit ccc8003
Show file tree
Hide file tree
Showing 21 changed files with 757 additions and 31 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### Improvements

* (x/bank) [#12706](https://github.com/cosmos/cosmos-sdk/pull/12706) Added the `chain-id` flag to the `AddTxFlagsToCmd` API. There is no longer a need to explicitly register this flag on commands whens `AddTxFlagsToCmd` is already called.
* [#12791](https://github.com/cosmos/cosmos-sdk/pull/12791) Bump the math library used in the sdk and replace old usages of sdk.*
* (x/params) [#12615](https://github.com/cosmos/cosmos-sdk/pull/12615) Add `GetParamSetIfExists` function to params `Subspace` to prevent panics on breaking changes.
* [#12717](https://github.com/cosmos/cosmos-sdk/pull/12717) Use injected encoding params in simapp.
Expand All @@ -70,6 +71,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### API Breaking Changes

* (x/bank) [#12706](https://github.com/cosmos/cosmos-sdk/pull/12706) Removed the `testutil` package from the `x/bank/client` package.
* (simapp) [#12747](https://github.com/cosmos/cosmos-sdk/pull/12747) Remove `simapp.MakeTestEncodingConfig`. Please use `moduletestutil.MakeTestEncodingConfig` (`types/module/testutil`) in tests instead.
* (x/bank) [#12648](https://github.com/cosmos/cosmos-sdk/pull/12648) `NewSendAuthorization` takes a new argument of an optional list of addresses allowed to receive bank assests via authz MsgSend grant. You can pass `nil` for the same behavior as before, i.e. any recipient is allowed.
* (x/bank) [\#12593](https://github.com/cosmos/cosmos-sdk/pull/12593) Add `SpendableCoin` method to `BaseViewKeeper`
Expand Down
23 changes: 23 additions & 0 deletions client/account_retriever.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,26 @@ type AccountRetriever interface {
EnsureExists(clientCtx Context, addr sdk.AccAddress) error
GetAccountNumberSequence(clientCtx Context, addr sdk.AccAddress) (accNum uint64, accSeq uint64, err error)
}

var _ AccountRetriever = (*MockAccountRetriever)(nil)

// MockAccountRetriever defines a no-op basic AccountRetriever that can be used
// in mocked contexts. Tests or context that need more sophisticated testing
// state should implement their own mock AccountRetriever.
type MockAccountRetriever struct{}

func (mar MockAccountRetriever) GetAccount(_ Context, _ sdk.AccAddress) (Account, error) {
return nil, nil
}

func (mar MockAccountRetriever) GetAccountWithHeight(_ Context, _ sdk.AccAddress) (Account, int64, error) {
return nil, 0, nil
}

func (mar MockAccountRetriever) EnsureExists(_ Context, _ sdk.AccAddress) error {
return nil
}

func (mar MockAccountRetriever) GetAccountNumberSequence(_ Context, _ sdk.AccAddress) (uint64, uint64, error) {
return 0, 0, nil
}
12 changes: 4 additions & 8 deletions client/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,10 @@ import (
"io"
"os"

"github.com/gogo/protobuf/proto"
"github.com/spf13/viper"

"sigs.k8s.io/yaml"

"google.golang.org/grpc"

"github.com/gogo/protobuf/proto"
rpcclient "github.com/tendermint/tendermint/rpc/client"
"sigs.k8s.io/yaml"

"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
Expand All @@ -26,7 +22,7 @@ import (
// handling and queries.
type Context struct {
FromAddress sdk.AccAddress
Client rpcclient.Client
Client TendermintRPC
GRPCClient *grpc.ClientConn
ChainID string
Codec codec.Codec
Expand Down Expand Up @@ -128,7 +124,7 @@ func (ctx Context) WithHeight(height int64) Context {

// WithClient returns a copy of the context with an updated RPC client
// instance.
func (ctx Context) WithClient(client rpcclient.Client) Context {
func (ctx Context) WithClient(client TendermintRPC) Context {
ctx.Client = client
return ctx
}
Expand Down
6 changes: 4 additions & 2 deletions client/flags/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const (
FlagReverse = "reverse"
FlagTip = "tip"
FlagAux = "aux"
FlagOutput = tmcli.OutputFlag

// Tendermint logging flags
FlagLogLevel = "log_level"
Expand All @@ -93,7 +94,7 @@ var LineBreak = &cobra.Command{Run: func(*cobra.Command, []string) {}}
func AddQueryFlagsToCmd(cmd *cobra.Command) {
cmd.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to Tendermint RPC interface for this chain")
cmd.Flags().Int64(FlagHeight, 0, "Use a specific height to query state at (this can error if the node is pruning state)")
cmd.Flags().StringP(tmcli.OutputFlag, "o", "text", "Output format (text|json)")
cmd.Flags().StringP(FlagOutput, "o", "text", "Output format (text|json)")

// some base commands does not require chainID e.g `simd testnet` while subcommands do
// hence the flag should not be required for those commands
Expand All @@ -102,7 +103,7 @@ func AddQueryFlagsToCmd(cmd *cobra.Command) {

// AddTxFlagsToCmd adds common flags to a module tx command.
func AddTxFlagsToCmd(cmd *cobra.Command) {
cmd.Flags().StringP(tmcli.OutputFlag, "o", "json", "Output format (text|json)")
cmd.Flags().StringP(FlagOutput, "o", "json", "Output format (text|json)")
cmd.Flags().String(FlagKeyringDir, "", "The client Keyring directory; if omitted, the default 'home' directory will be used")
cmd.Flags().String(FlagFrom, "", "Name or address of private key with which to sign")
cmd.Flags().Uint64P(FlagAccountNumber, "a", 0, "The account number of the signing account (offline mode only)")
Expand All @@ -125,6 +126,7 @@ func AddTxFlagsToCmd(cmd *cobra.Command) {
cmd.Flags().String(FlagFeeGranter, "", "Fee granter grants fees for the transaction")
cmd.Flags().String(FlagTip, "", "Tip is the amount that is going to be transferred to the fee payer on the target chain. This flag is only valid when used with --aux, and is ignored if the target chain didn't enable the TipDecorator")
cmd.Flags().Bool(FlagAux, false, "Generate aux signer data instead of sending a tx")
cmd.Flags().String(FlagChainID, "", "The network chain ID")

// --gas can accept integers and "auto"
cmd.Flags().String(FlagGas, "", fmt.Sprintf("gas limit to set per-transaction; set to %q to calculate sufficient gas automatically (default %d)", GasFlagAuto, DefaultGasLimit))
Expand Down
3 changes: 2 additions & 1 deletion client/grpc_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import (
"reflect"
"strconv"

"github.com/cosmos/cosmos-sdk/codec"
proto "github.com/gogo/protobuf/proto"
"google.golang.org/grpc/encoding"

"github.com/cosmos/cosmos-sdk/codec"

gogogrpc "github.com/gogo/protobuf/grpc"
abci "github.com/tendermint/tendermint/abci/types"
"google.golang.org/grpc"
Expand Down
7 changes: 3 additions & 4 deletions client/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ import (
"strings"

"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

abci "github.com/tendermint/tendermint/abci/types"
tmbytes "github.com/tendermint/tendermint/libs/bytes"
rpcclient "github.com/tendermint/tendermint/rpc/client"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

"github.com/cosmos/cosmos-sdk/store/rootmulti"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand All @@ -20,7 +19,7 @@ import (

// GetNode returns an RPC client. If the context's client is not defined, an
// error is returned.
func (ctx Context) GetNode() (rpcclient.Client, error) {
func (ctx Context) GetNode() (TendermintRPC, error) {
if ctx.Client == nil {
return nil, errors.New("no RPC client is defined in offline mode")
}
Expand Down
28 changes: 28 additions & 0 deletions client/tendermint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package client

import (
"context"

"github.com/tendermint/tendermint/libs/bytes"
rpcclient "github.com/tendermint/tendermint/rpc/client"
"github.com/tendermint/tendermint/rpc/coretypes"
)

// TendermintRPC defines the interface of a Tendermint RPC client needed for
// queries and transaction handling.
type TendermintRPC interface {
rpcclient.ABCIClient

Validators(ctx context.Context, height *int64, page, perPage *int) (*coretypes.ResultValidators, error)
Status(context.Context) (*coretypes.ResultStatus, error)
Block(ctx context.Context, height *int64) (*coretypes.ResultBlock, error)
BlockchainInfo(ctx context.Context, minHeight, maxHeight int64) (*coretypes.ResultBlockchainInfo, error)
Tx(ctx context.Context, hash bytes.HexBytes, prove bool) (*coretypes.ResultTx, error)
TxSearch(
ctx context.Context,
query string,
prove bool,
page, perPage *int,
orderBy string,
) (*coretypes.ResultTxSearch, error)
}
1 change: 0 additions & 1 deletion client/tx/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,6 @@ func (f Factory) getSimPK() (cryptotypes.PubKey, error) {
// the updated fields will be returned.
func (f Factory) Prepare(clientCtx client.Context) (Factory, error) {
fc := f

from := clientCtx.GetFromAddress()

if err := fc.accountRetriever.EnsureExists(clientCtx, from); err != nil {
Expand Down
17 changes: 12 additions & 5 deletions server/cmd/execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,25 @@ import (
func Execute(rootCmd *cobra.Command, envPrefix string, defaultHome string) error {
// Create and set a client.Context on the command's Context. During the pre-run
// of the root command, a default initialized client.Context is provided to
// seed child command execution with values such as AccountRetriver, Keyring,
// seed child command execution with values such as AccountRetriever, Keyring,
// and a Tendermint RPC. This requires the use of a pointer reference when
// getting and setting the client.Context. Ideally, we utilize
// https://github.com/spf13/cobra/pull/1118.
srvCtx := server.NewDefaultContext()
ctx := context.Background()
ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{})
ctx = context.WithValue(ctx, server.ServerContextKey, srvCtx)
ctx := CreateExecuteContext(context.Background())

rootCmd.PersistentFlags().String(flags.FlagLogLevel, zerolog.InfoLevel.String(), "The logging level (trace|debug|info|warn|error|fatal|panic)")
rootCmd.PersistentFlags().String(flags.FlagLogFormat, tmlog.LogFormatPlain, "The logging format (json|plain)")

executor := tmcli.PrepareBaseCmd(rootCmd, envPrefix, defaultHome)
return executor.ExecuteContext(ctx)
}

// CreateExecuteContext returns a base Context with server and client context
// values initialized.
func CreateExecuteContext(ctx context.Context) context.Context {
srvCtx := server.NewDefaultContext()
ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{})
ctx = context.WithValue(ctx, server.ServerContextKey, srvCtx)

return ctx
}
2 changes: 0 additions & 2 deletions simapp/simd/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,6 @@ func queryCommand() *cobra.Command {
)

simapp.ModuleBasics.AddQueryCommands(cmd)
cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID")

return cmd
}
Expand All @@ -243,7 +242,6 @@ func txCommand() *cobra.Command {
)

simapp.ModuleBasics.AddTxCommands(cmd)
cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID")

return cmd
}
Expand Down
2 changes: 1 addition & 1 deletion x/auth/client/cli/tips.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func GetAuxToFeeCommand() *cobra.Command {
}

flags.AddTxFlagsToCmd(cmd)
cmd.Flags().String(flags.FlagChainID, "", "network chain ID")

return cmd
}

Expand Down
1 change: 0 additions & 1 deletion x/auth/client/cli/tx_multisign.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ The SIGN_MODE_DIRECT sign mode is not supported.'
cmd.Flags().String(flags.FlagOutputDocument, "", "The document is written to the given file instead of STDOUT")
cmd.Flags().Bool(flagAmino, false, "Generate Amino-encoded JSON suitable for submitting to the txs REST endpoint")
flags.AddTxFlagsToCmd(cmd)
cmd.Flags().String(flags.FlagChainID, "", "network chain ID")

return cmd
}
Expand Down
2 changes: 0 additions & 2 deletions x/auth/client/cli/tx_sign.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ account key. It implies --signature-only.
cmd.Flags().String(flagMultisig, "", "Address or key name of the multisig account on behalf of which the transaction shall be signed")
cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT")
cmd.Flags().Bool(flagSigOnly, true, "Print only the generated signature, then exit")
cmd.Flags().String(flags.FlagChainID, "", "network chain ID")
flags.AddTxFlagsToCmd(cmd)

cmd.MarkFlagRequired(flags.FlagFrom)
Expand Down Expand Up @@ -192,7 +191,6 @@ be generated via the 'multisign' command.
cmd.Flags().Bool(flagOverwrite, false, "Overwrite existing signatures with a new one. If disabled, new signature will be appended")
cmd.Flags().Bool(flagSigOnly, false, "Print only the signatures")
cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT")
cmd.Flags().String(flags.FlagChainID, "", "The network chain ID")
cmd.Flags().Bool(flagAmino, false, "Generate Amino encoded JSON suitable for submiting to the txs REST endpoint")
flags.AddTxFlagsToCmd(cmd)

Expand Down
1 change: 0 additions & 1 deletion x/auth/client/cli/validate_sigs.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ transaction will be not be performed as that will require RPC communication with
Args: cobra.ExactArgs(1),
}

cmd.Flags().String(flags.FlagChainID, "", "The network chain ID")
flags.AddTxFlagsToCmd(cmd)

return cmd
Expand Down
9 changes: 9 additions & 0 deletions x/bank/client/cli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ Example:
if err != nil {
return err
}

denom, err := cmd.Flags().GetString(FlagDenom)
if err != nil {
return err
Expand All @@ -75,17 +76,22 @@ Example:
if err != nil {
return err
}

ctx := cmd.Context()

if denom == "" {
params := types.NewQueryAllBalancesRequest(addr, pageReq)

res, err := queryClient.AllBalances(ctx, params)
if err != nil {
return err
}

return clientCtx.PrintProto(res)
}

params := types.NewQueryBalanceRequest(addr, denom)

res, err := queryClient.Balance(ctx, params)
if err != nil {
return err
Expand Down Expand Up @@ -125,6 +131,7 @@ To query for the client metadata of a specific coin denomination use:
if err != nil {
return err
}

denom, err := cmd.Flags().GetString(FlagDenom)
if err != nil {
return err
Expand Down Expand Up @@ -178,6 +185,7 @@ To query for the total supply of a specific coin denomination use:
if err != nil {
return err
}

denom, err := cmd.Flags().GetString(FlagDenom)
if err != nil {
return err
Expand All @@ -190,6 +198,7 @@ To query for the total supply of a specific coin denomination use:
if err != nil {
return err
}

if denom == "" {
res, err := queryClient.TotalSupply(ctx, &types.QueryTotalSupplyRequest{Pagination: pageReq})
if err != nil {
Expand Down
Loading

0 comments on commit ccc8003

Please sign in to comment.