Skip to content

Commit

Permalink
refactor: remove dependency on simapp from baseapp tests (#12543)
Browse files Browse the repository at this point in the history
  • Loading branch information
kocubinski authored Jul 12, 2022
1 parent 23576d3 commit 9f95534
Show file tree
Hide file tree
Showing 4 changed files with 270 additions and 119 deletions.
114 changes: 78 additions & 36 deletions baseapp/block_gas_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,29 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"

bankmodulev1 "cosmossdk.io/api/cosmos/bank/module/v1"
"cosmossdk.io/depinject"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/runtime"
store "github.com/cosmos/cosmos-sdk/store/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
xauthsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
)

var blockMaxGas = uint64(simtestutil.DefaultConsensusParams.Block.MaxGas)
Expand All @@ -42,75 +51,108 @@ func TestBaseApp_BlockGas(t *testing.T) {
{"more than block gas meter", uint64(float64(blockMaxGas) * 1.2), false, true},
{"consume MaxUint64", math.MaxUint64, false, true},
{"consume MaxGasWanted", txtypes.MaxGasWanted, false, true},
{"consume block gas when paniced", 10, true, true},
{"consume block gas when panicked", 10, true, true},
}

for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
var app *simapp.SimApp
routerOpt := func(bapp *baseapp.BaseApp) {
route := (&testdata.TestMsg{}).Route()
bapp.Router().AddRoute(sdk.NewRoute(route, func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {
_, ok := msg.(*testdata.TestMsg)
if !ok {
return &sdk.Result{}, fmt.Errorf("Wrong Msg type, expected %T, got %T", (*testdata.TestMsg)(nil), msg)
var (
bankKeeper bankkeeper.Keeper
accountKeeper authkeeper.AccountKeeper
paramsKeeper paramskeeper.Keeper
stakingKeeper *stakingkeeper.Keeper
appBuilder *runtime.AppBuilder
txConfig client.TxConfig
cdc codec.Codec
pcdc codec.ProtoCodecMarshaler
interfaceRegistry codectypes.InterfaceRegistry
err error
)

appConfig := depinject.Configs(makeTestConfig(),
depinject.ProvideInModule(banktypes.ModuleName,
func(_ *bankmodulev1.Module, key *store.KVStoreKey) runtime.BaseAppOption {
return func(app *baseapp.BaseApp) {
route := (&testdata.TestMsg{}).Route()
app.Router().AddRoute(sdk.NewRoute(route, func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {
_, ok := msg.(*testdata.TestMsg)
if !ok {
return &sdk.Result{}, fmt.Errorf("Wrong Msg type, expected %T, got %T", (*testdata.TestMsg)(nil), msg)
}
ctx.KVStore(key).Set([]byte("ok"), []byte("ok"))
ctx.GasMeter().ConsumeGas(tc.gasToConsume, "TestMsg")
if tc.panicTx {
panic("panic in tx execution")
}
return &sdk.Result{}, nil
}))
}
ctx.KVStore(app.GetKey(banktypes.ModuleName)).Set([]byte("ok"), []byte("ok"))
ctx.GasMeter().ConsumeGas(tc.gasToConsume, "TestMsg")
if tc.panicTx {
panic("panic in tx execution")
}
return &sdk.Result{}, nil
}))
}

encCfg := simapp.MakeTestEncodingConfig()
app = simapp.NewSimApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, encCfg, simtestutil.EmptyAppOptions{}, routerOpt)
app.InterfaceRegistry().RegisterImplementations((*sdk.Msg)(nil),
err = depinject.Inject(appConfig,
&bankKeeper,
&accountKeeper,
&paramsKeeper,
&stakingKeeper,
&interfaceRegistry,
&txConfig,
&cdc,
&pcdc,
&appBuilder)
require.NoError(t, err)

bapp := appBuilder.Build(log.NewNopLogger(), dbm.NewMemDB(), nil)
err = bapp.Load(true)
require.NoError(t, err)

t.Run(tc.name, func(t *testing.T) {
interfaceRegistry.RegisterImplementations((*sdk.Msg)(nil),
&testdata.TestMsg{},
)
genState := simapp.GenesisStateWithSingleValidator(t, app)
genState := GenesisStateWithSingleValidator(t, cdc, appBuilder)
stateBytes, err := tmjson.MarshalIndent(genState, "", " ")
require.NoError(t, err)
app.InitChain(abci.RequestInitChain{
bapp.InitChain(abci.RequestInitChain{
Validators: []abci.ValidatorUpdate{},
ConsensusParams: simtestutil.DefaultConsensusParams,
AppStateBytes: stateBytes,
})

ctx := app.NewContext(false, tmproto.Header{})
ctx := bapp.NewContext(false, tmproto.Header{})

// tx fee
feeCoin := sdk.NewCoin("atom", sdk.NewInt(150))
feeAmount := sdk.NewCoins(feeCoin)

// test account and fund
priv1, _, addr1 := testdata.KeyTestPubAddr()
err = app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, feeAmount)
err = bankKeeper.MintCoins(ctx, minttypes.ModuleName, feeAmount)
require.NoError(t, err)
err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr1, feeAmount)
err = bankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr1, feeAmount)
require.NoError(t, err)
require.Equal(t, feeCoin.Amount, app.BankKeeper.GetBalance(ctx, addr1, feeCoin.Denom).Amount)
seq, _ := app.AccountKeeper.GetSequence(ctx, addr1)
require.Equal(t, feeCoin.Amount, bankKeeper.GetBalance(ctx, addr1, feeCoin.Denom).Amount)
seq := accountKeeper.GetAccount(ctx, addr1).GetSequence()
require.Equal(t, uint64(0), seq)

// msg and signatures
msg := testdata.NewTestMsg(addr1)

txBuilder := encCfg.TxConfig.NewTxBuilder()
txBuilder := txConfig.NewTxBuilder()

require.NoError(t, txBuilder.SetMsgs(msg))
txBuilder.SetFeeAmount(feeAmount)
txBuilder.SetGasLimit(txtypes.MaxGasWanted) // tx validation checks that gasLimit can't be bigger than this

privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{7}, []uint64{0}
_, txBytes, err := createTestTx(encCfg.TxConfig, txBuilder, privs, accNums, accSeqs, ctx.ChainID())
senderAccountNumber := accountKeeper.GetAccount(ctx, addr1).GetAccountNumber()
privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{senderAccountNumber}, []uint64{0}
_, txBytes, err := createTestTx(txConfig, txBuilder, privs, accNums, accSeqs, ctx.ChainID())
require.NoError(t, err)

app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: 1}})
rsp := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes})
bapp.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: 1}})
rsp := bapp.DeliverTx(abci.RequestDeliverTx{Tx: txBytes})

// check result
ctx = app.GetContextForDeliverTx(txBytes)
okValue := ctx.KVStore(app.GetKey(banktypes.ModuleName)).Get([]byte("ok"))
ctx = bapp.GetContextForDeliverTx(txBytes)
okValue := ctx.KVStore(bapp.UnsafeFindStoreKey(banktypes.ModuleName)).Get([]byte("ok"))

if tc.expErr {
if tc.panicTx {
Expand All @@ -132,9 +174,9 @@ func TestBaseApp_BlockGas(t *testing.T) {
}
require.Equal(t, expGasConsumed, ctx.BlockGasMeter().GasConsumed())
// tx fee is always deducted
require.Equal(t, int64(0), app.BankKeeper.GetBalance(ctx, addr1, feeCoin.Denom).Amount.Int64())
require.Equal(t, int64(0), bankKeeper.GetBalance(ctx, addr1, feeCoin.Denom).Amount.Int64())
// sender's sequence is always increased
seq, err = app.AccountKeeper.GetSequence(ctx, addr1)
seq = accountKeeper.GetAccount(ctx, addr1).GetSequence()
require.NoError(t, err)
require.Equal(t, uint64(1), seq)
})
Expand Down
11 changes: 6 additions & 5 deletions baseapp/grpcrouter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import (
"github.com/tendermint/tendermint/libs/log"
dbm "github.com/tendermint/tm-db"

"cosmossdk.io/depinject"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
"github.com/cosmos/cosmos-sdk/testutil/testdata_pulsar"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -53,11 +54,11 @@ func TestGRPCQueryRouter(t *testing.T) {

func TestRegisterQueryServiceTwice(t *testing.T) {
// Setup baseapp.
var appBuilder *runtime.AppBuilder
err := depinject.Inject(makeMinimalConfig(), &appBuilder)
require.NoError(t, err)
db := dbm.NewMemDB()
encCfg := simapp.MakeTestEncodingConfig()
app := baseapp.NewBaseApp("test", log.MustNewDefaultLogger("plain", "info", false), db, encCfg.TxConfig.TxDecoder())
app.SetInterfaceRegistry(encCfg.InterfaceRegistry)
testdata.RegisterInterfaces(encCfg.InterfaceRegistry)
app := appBuilder.Build(log.MustNewDefaultLogger("plain", "info", false), db, nil)

// First time registering service shouldn't panic.
require.NotPanics(t, func() {
Expand Down
71 changes: 47 additions & 24 deletions baseapp/msg_service_router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,37 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"

"github.com/cosmos/cosmos-sdk/baseapp"
"cosmossdk.io/depinject"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/simapp"
"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/testdata"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
)

func TestRegisterMsgService(t *testing.T) {
db := dbm.NewMemDB()
// Setup baseapp.
var (
appBuilder *runtime.AppBuilder
registry codectypes.InterfaceRegistry
)
err := depinject.Inject(makeMinimalConfig(), &appBuilder, &registry)
require.NoError(t, err)
app := appBuilder.Build(log.MustNewDefaultLogger("plain", "info", false), dbm.NewMemDB(), nil)

// Create an encoding config that doesn't register testdata Msg services.
encCfg := simapp.MakeTestEncodingConfig()
app := baseapp.NewBaseApp("test", log.MustNewDefaultLogger("plain", "info", false), db, encCfg.TxConfig.TxDecoder())
app.SetInterfaceRegistry(encCfg.InterfaceRegistry)
require.Panics(t, func() {
testdata.RegisterMsgServer(
app.MsgServiceRouter(),
testdata.MsgServerImpl{},
)
})

// Register testdata Msg services, and rerun `RegisterService`.
testdata.RegisterInterfaces(encCfg.InterfaceRegistry)
// Register testdata Msg services, and rerun `RegisterMsgService`.
testdata.RegisterInterfaces(registry)

require.NotPanics(t, func() {
testdata.RegisterMsgServer(
app.MsgServiceRouter(),
Expand All @@ -43,11 +50,15 @@ func TestRegisterMsgService(t *testing.T) {

func TestRegisterMsgServiceTwice(t *testing.T) {
// Setup baseapp.
var (
appBuilder *runtime.AppBuilder
registry codectypes.InterfaceRegistry
)
err := depinject.Inject(makeMinimalConfig(), &appBuilder, &registry)
require.NoError(t, err)
db := dbm.NewMemDB()
encCfg := simapp.MakeTestEncodingConfig()
app := baseapp.NewBaseApp("test", log.MustNewDefaultLogger("plain", "info", false), db, encCfg.TxConfig.TxDecoder())
app.SetInterfaceRegistry(encCfg.InterfaceRegistry)
testdata.RegisterInterfaces(encCfg.InterfaceRegistry)
app := appBuilder.Build(log.MustNewDefaultLogger("plain", "info", false), db, nil)
testdata.RegisterInterfaces(registry)

// First time registering service shouldn't panic.
require.NotPanics(t, func() {
Expand All @@ -68,30 +79,42 @@ func TestRegisterMsgServiceTwice(t *testing.T) {

func TestMsgService(t *testing.T) {
priv, _, _ := testdata.KeyTestPubAddr()
encCfg := simapp.MakeTestEncodingConfig()
testdata.RegisterInterfaces(encCfg.InterfaceRegistry)
db := dbm.NewMemDB()
app := baseapp.NewBaseApp("test", log.MustNewDefaultLogger("plain", "info", false), db, encCfg.TxConfig.TxDecoder())
app.SetInterfaceRegistry(encCfg.InterfaceRegistry)

var (
appBuilder *runtime.AppBuilder
cdc codec.ProtoCodecMarshaler
interfaceRegistry codectypes.InterfaceRegistry
)
err := depinject.Inject(makeMinimalConfig(), &appBuilder, &cdc, &interfaceRegistry)
require.NoError(t, err)
app := appBuilder.Build(log.NewNopLogger(), dbm.NewMemDB(), nil)

// patch in TxConfig instead of using an output from x/auth/tx
txConfig := authtx.NewTxConfig(cdc, authtx.DefaultSignModes)
// set the TxDecoder in the BaseApp for minimal tx simulations
app.SetTxDecoder(txConfig.TxDecoder())

testdata.RegisterInterfaces(interfaceRegistry)
testdata.RegisterMsgServer(
app.MsgServiceRouter(),
testdata.MsgServerImpl{},
)
_ = app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: 1}})

msg := testdata.MsgCreateDog{Dog: &testdata.Dog{Name: "Spot"}}
txBuilder := encCfg.TxConfig.NewTxBuilder()

txBuilder := txConfig.NewTxBuilder()
txBuilder.SetFeeAmount(testdata.NewTestFeeAmount())
txBuilder.SetGasLimit(testdata.NewTestGasLimit())
err := txBuilder.SetMsgs(&msg)
err = txBuilder.SetMsgs(&msg)
require.NoError(t, err)

// First round: we gather all the signer infos. We use the "set empty
// signature" hack to do that.
sigV2 := signing.SignatureV2{
PubKey: priv.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: encCfg.TxConfig.SignModeHandler().DefaultMode(),
SignMode: txConfig.SignModeHandler().DefaultMode(),
Signature: nil,
},
Sequence: 0,
Expand All @@ -107,14 +130,14 @@ func TestMsgService(t *testing.T) {
Sequence: 0,
}
sigV2, err = tx.SignWithPrivKey(
encCfg.TxConfig.SignModeHandler().DefaultMode(), signerData,
txBuilder, priv, encCfg.TxConfig, 0)
txConfig.SignModeHandler().DefaultMode(), signerData,
txBuilder, priv, txConfig, 0)
require.NoError(t, err)
err = txBuilder.SetSignatures(sigV2)
require.NoError(t, err)

// Send the tx to the app
txBytes, err := encCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
txBytes, err := txConfig.TxEncoder()(txBuilder.GetTx())
require.NoError(t, err)
res := app.DeliverTx(abci.RequestDeliverTx{Tx: txBytes})
require.Equal(t, abci.CodeTypeOK, res.Code, "res=%+v", res)
Expand Down
Loading

0 comments on commit 9f95534

Please sign in to comment.