Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: add mock unit tests for bank module #12721

Merged
merged 9 commits into from
Jul 27, 2022
1 change: 1 addition & 0 deletions scripts/mockgen.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
34 changes: 18 additions & 16 deletions x/bank/keeper/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)}
Expand All @@ -59,19 +61,19 @@ 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)
suite.Require().True(found)
suite.Require().Equal(m, m2)
}

func (suite *IntegrationTestSuite) TestTotalSupply() {
func (suite *KeeperTestSuite) TestTotalSupply() {
// Prepare some test data.
defaultGenesis := types.DefaultGenesisState()
balances := []types.Balance{
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
95 changes: 49 additions & 46 deletions x/bank/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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{})
Expand All @@ -33,19 +32,18 @@ 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)
suite.Require().NotNil(res)
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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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{}
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -288,7 +289,7 @@ func (suite *IntegrationTestSuite) QueryDenomsMetadataRequest() {
}
}

func (suite *IntegrationTestSuite) QueryDenomMetadataRequest() {
func (suite *KeeperTestSuite) QueryDenomMetadataRequest() {
var (
req *types.QueryDenomMetadataRequest
expMetadata = types.Metadata{}
Expand Down Expand Up @@ -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,
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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{
Expand All @@ -425,9 +428,9 @@ func (suite *IntegrationTestSuite) TestGRPCDenomOwners() {
},
},
expPass: true,
numAddrs: 7,
numAddrs: 4,
hasNext: false,
total: 13,
total: 10,
},
}

Expand All @@ -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)
Expand Down
Loading