refactor: add mock unit tests for bank module (#12721)

## Description

Closes: #12503 



---

### Author Checklist

*All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.*

I have...

- [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] added `!` to the type prefix if API or client breaking change
- [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#pr-targeting))
- [ ] provided a link to the relevant issue or specification
- [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/main/docs/building-modules)
- [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#testing)
- [ ] added a changelog entry to `CHANGELOG.md`
- [ ] included comments for [documenting Go code](https://blog.golang.org/godoc)
- [ ] updated the relevant documentation or specification
- [ ] reviewed "Files changed" and left comments if necessary
- [ ] confirmed all CI checks have passed

### Reviewers Checklist

*All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.*

I have...

- [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] confirmed `!` in the type prefix if API or client breaking change
- [ ] confirmed all author checklist items have been addressed 
- [ ] reviewed state machine logic
- [ ] reviewed API design and naming
- [ ] reviewed documentation is accurate
- [ ] reviewed tests and test coverage
- [ ] manually tested (if applicable)
This commit is contained in:
cool-developer 2022-07-27 12:48:32 -04:00 committed by GitHub
parent 9ffd57a5fb
commit 105f22ef8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 1176 additions and 787 deletions

View File

@ -15,3 +15,4 @@ $mockgen_cmd -source=x/feegrant/expected_keepers.go -package testutil -destinati
$mockgen_cmd -source=x/mint/types/expected_keepers.go -package testutil -destination x/mint/testutil/expected_keepers_mocks.go
$mockgen_cmd -source=x/params/proposal_handler_test.go -package testutil -destination x/params/testutil/staking_keeper_mock.go
$mockgen_cmd -source=x/crisis/types/expected_keepers.go -package testutil -destination x/crisis/testutil/expected_keepers_mocks.go
$mockgen_cmd -source=x/bank/types/expected_keepers.go -package testutil -destination x/bank/testutil/expected_keepers_mocks.go

View File

@ -7,35 +7,37 @@ import (
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
)
func (suite *IntegrationTestSuite) TestExportGenesis() {
app, ctx := suite.app, suite.ctx
func (suite *KeeperTestSuite) TestExportGenesis() {
ctx := suite.ctx
expectedMetadata := suite.getTestMetadata()
expectedBalances, expTotalSupply := suite.getTestBalancesAndSupply()
// Adding genesis supply to the expTotalSupply
genesisSupply, _, err := suite.app.BankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit})
genesisSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit})
suite.Require().NoError(err)
expTotalSupply = expTotalSupply.Add(genesisSupply...)
for i := range []int{1, 2} {
app.BankKeeper.SetDenomMetaData(ctx, expectedMetadata[i])
suite.bankKeeper.SetDenomMetaData(ctx, expectedMetadata[i])
accAddr, err1 := sdk.AccAddressFromBech32(expectedBalances[i].Address)
if err1 != nil {
panic(err1)
}
// set balances via mint and send
suite.mockMintCoins(mintAcc)
suite.
Require().
NoError(app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedBalances[i].Coins))
NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedBalances[i].Coins))
suite.mockSendCoinsFromModuleToAccount(mintAcc, accAddr)
suite.
Require().
NoError(app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, accAddr, expectedBalances[i].Coins))
NoError(suite.bankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, accAddr, expectedBalances[i].Coins))
}
suite.Require().NoError(app.BankKeeper.SetParams(ctx, types.DefaultParams()))
suite.Require().NoError(suite.bankKeeper.SetParams(ctx, types.DefaultParams()))
exportGenesis := app.BankKeeper.ExportGenesis(ctx)
exportGenesis := suite.bankKeeper.ExportGenesis(ctx)
suite.Require().Len(exportGenesis.Params.SendEnabled, 0)
suite.Require().Equal(types.DefaultParams().DefaultSendEnabled, exportGenesis.Params.DefaultSendEnabled)
@ -44,7 +46,7 @@ func (suite *IntegrationTestSuite) TestExportGenesis() {
suite.Require().Equal(expectedMetadata, exportGenesis.DenomMetadata)
}
func (suite *IntegrationTestSuite) getTestBalancesAndSupply() ([]types.Balance, sdk.Coins) {
func (suite *KeeperTestSuite) getTestBalancesAndSupply() ([]types.Balance, sdk.Coins) {
addr2, _ := sdk.AccAddressFromBech32("cosmos1f9xjhxm0plzrh9cskf4qee4pc2xwp0n0556gh0")
addr1, _ := sdk.AccAddressFromBech32("cosmos1t5u0jfg3ljsjrh2m9e47d4ny2hea7eehxrzdgd")
addr1Balance := sdk.Coins{sdk.NewInt64Coin("testcoin3", 10)}
@ -59,11 +61,11 @@ func (suite *IntegrationTestSuite) getTestBalancesAndSupply() ([]types.Balance,
}, totalSupply
}
func (suite *IntegrationTestSuite) TestInitGenesis() {
func (suite *KeeperTestSuite) TestInitGenesis() {
m := types.Metadata{Description: sdk.DefaultBondDenom, Base: sdk.DefaultBondDenom, Display: sdk.DefaultBondDenom}
g := types.DefaultGenesisState()
g.DenomMetadata = []types.Metadata{m}
bk := suite.app.BankKeeper
bk := suite.bankKeeper
bk.InitGenesis(suite.ctx, g)
m2, found := bk.GetDenomMetaData(suite.ctx, m.Base)
@ -71,7 +73,7 @@ func (suite *IntegrationTestSuite) TestInitGenesis() {
suite.Require().Equal(m, m2)
}
func (suite *IntegrationTestSuite) TestTotalSupply() {
func (suite *KeeperTestSuite) TestTotalSupply() {
// Prepare some test data.
defaultGenesis := types.DefaultGenesisState()
balances := []types.Balance{
@ -81,7 +83,7 @@ func (suite *IntegrationTestSuite) TestTotalSupply() {
}
totalSupply := sdk.NewCoins(sdk.NewCoin("foocoin", sdk.NewInt(11)), sdk.NewCoin("barcoin", sdk.NewInt(21)))
genesisSupply, _, err := suite.app.BankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit})
genesisSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit})
suite.Require().NoError(err)
testcases := []struct {
@ -112,10 +114,10 @@ func (suite *IntegrationTestSuite) TestTotalSupply() {
tc := tc
suite.Run(tc.name, func() {
if tc.expPanic {
suite.PanicsWithError(tc.expPanicMsg, func() { suite.app.BankKeeper.InitGenesis(suite.ctx, tc.genesis) })
suite.PanicsWithError(tc.expPanicMsg, func() { suite.bankKeeper.InitGenesis(suite.ctx, tc.genesis) })
} else {
suite.app.BankKeeper.InitGenesis(suite.ctx, tc.genesis)
totalSupply, _, err := suite.app.BankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit})
suite.bankKeeper.InitGenesis(suite.ctx, tc.genesis)
totalSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit})
suite.Require().NoError(err)
// adding genesis supply to expected supply

View File

@ -5,7 +5,6 @@ import (
"fmt"
"time"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
@ -16,8 +15,8 @@ import (
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
)
func (suite *IntegrationTestSuite) TestQueryBalance() {
app, ctx, queryClient := suite.app, suite.ctx, suite.queryClient
func (suite *KeeperTestSuite) TestQueryBalance() {
ctx, queryClient := suite.ctx, suite.queryClient
_, _, addr := testdata.KeyTestPubAddr()
_, err := queryClient.Balance(gocontext.Background(), &types.QueryBalanceRequest{})
@ -33,10 +32,9 @@ func (suite *IntegrationTestSuite) TestQueryBalance() {
suite.True(res.Balance.IsZero())
origCoins := sdk.NewCoins(newFooCoin(50), newBarCoin(30))
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr)
app.AccountKeeper.SetAccount(ctx, acc)
suite.Require().NoError(testutil.FundAccount(app.BankKeeper, ctx, acc.GetAddress(), origCoins))
suite.mockFundAccount(addr)
suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, ctx, addr, origCoins))
res, err = queryClient.Balance(gocontext.Background(), req)
suite.Require().NoError(err)
@ -44,8 +42,8 @@ func (suite *IntegrationTestSuite) TestQueryBalance() {
suite.True(res.Balance.IsEqual(newFooCoin(50)))
}
func (suite *IntegrationTestSuite) TestQueryAllBalances() {
app, ctx, queryClient := suite.app, suite.ctx, suite.queryClient
func (suite *KeeperTestSuite) TestQueryAllBalances() {
ctx, queryClient := suite.ctx, suite.queryClient
_, _, addr := testdata.KeyTestPubAddr()
_, err := queryClient.AllBalances(gocontext.Background(), &types.QueryAllBalancesRequest{})
suite.Require().Error(err)
@ -65,10 +63,9 @@ func (suite *IntegrationTestSuite) TestQueryAllBalances() {
barCoins := newBarCoin(30)
origCoins := sdk.NewCoins(fooCoins, barCoins)
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr)
app.AccountKeeper.SetAccount(ctx, acc)
suite.Require().NoError(testutil.FundAccount(app.BankKeeper, ctx, acc.GetAddress(), origCoins))
suite.mockFundAccount(addr)
suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, ctx, addr, origCoins))
res, err = queryClient.AllBalances(gocontext.Background(), req)
suite.Require().NoError(err)
@ -89,10 +86,11 @@ func (suite *IntegrationTestSuite) TestQueryAllBalances() {
suite.Nil(res.Pagination.NextKey)
}
func (suite *IntegrationTestSuite) TestSpendableBalances() {
app, ctx, queryClient := suite.app, suite.ctx, suite.queryClient
func (suite *KeeperTestSuite) TestSpendableBalances() {
ctx := suite.ctx
_, _, addr := testdata.KeyTestPubAddr()
ctx = ctx.WithBlockTime(time.Now())
queryClient := suite.mockQueryClient(ctx)
_, err := queryClient.SpendableBalances(sdk.WrapSDKContext(ctx), &types.QuerySpendableBalancesRequest{})
suite.Require().Error(err)
@ -103,7 +101,9 @@ func (suite *IntegrationTestSuite) TestSpendableBalances() {
CountTotal: false,
}
req := types.NewQuerySpendableBalancesRequest(addr, pageReq)
acc := authtypes.NewBaseAccountWithAddress(addr)
suite.mockSpendableCoins(ctx, acc)
res, err := queryClient.SpendableBalances(sdk.WrapSDKContext(ctx), req)
suite.Require().NoError(err)
suite.Require().NotNil(res)
@ -113,23 +113,21 @@ func (suite *IntegrationTestSuite) TestSpendableBalances() {
barCoins := newBarCoin(30)
origCoins := sdk.NewCoins(fooCoins, barCoins)
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr)
acc = vestingtypes.NewContinuousVestingAccount(
acc.(*authtypes.BaseAccount),
vacc := vestingtypes.NewContinuousVestingAccount(
acc,
sdk.NewCoins(fooCoins),
ctx.BlockTime().Unix(),
ctx.BlockTime().Add(time.Hour).Unix(),
)
app.AccountKeeper.SetAccount(ctx, acc)
suite.Require().NoError(testutil.FundAccount(app.BankKeeper, ctx, acc.GetAddress(), origCoins))
suite.mockFundAccount(addr)
suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, suite.ctx, addr, origCoins))
// move time forward for some tokens to vest
ctx = ctx.WithBlockTime(ctx.BlockTime().Add(30 * time.Minute))
queryHelper := baseapp.NewQueryServerTestHelper(ctx, app.InterfaceRegistry())
types.RegisterQueryServer(queryHelper, app.BankKeeper)
queryClient = types.NewQueryClient(queryHelper)
queryClient = suite.mockQueryClient(ctx)
suite.mockSpendableCoins(ctx, vacc)
res, err = queryClient.SpendableBalances(sdk.WrapSDKContext(ctx), req)
suite.Require().NoError(err)
suite.Require().NotNil(res)
@ -139,35 +137,38 @@ func (suite *IntegrationTestSuite) TestSpendableBalances() {
suite.EqualValues(25, res.Balances[1].Amount.Int64())
}
func (suite *IntegrationTestSuite) TestQueryTotalSupply() {
app, ctx, queryClient := suite.app, suite.ctx, suite.queryClient
func (suite *KeeperTestSuite) TestQueryTotalSupply() {
ctx, queryClient := suite.ctx, suite.queryClient
res, err := queryClient.TotalSupply(gocontext.Background(), &types.QueryTotalSupplyRequest{})
suite.Require().NoError(err)
genesisSupply := res.Supply
testCoins := sdk.NewCoins(sdk.NewInt64Coin("test", 400000000))
suite.mockMintCoins(mintAcc)
suite.
Require().
NoError(app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, testCoins))
NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, testCoins))
res, err = queryClient.TotalSupply(gocontext.Background(), &types.QueryTotalSupplyRequest{})
suite.Require().NoError(err)
suite.Require().NotNil(res)
expectedTotalSupply := genesisSupply.Add(testCoins...)
suite.Require().Equal(2, len(res.Supply))
suite.Require().Equal(1, len(res.Supply))
suite.Require().Equal(res.Supply, expectedTotalSupply)
}
func (suite *IntegrationTestSuite) TestQueryTotalSupplyOf() {
app, ctx, queryClient := suite.app, suite.ctx, suite.queryClient
func (suite *KeeperTestSuite) TestQueryTotalSupplyOf() {
ctx, queryClient := suite.ctx, suite.queryClient
test1Supply := sdk.NewInt64Coin("test1", 4000000)
test2Supply := sdk.NewInt64Coin("test2", 700000000)
expectedTotalSupply := sdk.NewCoins(test1Supply, test2Supply)
suite.mockMintCoins(mintAcc)
suite.
Require().
NoError(app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedTotalSupply))
NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedTotalSupply))
_, err := queryClient.SupplyOf(gocontext.Background(), &types.QuerySupplyOfRequest{})
suite.Require().Error(err)
@ -179,14 +180,14 @@ func (suite *IntegrationTestSuite) TestQueryTotalSupplyOf() {
suite.Require().Equal(test1Supply, res.Amount)
}
func (suite *IntegrationTestSuite) TestQueryParams() {
func (suite *KeeperTestSuite) TestQueryParams() {
res, err := suite.queryClient.Params(gocontext.Background(), &types.QueryParamsRequest{})
suite.Require().NoError(err)
suite.Require().NotNil(res)
suite.Require().Equal(suite.app.BankKeeper.GetParams(suite.ctx), res.GetParams())
suite.Require().Equal(suite.bankKeeper.GetParams(suite.ctx), res.GetParams())
}
func (suite *IntegrationTestSuite) QueryDenomsMetadataRequest() {
func (suite *KeeperTestSuite) QueryDenomsMetadataRequest() {
var (
req *types.QueryDenomsMetadataRequest
expMetadata = []types.Metadata{}
@ -254,8 +255,8 @@ func (suite *IntegrationTestSuite) QueryDenomsMetadataRequest() {
Display: "eth",
}
suite.app.BankKeeper.SetDenomMetaData(suite.ctx, metadataAtom)
suite.app.BankKeeper.SetDenomMetaData(suite.ctx, metadataEth)
suite.bankKeeper.SetDenomMetaData(suite.ctx, metadataAtom)
suite.bankKeeper.SetDenomMetaData(suite.ctx, metadataEth)
expMetadata = []types.Metadata{metadataAtom, metadataEth}
req = &types.QueryDenomsMetadataRequest{
Pagination: &query.PageRequest{
@ -288,7 +289,7 @@ func (suite *IntegrationTestSuite) QueryDenomsMetadataRequest() {
}
}
func (suite *IntegrationTestSuite) QueryDenomMetadataRequest() {
func (suite *KeeperTestSuite) QueryDenomMetadataRequest() {
var (
req *types.QueryDenomMetadataRequest
expMetadata = types.Metadata{}
@ -336,7 +337,7 @@ func (suite *IntegrationTestSuite) QueryDenomMetadataRequest() {
Display: "atom",
}
suite.app.BankKeeper.SetDenomMetaData(suite.ctx, expMetadata)
suite.bankKeeper.SetDenomMetaData(suite.ctx, expMetadata)
req = &types.QueryDenomMetadataRequest{
Denom: expMetadata.Base,
}
@ -365,21 +366,23 @@ func (suite *IntegrationTestSuite) QueryDenomMetadataRequest() {
}
}
func (suite *IntegrationTestSuite) TestGRPCDenomOwners() {
func (suite *KeeperTestSuite) TestGRPCDenomOwners() {
ctx := suite.ctx
authKeeper, keeper := suite.initKeepersWithmAccPerms(make(map[string]bool))
keeper := suite.bankKeeper
suite.mockMintCoins(mintAcc)
suite.Require().NoError(keeper.MintCoins(ctx, minttypes.ModuleName, initCoins))
for i := 0; i < 10; i++ {
acc := authKeeper.NewAccountWithAddress(ctx, authtypes.NewModuleAddress(fmt.Sprintf("account-%d", i)))
authKeeper.SetAccount(ctx, acc)
addr := sdk.AccAddress([]byte(fmt.Sprintf("account-%d", i)))
bal := sdk.NewCoins(sdk.NewCoin(
sdk.DefaultBondDenom,
sdk.TokensFromConsensusPower(initialPower/10, sdk.DefaultPowerReduction),
))
suite.Require().NoError(keeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, acc.GetAddress(), bal))
suite.mockSendCoinsFromModuleToAccount(mintAcc, addr)
suite.Require().NoError(keeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, bal))
}
testCases := map[string]struct {
@ -413,7 +416,7 @@ func (suite *IntegrationTestSuite) TestGRPCDenomOwners() {
expPass: true,
numAddrs: 6,
hasNext: true,
total: 13,
total: 10,
},
"valid request - page 2": {
req: &types.QueryDenomOwnersRequest{
@ -425,9 +428,9 @@ func (suite *IntegrationTestSuite) TestGRPCDenomOwners() {
},
},
expPass: true,
numAddrs: 7,
numAddrs: 4,
hasNext: false,
total: 13,
total: 10,
},
}
@ -454,8 +457,8 @@ func (suite *IntegrationTestSuite) TestGRPCDenomOwners() {
suite.Require().True(true)
}
func (suite *IntegrationTestSuite) TestQuerySendEnabled() {
ctx, bankKeeper := suite.ctx, suite.app.BankKeeper
func (suite *KeeperTestSuite) TestQuerySendEnabled() {
ctx, bankKeeper := suite.ctx, suite.bankKeeper
bankKeeper.SetSendEnabled(ctx, "falsestcoin", false)
bankKeeper.SetSendEnabled(ctx, "truestcoin", true)

File diff suppressed because it is too large Load Diff

View File

@ -7,7 +7,7 @@ import (
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/errors"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/bank/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
)
@ -41,7 +41,7 @@ func (k msgServer) Send(goCtx context.Context, msg *types.MsgSend) (*types.MsgSe
}
if k.BlockedAddr(to) {
return nil, errors.Wrapf(errors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress)
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", msg.ToAddress)
}
err = k.SendCoins(ctx, from, to, msg.Amount)
@ -85,7 +85,7 @@ func (k msgServer) MultiSend(goCtx context.Context, msg *types.MsgMultiSend) (*t
accAddr := sdk.MustAccAddressFromBech32(out.Address)
if k.BlockedAddr(accAddr) {
return nil, errors.Wrapf(errors.ErrUnauthorized, "%s is not allowed to receive transactions", out.Address)
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", out.Address)
}
}
@ -106,7 +106,7 @@ func (k msgServer) MultiSend(goCtx context.Context, msg *types.MsgMultiSend) (*t
func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) {
if k.GetAuthority() != req.Authority {
return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), req.Authority)
return nil, sdkerrors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), req.Authority)
}
ctx := sdk.UnwrapSDKContext(goCtx)

View File

@ -1,22 +1,24 @@
package keeper_test
import (
"github.com/cosmos/cosmos-sdk/x/bank/types"
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"
)
func (suite *IntegrationTestSuite) TestMsgUpdateParams() {
func (suite *KeeperTestSuite) TestMsgUpdateParams() {
// default params
params := types.DefaultParams()
params := banktypes.DefaultParams()
testCases := []struct {
name string
input *types.MsgUpdateParams
input *banktypes.MsgUpdateParams
expErr bool
expErrMsg string
}{
{
name: "invalid authority",
input: &types.MsgUpdateParams{
input: &banktypes.MsgUpdateParams{
Authority: "invalid",
Params: params,
},
@ -25,10 +27,10 @@ func (suite *IntegrationTestSuite) TestMsgUpdateParams() {
},
{
name: "send enabled param",
input: &types.MsgUpdateParams{
Authority: suite.app.BankKeeper.GetAuthority(),
Params: types.Params{
SendEnabled: []*types.SendEnabled{
input: &banktypes.MsgUpdateParams{
Authority: suite.bankKeeper.GetAuthority(),
Params: banktypes.Params{
SendEnabled: []*banktypes.SendEnabled{
{Denom: "foo", Enabled: true},
},
},
@ -37,8 +39,8 @@ func (suite *IntegrationTestSuite) TestMsgUpdateParams() {
},
{
name: "all good",
input: &types.MsgUpdateParams{
Authority: suite.app.BankKeeper.GetAuthority(),
input: &banktypes.MsgUpdateParams{
Authority: suite.bankKeeper.GetAuthority(),
Params: params,
},
expErr: false,
@ -59,3 +61,113 @@ func (suite *IntegrationTestSuite) TestMsgUpdateParams() {
})
}
}
func (suite *KeeperTestSuite) TestMsgSend() {
origCoins := sdk.NewCoins(sdk.NewInt64Coin("sendableCoin", 100))
suite.bankKeeper.SetSendEnabled(suite.ctx, origCoins.Denoms()[0], true)
testCases := []struct {
name string
input *banktypes.MsgSend
expErr bool
expErrMsg string
}{
{
name: "invalid send to blocked address",
input: &banktypes.MsgSend{
FromAddress: minterAcc.GetAddress().String(),
ToAddress: accAddrs[4].String(),
Amount: origCoins,
},
expErr: true,
expErrMsg: "is not allowed to receive funds",
},
{
name: "all good",
input: &banktypes.MsgSend{
FromAddress: minterAcc.GetAddress().String(),
ToAddress: baseAcc.Address,
Amount: origCoins,
},
expErr: false,
},
}
for _, tc := range testCases {
tc := tc
suite.Run(tc.name, func() {
suite.mockMintCoins(minterAcc)
suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins)
if !tc.expErr {
suite.mockSendCoins(suite.ctx, minterAcc, baseAcc.GetAddress())
}
_, err := suite.msgServer.Send(suite.ctx, tc.input)
if tc.expErr {
suite.Require().Error(err)
suite.Require().Contains(err.Error(), tc.expErrMsg)
} else {
suite.Require().NoError(err)
}
})
}
}
func (suite *KeeperTestSuite) TestMsgMultiSend() {
origDenom := "sendableCoin"
origCoins := sdk.NewCoins(sdk.NewInt64Coin(origDenom, 100))
sendCoins := sdk.NewCoins(sdk.NewInt64Coin(origDenom, 50))
suite.bankKeeper.SetSendEnabled(suite.ctx, origDenom, true)
testCases := []struct {
name string
input *banktypes.MsgMultiSend
expErr bool
expErrMsg string
}{
{
name: "invalid send to blocked address",
input: &banktypes.MsgMultiSend{
Inputs: []banktypes.Input{
{Address: minterAcc.GetAddress().String(), Coins: origCoins},
},
Outputs: []banktypes.Output{
{Address: accAddrs[0].String(), Coins: sendCoins},
{Address: accAddrs[4].String(), Coins: sendCoins},
},
},
expErr: true,
expErrMsg: "is not allowed to receive funds",
},
{
name: "invalid send to blocked address",
input: &banktypes.MsgMultiSend{
Inputs: []banktypes.Input{
{Address: minterAcc.GetAddress().String(), Coins: origCoins},
},
Outputs: []banktypes.Output{
{Address: accAddrs[0].String(), Coins: sendCoins},
{Address: accAddrs[1].String(), Coins: sendCoins},
},
},
expErr: false,
},
}
for _, tc := range testCases {
tc := tc
suite.Run(tc.name, func() {
suite.mockMintCoins(minterAcc)
suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins)
if !tc.expErr {
suite.mockInputOutputCoins([]authtypes.AccountI{minterAcc}, accAddrs[:2])
}
_, err := suite.msgServer.MultiSend(suite.ctx, tc.input)
if tc.expErr {
suite.Require().Error(err)
suite.Require().Contains(err.Error(), tc.expErrMsg)
} else {
suite.Require().NoError(err)
}
})
}
}

View File

@ -14,16 +14,15 @@ import (
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
)
func (suite *IntegrationTestSuite) TestQuerier_QueryBalance() {
app, ctx := suite.app, suite.ctx
legacyAmino := app.LegacyAmino()
func (suite *KeeperTestSuite) TestQuerier_QueryBalance() {
ctx, legacyAmino := suite.ctx, suite.encCfg.Amino
_, _, addr := testdata.KeyTestPubAddr()
req := abci.RequestQuery{
Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryBalance),
Data: []byte{},
}
querier := keeper.NewQuerier(app.BankKeeper, legacyAmino)
querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino)
res, err := querier(ctx, []string{types.QueryBalance}, req)
suite.Require().NotNil(err)
@ -39,10 +38,9 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryBalance() {
suite.True(balance.IsZero())
origCoins := sdk.NewCoins(newFooCoin(50), newBarCoin(30))
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr)
app.AccountKeeper.SetAccount(ctx, acc)
suite.Require().NoError(testutil.FundAccount(app.BankKeeper, ctx, acc.GetAddress(), origCoins))
suite.mockFundAccount(addr)
suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, ctx, addr, origCoins))
res, err = querier(ctx, []string{types.QueryBalance}, req)
suite.Require().NoError(err)
@ -51,16 +49,15 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryBalance() {
suite.True(balance.IsEqual(newFooCoin(50)))
}
func (suite *IntegrationTestSuite) TestQuerier_QueryAllBalances() {
app, ctx := suite.app, suite.ctx
legacyAmino := app.LegacyAmino()
func (suite *KeeperTestSuite) TestQuerier_QueryAllBalances() {
ctx, legacyAmino := suite.ctx, suite.encCfg.Amino
_, _, addr := testdata.KeyTestPubAddr()
req := abci.RequestQuery{
Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryAllBalances),
Data: []byte{},
}
querier := keeper.NewQuerier(app.BankKeeper, legacyAmino)
querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino)
res, err := querier(ctx, []string{types.QueryAllBalances}, req)
suite.Require().NotNil(err)
@ -76,10 +73,9 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryAllBalances() {
suite.True(balances.IsZero())
origCoins := sdk.NewCoins(newFooCoin(50), newBarCoin(30))
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr)
app.AccountKeeper.SetAccount(ctx, acc)
suite.Require().NoError(testutil.FundAccount(app.BankKeeper, ctx, acc.GetAddress(), origCoins))
suite.mockFundAccount(addr)
suite.Require().NoError(testutil.FundAccount(suite.bankKeeper, ctx, addr, origCoins))
res, err = querier(ctx, []string{types.QueryAllBalances}, req)
suite.Require().NoError(err)
suite.Require().NotNil(res)
@ -87,24 +83,25 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryAllBalances() {
suite.True(balances.IsEqual(origCoins))
}
func (suite *IntegrationTestSuite) TestQuerier_QueryTotalSupply() {
app, ctx := suite.app, suite.ctx
legacyAmino := app.LegacyAmino()
func (suite *KeeperTestSuite) TestQuerier_QueryTotalSupply() {
ctx, legacyAmino := suite.ctx, suite.encCfg.Amino
genesisSupply, _, err := suite.app.BankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit})
genesisSupply, _, err := suite.bankKeeper.GetPaginatedTotalSupply(suite.ctx, &query.PageRequest{Limit: query.MaxLimit})
suite.Require().NoError(err)
testCoins := sdk.NewCoins(sdk.NewInt64Coin("test", 400000000))
suite.mockMintCoins(mintAcc)
suite.
Require().
NoError(app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, testCoins))
NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, testCoins))
req := abci.RequestQuery{
Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryTotalSupply),
Data: []byte{},
}
querier := keeper.NewQuerier(app.BankKeeper, legacyAmino)
querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino)
res, err := querier(ctx, []string{types.QueryTotalSupply}, req)
suite.Require().NotNil(err)
@ -124,22 +121,23 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryTotalSupply() {
suite.Require().Equal(expectedTotalSupply, resp.Supply)
}
func (suite *IntegrationTestSuite) TestQuerier_QueryTotalSupplyOf() {
app, ctx := suite.app, suite.ctx
legacyAmino := app.LegacyAmino()
func (suite *KeeperTestSuite) TestQuerier_QueryTotalSupplyOf() {
ctx, legacyAmino := suite.ctx, suite.encCfg.Amino
test1Supply := sdk.NewInt64Coin("test1", 4000000)
test2Supply := sdk.NewInt64Coin("test2", 700000000)
expectedTotalSupply := sdk.NewCoins(test1Supply, test2Supply)
suite.mockMintCoins(mintAcc)
suite.
Require().
NoError(app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedTotalSupply))
NoError(suite.bankKeeper.MintCoins(ctx, minttypes.ModuleName, expectedTotalSupply))
req := abci.RequestQuery{
Path: fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QuerySupplyOf),
Data: []byte{},
}
querier := keeper.NewQuerier(app.BankKeeper, legacyAmino)
querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino)
res, err := querier(ctx, []string{types.QuerySupplyOf}, req)
suite.Require().NotNil(err)
@ -155,15 +153,15 @@ func (suite *IntegrationTestSuite) TestQuerier_QueryTotalSupplyOf() {
suite.Require().Equal(test1Supply, resp)
}
func (suite *IntegrationTestSuite) TestQuerierRouteNotFound() {
app, ctx := suite.app, suite.ctx
legacyAmino := app.LegacyAmino()
func (suite *KeeperTestSuite) TestQuerierRouteNotFound() {
ctx := suite.ctx
legacyAmino := suite.encCfg.Amino
req := abci.RequestQuery{
Path: fmt.Sprintf("custom/%s/invalid", types.ModuleName),
Data: []byte{},
}
querier := keeper.NewQuerier(app.BankKeeper, legacyAmino)
querier := keeper.NewQuerier(suite.bankKeeper, legacyAmino)
_, err := querier(ctx, []string{"invalid"}, req)
suite.Error(err)
}

View File

@ -0,0 +1,228 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: x/bank/types/expected_keepers.go
// Package testutil is a generated GoMock package.
package testutil
import (
reflect "reflect"
types "github.com/cosmos/cosmos-sdk/types"
types0 "github.com/cosmos/cosmos-sdk/x/auth/types"
gomock "github.com/golang/mock/gomock"
)
// MockAccountKeeper is a mock of AccountKeeper interface.
type MockAccountKeeper struct {
ctrl *gomock.Controller
recorder *MockAccountKeeperMockRecorder
}
// MockAccountKeeperMockRecorder is the mock recorder for MockAccountKeeper.
type MockAccountKeeperMockRecorder struct {
mock *MockAccountKeeper
}
// NewMockAccountKeeper creates a new mock instance.
func NewMockAccountKeeper(ctrl *gomock.Controller) *MockAccountKeeper {
mock := &MockAccountKeeper{ctrl: ctrl}
mock.recorder = &MockAccountKeeperMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder {
return m.recorder
}
// GetAccount mocks base method.
func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types0.AccountI {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetAccount", ctx, addr)
ret0, _ := ret[0].(types0.AccountI)
return ret0
}
// GetAccount indicates an expected call of GetAccount.
func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetAccount), ctx, addr)
}
// GetAllAccounts mocks base method.
func (m *MockAccountKeeper) GetAllAccounts(ctx types.Context) []types0.AccountI {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetAllAccounts", ctx)
ret0, _ := ret[0].([]types0.AccountI)
return ret0
}
// GetAllAccounts indicates an expected call of GetAllAccounts.
func (mr *MockAccountKeeperMockRecorder) GetAllAccounts(ctx interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllAccounts", reflect.TypeOf((*MockAccountKeeper)(nil).GetAllAccounts), ctx)
}
// GetModuleAccount mocks base method.
func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, moduleName string) types0.ModuleAccountI {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetModuleAccount", ctx, moduleName)
ret0, _ := ret[0].(types0.ModuleAccountI)
return ret0
}
// GetModuleAccount indicates an expected call of GetModuleAccount.
func (mr *MockAccountKeeperMockRecorder) GetModuleAccount(ctx, moduleName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAccount), ctx, moduleName)
}
// GetModuleAccountAndPermissions mocks base method.
func (m *MockAccountKeeper) GetModuleAccountAndPermissions(ctx types.Context, moduleName string) (types0.ModuleAccountI, []string) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetModuleAccountAndPermissions", ctx, moduleName)
ret0, _ := ret[0].(types0.ModuleAccountI)
ret1, _ := ret[1].([]string)
return ret0, ret1
}
// GetModuleAccountAndPermissions indicates an expected call of GetModuleAccountAndPermissions.
func (mr *MockAccountKeeperMockRecorder) GetModuleAccountAndPermissions(ctx, moduleName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAccountAndPermissions", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAccountAndPermissions), ctx, moduleName)
}
// GetModuleAddress mocks base method.
func (m *MockAccountKeeper) GetModuleAddress(moduleName string) types.AccAddress {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetModuleAddress", moduleName)
ret0, _ := ret[0].(types.AccAddress)
return ret0
}
// GetModuleAddress indicates an expected call of GetModuleAddress.
func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(moduleName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAddress", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAddress), moduleName)
}
// GetModuleAddressAndPermissions mocks base method.
func (m *MockAccountKeeper) GetModuleAddressAndPermissions(moduleName string) (types.AccAddress, []string) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetModuleAddressAndPermissions", moduleName)
ret0, _ := ret[0].(types.AccAddress)
ret1, _ := ret[1].([]string)
return ret0, ret1
}
// GetModuleAddressAndPermissions indicates an expected call of GetModuleAddressAndPermissions.
func (mr *MockAccountKeeperMockRecorder) GetModuleAddressAndPermissions(moduleName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAddressAndPermissions", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAddressAndPermissions), moduleName)
}
// GetModulePermissions mocks base method.
func (m *MockAccountKeeper) GetModulePermissions() map[string]types0.PermissionsForAddress {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetModulePermissions")
ret0, _ := ret[0].(map[string]types0.PermissionsForAddress)
return ret0
}
// GetModulePermissions indicates an expected call of GetModulePermissions.
func (mr *MockAccountKeeperMockRecorder) GetModulePermissions() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModulePermissions", reflect.TypeOf((*MockAccountKeeper)(nil).GetModulePermissions))
}
// HasAccount mocks base method.
func (m *MockAccountKeeper) HasAccount(ctx types.Context, addr types.AccAddress) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "HasAccount", ctx, addr)
ret0, _ := ret[0].(bool)
return ret0
}
// HasAccount indicates an expected call of HasAccount.
func (mr *MockAccountKeeperMockRecorder) HasAccount(ctx, addr interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasAccount", reflect.TypeOf((*MockAccountKeeper)(nil).HasAccount), ctx, addr)
}
// IterateAccounts mocks base method.
func (m *MockAccountKeeper) IterateAccounts(ctx types.Context, process func(types0.AccountI) bool) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "IterateAccounts", ctx, process)
}
// IterateAccounts indicates an expected call of IterateAccounts.
func (mr *MockAccountKeeperMockRecorder) IterateAccounts(ctx, process interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateAccounts", reflect.TypeOf((*MockAccountKeeper)(nil).IterateAccounts), ctx, process)
}
// NewAccount mocks base method.
func (m *MockAccountKeeper) NewAccount(arg0 types.Context, arg1 types0.AccountI) types0.AccountI {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewAccount", arg0, arg1)
ret0, _ := ret[0].(types0.AccountI)
return ret0
}
// NewAccount indicates an expected call of NewAccount.
func (mr *MockAccountKeeperMockRecorder) NewAccount(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewAccount", reflect.TypeOf((*MockAccountKeeper)(nil).NewAccount), arg0, arg1)
}
// NewAccountWithAddress mocks base method.
func (m *MockAccountKeeper) NewAccountWithAddress(ctx types.Context, addr types.AccAddress) types0.AccountI {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "NewAccountWithAddress", ctx, addr)
ret0, _ := ret[0].(types0.AccountI)
return ret0
}
// NewAccountWithAddress indicates an expected call of NewAccountWithAddress.
func (mr *MockAccountKeeperMockRecorder) NewAccountWithAddress(ctx, addr interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewAccountWithAddress", reflect.TypeOf((*MockAccountKeeper)(nil).NewAccountWithAddress), ctx, addr)
}
// SetAccount mocks base method.
func (m *MockAccountKeeper) SetAccount(ctx types.Context, acc types0.AccountI) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "SetAccount", ctx, acc)
}
// SetAccount indicates an expected call of SetAccount.
func (mr *MockAccountKeeperMockRecorder) SetAccount(ctx, acc interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetAccount), ctx, acc)
}
// SetModuleAccount mocks base method.
func (m *MockAccountKeeper) SetModuleAccount(ctx types.Context, macc types0.ModuleAccountI) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "SetModuleAccount", ctx, macc)
}
// SetModuleAccount indicates an expected call of SetModuleAccount.
func (mr *MockAccountKeeperMockRecorder) SetModuleAccount(ctx, macc interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).SetModuleAccount), ctx, macc)
}
// ValidatePermissions mocks base method.
func (m *MockAccountKeeper) ValidatePermissions(macc types0.ModuleAccountI) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ValidatePermissions", macc)
ret0, _ := ret[0].(error)
return ret0
}
// ValidatePermissions indicates an expected call of ValidatePermissions.
func (mr *MockAccountKeeperMockRecorder) ValidatePermissions(macc interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidatePermissions", reflect.TypeOf((*MockAccountKeeper)(nil).ValidatePermissions), macc)
}

View File

@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
@ -21,12 +21,11 @@ var (
)
func TestSendAuthorization(t *testing.T) {
app := simapp.Setup(t, false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
ctx := testutil.DefaultContextWithDB(t, sdk.NewKVStoreKey(types.StoreKey), sdk.NewTransientStoreKey("transient_test")).Ctx.WithBlockHeader(tmproto.Header{})
allowList := make([]sdk.AccAddress, 1)
allowList[0] = toAddr
authorization := types.NewSendAuthorization(coins1000, nil)
t.Log("verify authorization returns valid method name")
require.Equal(t, authorization.MsgTypeURL(), "/cosmos.bank.v1beta1.MsgSend")
require.NoError(t, authorization.ValidateBasic())