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: Use mocks for x/nft testing #12407

Merged
merged 18 commits into from
Jul 5, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ mocks: $(MOCKS_DIR)
$(mockgen_cmd) -package mocks -destination tests/mocks/grpc_server.go github.com/gogo/protobuf/grpc Server
$(mockgen_cmd) -package mocks -destination tests/mocks/tendermint_tendermint_libs_log_DB.go github.com/tendermint/tendermint/libs/log Logger
$(mockgen_cmd) -source=orm/model/ormtable/hooks.go -package ormmocks -destination orm/testing/ormmocks/hooks.go
$(mockgen_cmd) -source=x/nft/expected_keepers.go -package testutil -destination x/nft/testutil/expected_keepers_mocks.go
facundomedica marked this conversation as resolved.
Show resolved Hide resolved
.PHONY: mocks

$(MOCKS_DIR):
Expand Down
15 changes: 15 additions & 0 deletions testutil/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,18 @@ func DefaultContext(key storetypes.StoreKey, tkey storetypes.StoreKey) sdk.Conte

return ctx
}

func DefaultContextWithDB(key storetypes.StoreKey, tkey storetypes.StoreKey) (sdk.Context, *dbm.MemDB, store.CommitMultiStore) {
facundomedica marked this conversation as resolved.
Show resolved Hide resolved
db := dbm.NewMemDB()
cms := store.NewCommitMultiStore(db)
cms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, db)
cms.MountStoreWithDB(tkey, storetypes.StoreTypeTransient, db)
err := cms.LoadLatestVersion()
if err != nil {
panic(err)
}

ctx := sdk.NewContext(cms, tmproto.Header{}, false, log.NewNopLogger())

return ctx, db, cms
}
40 changes: 40 additions & 0 deletions types/module/testutil/codec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package testutil

import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/std"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/auth/tx"
)

type TestEncodingConfig struct {
InterfaceRegistry types.InterfaceRegistry
Codec codec.Codec
TxConfig client.TxConfig
Amino *codec.LegacyAmino
bm module.BasicManager
}

func MakeTestEncodingConfig(modules ...module.AppModuleBasic) TestEncodingConfig {
cdc := codec.NewLegacyAmino()
interfaceRegistry := types.NewInterfaceRegistry()
codec := codec.NewProtoCodec(interfaceRegistry)

encCfg := TestEncodingConfig{
InterfaceRegistry: interfaceRegistry,
Codec: codec,
TxConfig: tx.NewTxConfig(codec, tx.DefaultSignModes),
Amino: cdc,
}

mb := module.NewBasicManager(modules...)

std.RegisterLegacyAminoCodec(encCfg.Amino)
std.RegisterInterfaces(encCfg.InterfaceRegistry)
mb.RegisterLegacyAminoCodec(encCfg.Amino)
mb.RegisterInterfaces(encCfg.InterfaceRegistry)

return encCfg
}
55 changes: 31 additions & 24 deletions x/nft/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,23 @@ package keeper_test
import (
"testing"

"github.com/golang/mock/gomock"
"github.com/stretchr/testify/suite"
"github.com/tendermint/tendermint/libs/log"
tmtime "github.com/tendermint/tendermint/libs/time"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"

"github.com/cosmos/cosmos-sdk/baseapp"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/store"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/nft"
"github.com/cosmos/cosmos-sdk/x/nft/keeper"
"github.com/cosmos/cosmos-sdk/x/nft/testutil"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/nft/module"
nftTestutil "github.com/cosmos/cosmos-sdk/x/nft/testutil"
facundomedica marked this conversation as resolved.
Show resolved Hide resolved
)

const (
Expand All @@ -37,34 +41,37 @@ type TestSuite struct {
addrs []sdk.AccAddress
queryClient nft.QueryClient
nftKeeper keeper.Keeper

encCfg testutil.TestEncodingConfig
}

func (s *TestSuite) SetupTest() {
var (
interfaceRegistry codectypes.InterfaceRegistry
bankKeeper bankkeeper.Keeper
stakingKeeper *stakingkeeper.Keeper
nftKeeper keeper.Keeper
)

app, err := simtestutil.Setup(
testutil.AppConfig,
&interfaceRegistry,
&nftKeeper,
&bankKeeper,
&stakingKeeper,
)
// suite setup
s.addrs = simtestutil.CreateIncrementalAccounts(3)
s.encCfg = testutil.MakeTestEncodingConfig(module.AppModuleBasic{})

mkey := sdk.NewKVStoreKey(nft.StoreKey)
db := dbm.NewMemDB()
cms := store.NewCommitMultiStore(db)
cms.MountStoreWithDB(mkey, storetypes.StoreTypeIAVL, nil)
err := cms.LoadLatestVersion()
s.Require().NoError(err)

ctx := app.BaseApp.NewContext(false, tmproto.Header{})
ctx := sdk.NewContext(cms, tmproto.Header{}, false, log.NewNopLogger())
ctx = ctx.WithBlockHeader(tmproto.Header{Time: tmtime.Now()})
queryHelper := baseapp.NewQueryServerTestHelper(ctx, interfaceRegistry)

// gomock initializations
ctrl := gomock.NewController(s.T())
accountKeeper := nftTestutil.NewMockAccountKeeper(ctrl)
bankKeeper := nftTestutil.NewMockBankKeeper(ctrl)
accountKeeper.EXPECT().GetModuleAddress("nft").Return(s.addrs[0]).AnyTimes()

nftKeeper := keeper.NewKeeper(mkey, s.encCfg.Codec, accountKeeper, bankKeeper)
queryHelper := baseapp.NewQueryServerTestHelper(ctx, s.encCfg.InterfaceRegistry)
nft.RegisterQueryServer(queryHelper, nftKeeper)

s.ctx = ctx
s.queryClient = nft.NewQueryClient(queryHelper)
s.addrs = simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 3, sdk.NewInt(30000000))
s.nftKeeper = nftKeeper
s.queryClient = nft.NewQueryClient(queryHelper)
s.ctx = ctx
}

func TestTestSuite(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion x/nft/module/module.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package nft
package module

import (
"context"
Expand Down
129 changes: 77 additions & 52 deletions x/nft/simulation/operations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,72 +5,104 @@ import (
"testing"
"time"

"github.com/stretchr/testify/suite"

abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"

"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/testutil"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletypes "github.com/cosmos/cosmos-sdk/types/module"
moduleTestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/nft"
"github.com/cosmos/cosmos-sdk/x/nft/keeper"
nftkeeper "github.com/cosmos/cosmos-sdk/x/nft/keeper"
"github.com/cosmos/cosmos-sdk/x/nft/module"
"github.com/cosmos/cosmos-sdk/x/nft/simulation"
"github.com/cosmos/cosmos-sdk/x/nft/testutil"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
nftTestutil "github.com/cosmos/cosmos-sdk/x/nft/testutil"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/suite"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
tmtime "github.com/tendermint/tendermint/libs/time"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)

type SimTestSuite struct {
suite.Suite

ctx sdk.Context

app *runtime.App
codec codec.Codec
interfaceRegistry codectypes.InterfaceRegistry
accountKeeper authkeeper.AccountKeeper
bankKeeper bankkeeper.Keeper
stakingKeeper *stakingkeeper.Keeper
nftKeeper nftkeeper.Keeper
ctx sdk.Context
baseApp *baseapp.BaseApp
accountKeeper *nftTestutil.MockAccountKeeper
bankKeeper *nftTestutil.MockBankKeeper
nftKeeper nftkeeper.Keeper
encCfg moduleTestutil.TestEncodingConfig
}

func (suite *SimTestSuite) SetupTest() {
app, err := simtestutil.Setup(
testutil.AppConfig,
&suite.codec,
&suite.interfaceRegistry,
&suite.accountKeeper,
&suite.bankKeeper,
&suite.stakingKeeper,
&suite.nftKeeper,
key := sdk.NewKVStoreKey(nft.StoreKey)
// suite setup
addrs := simtestutil.CreateIncrementalAccounts(3)
suite.encCfg = moduleTestutil.MakeTestEncodingConfig(module.AppModuleBasic{})

// gomock initializations
ctrl := gomock.NewController(suite.T())
suite.accountKeeper = nftTestutil.NewMockAccountKeeper(ctrl)
suite.bankKeeper = nftTestutil.NewMockBankKeeper(ctrl)

suite.accountKeeper.EXPECT().GetModuleAddress(nft.ModuleName).Return(addrs[0]).AnyTimes()

ctx, db, cms := testutil.DefaultContextWithDB(key, sdk.NewTransientStoreKey("transient_test"))
suite.baseApp = baseapp.NewBaseApp(
"nft",
log.NewNopLogger(),
db,
suite.encCfg.TxConfig.TxDecoder(),
)
suite.Require().NoError(err)

suite.app = app
suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{})
suite.baseApp.SetCMS(cms)

suite.baseApp.SetInterfaceRegistry(suite.encCfg.InterfaceRegistry)
suite.ctx = ctx.WithBlockHeader(tmproto.Header{Time: tmtime.Now()})

suite.nftKeeper = keeper.NewKeeper(key, suite.encCfg.Codec, suite.accountKeeper, suite.bankKeeper)
queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, suite.encCfg.InterfaceRegistry)
nft.RegisterQueryServer(queryHelper, suite.nftKeeper)

cfg := moduletypes.NewConfigurator(suite.encCfg.Codec, suite.baseApp.MsgServiceRouter(), suite.baseApp.GRPCQueryRouter())

appModule := module.NewAppModule(suite.encCfg.Codec, suite.nftKeeper, suite.accountKeeper, suite.bankKeeper, suite.encCfg.InterfaceRegistry)
appModule.RegisterServices(cfg)
appModule.RegisterInterfaces(suite.encCfg.InterfaceRegistry)

}

func (suite *SimTestSuite) TestWeightedOperations() {
weightedOps := simulation.WeightedOperations(
suite.interfaceRegistry,
suite.encCfg.InterfaceRegistry,
make(simtypes.AppParams),
suite.codec,
suite.encCfg.Codec,
suite.accountKeeper,
suite.bankKeeper,
suite.nftKeeper,
)

// begin new block
suite.baseApp.BeginBlock(abci.RequestBeginBlock{
Header: tmproto.Header{
Height: suite.baseApp.LastBlockHeight() + 1,
AppHash: suite.baseApp.LastCommitID().Hash,
},
})

// setup 3 accounts
s := rand.NewSource(1)
r := rand.New(s)
accs := suite.getTestingAccounts(r, 3)

suite.accountKeeper.EXPECT().GetAccount(suite.ctx, accs[2].Address).Return(authtypes.NewBaseAccount(accs[2].Address, accs[2].PubKey, 0, 0)).Times(1)
suite.bankKeeper.EXPECT().SpendableCoins(suite.ctx, accs[2].Address).Return(sdk.Coins{sdk.NewInt64Coin("stake", 10)}).Times(1)

expected := []struct {
weight int
opMsgRoute string
Expand All @@ -80,7 +112,7 @@ func (suite *SimTestSuite) TestWeightedOperations() {
}

for i, w := range weightedOps {
operationMsg, _, err := w.Op()(r, suite.app.BaseApp, suite.ctx, accs, "")
operationMsg, _, err := w.Op()(r, suite.baseApp, suite.ctx, accs, "")
suite.Require().NoError(err)

// the following checks are very much dependent from the ordering of the output given
Expand All @@ -94,17 +126,6 @@ func (suite *SimTestSuite) TestWeightedOperations() {

func (suite *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Account {
accounts := simtypes.RandomAccounts(r, n)

initAmt := suite.stakingKeeper.TokensFromConsensusPower(suite.ctx, 200000)
initCoins := sdk.NewCoins(sdk.NewCoin("stake", initAmt))

// add coins to the accounts
for _, account := range accounts {
acc := suite.accountKeeper.NewAccountWithAddress(suite.ctx, account.Address)
suite.accountKeeper.SetAccount(suite.ctx, acc)
suite.Require().NoError(banktestutil.FundAccount(suite.bankKeeper, suite.ctx, account.Address, initCoins))
}

return accounts
}

Expand All @@ -115,22 +136,26 @@ func (suite *SimTestSuite) TestSimulateMsgSend() {
blockTime := time.Now().UTC()
ctx := suite.ctx.WithBlockTime(blockTime)

acc := authtypes.NewBaseAccount(accounts[0].Address, accounts[0].PubKey, 0, 0)
suite.accountKeeper.EXPECT().GetAccount(ctx, accounts[0].Address).Return(acc).Times(1)
suite.bankKeeper.EXPECT().SpendableCoins(ctx, accounts[0].Address).Return(sdk.Coins{sdk.NewInt64Coin("stake", 10)}).Times(1)

// begin new block
suite.app.BeginBlock(abci.RequestBeginBlock{
suite.baseApp.BeginBlock(abci.RequestBeginBlock{
Header: tmproto.Header{
Height: suite.app.LastBlockHeight() + 1,
AppHash: suite.app.LastCommitID().Hash,
Height: suite.baseApp.LastBlockHeight() + 1,
AppHash: suite.baseApp.LastCommitID().Hash,
},
})

// execute operation
registry := suite.interfaceRegistry
registry := suite.encCfg.InterfaceRegistry
op := simulation.SimulateMsgSend(codec.NewProtoCodec(registry), suite.accountKeeper, suite.bankKeeper, suite.nftKeeper)
operationMsg, futureOperations, err := op(r, suite.app.BaseApp, ctx, accounts, "")
operationMsg, futureOperations, err := op(r, suite.baseApp, ctx, accounts, "")
suite.Require().NoError(err)

var msg nft.MsgSend
suite.codec.UnmarshalJSON(operationMsg.Msg, &msg)
suite.encCfg.Codec.UnmarshalJSON(operationMsg.Msg, &msg)
suite.Require().True(operationMsg.OK)
suite.Require().Len(futureOperations, 0)
}
Expand Down
Loading