From 53dff03a3635f6de6193b1743b3ec8d0d556f5b5 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Mon, 25 Nov 2024 13:02:50 +0100 Subject: [PATCH] fix(testutil/integration): use only one context in integration test framework (backport #22616) (#22642) Co-authored-by: Julien Robert --- CHANGELOG.md | 8 +- tests/integration/accounts/fixture_test.go | 22 ++---- .../accounts_retro_compatibility_test.go | 22 +++--- tests/integration/auth/keeper/fixture_test.go | 10 +-- .../auth/keeper/migrate_x_accounts_test.go | 22 +++--- .../auth/keeper/msg_server_test.go | 2 +- .../bank/keeper/deterministic_test.go | 8 +- .../distribution/keeper/msg_server_test.go | 41 ++++------ .../evidence/keeper/infraction_test.go | 8 +- tests/integration/example/example_test.go | 8 -- .../integration/gov/keeper/grpc_query_test.go | 2 - tests/integration/gov/keeper/keeper_test.go | 16 +--- .../slashing/keeper/keeper_test.go | 13 +--- .../integration/staking/keeper/common_test.go | 13 ++-- .../staking/keeper/deterministic_test.go | 8 +- testutil/integration/helpers.go | 22 ++++++ testutil/integration/router.go | 76 +++++++++---------- x/bank/keeper/send.go | 2 +- 18 files changed, 126 insertions(+), 177 deletions(-) create mode 100644 testutil/integration/helpers.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ef6c57acfd5..36cc41858ead 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,7 +44,13 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i ### Improvements -### Bug Fixes +* (testutil/integration) [#22616](https://github.com/cosmos/cosmos-sdk/pull/22616) Remove double context in integration tests v1. + * Use `integrationApp.Context()` instead of creating a context prior. + +### Bug Fixes + +* (sims) [#21906](https://github.com/cosmos/cosmos-sdk/pull/21906) Skip sims test when running dry on validators +* (cli) [#21919](https://github.com/cosmos/cosmos-sdk/pull/21919) Query address-by-acc-num by account_id instead of id. ### API Breaking Changes diff --git a/tests/integration/accounts/fixture_test.go b/tests/integration/accounts/fixture_test.go index 63c301bbf4df..1f4522f866a5 100644 --- a/tests/integration/accounts/fixture_test.go +++ b/tests/integration/accounts/fixture_test.go @@ -60,9 +60,7 @@ type fixture struct { t *testing.T app *integration.App - cdc codec.Codec - ctx sdk.Context authKeeper authkeeper.AccountKeeper accountsKeeper accounts.Keeper @@ -82,7 +80,7 @@ func (f fixture) runBundle(txBytes ...[]byte) *accountsv1.MsgExecuteBundleRespon msgSrv := accounts.NewMsgServer(f.accountsKeeper) - resp, err := msgSrv.ExecuteBundle(f.ctx, &accountsv1.MsgExecuteBundle{ + resp, err := msgSrv.ExecuteBundle(f.app.Context(), &accountsv1.MsgExecuteBundle{ Bundler: f.bundler, Txs: txBytes, }) @@ -93,16 +91,16 @@ func (f fixture) runBundle(txBytes ...[]byte) *accountsv1.MsgExecuteBundleRespon func (f fixture) mint(address []byte, coins ...sdk.Coin) { f.t.Helper() for _, coin := range coins { - err := f.bankKeeper.MintCoins(f.ctx, minttypes.ModuleName, sdk.NewCoins(coin)) + err := f.bankKeeper.MintCoins(f.app.Context(), minttypes.ModuleName, sdk.NewCoins(coin)) require.NoError(f.t, err) - err = f.bankKeeper.SendCoinsFromModuleToAccount(f.ctx, minttypes.ModuleName, address, sdk.NewCoins(coin)) + err = f.bankKeeper.SendCoinsFromModuleToAccount(f.app.Context(), minttypes.ModuleName, address, sdk.NewCoins(coin)) require.NoError(f.t, err) } } func (f fixture) balance(recipient, denom string) sdk.Coin { f.t.Helper() - balances, err := f.bankKeeper.Balance(f.ctx, &banktypes.QueryBalanceRequest{ + balances, err := f.bankKeeper.Balance(f.app.Context(), &banktypes.QueryBalanceRequest{ Address: recipient, Denom: denom, }) @@ -119,10 +117,6 @@ func initFixture(t *testing.T, f func(ctx context.Context, msg *account_abstract cdc := encodingCfg.Codec logger := log.NewTestLogger(t) - cms := integration.CreateMultiStore(keys, logger) - - newCtx := sdk.NewContext(cms, true, logger) - router := baseapp.NewMsgServiceRouter() queryRouter := baseapp.NewGRPCQueryRouter() @@ -169,14 +163,11 @@ func initFixture(t *testing.T, f func(ctx context.Context, msg *account_abstract authority.String(), ) - params := banktypes.DefaultParams() - require.NoError(t, bankKeeper.SetParams(newCtx, params)) - accountsModule := accounts.NewAppModule(cdc, accountsKeeper) authModule := auth.NewAppModule(cdc, authKeeper, accountsKeeper, authsims.RandomGenesisAccounts, nil) bankModule := bank.NewAppModule(cdc, bankKeeper, authKeeper) - integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ @@ -194,14 +185,13 @@ func initFixture(t *testing.T, f func(ctx context.Context, msg *account_abstract banktypes.RegisterMsgServer(router, bankkeeper.NewMsgServerImpl(bankKeeper)) // init account - _, addr, err := accountsKeeper.Init(newCtx, "mock", []byte("system"), &gogotypes.Empty{}, nil) + _, addr, err := accountsKeeper.Init(integrationApp.Context(), "mock", []byte("system"), &gogotypes.Empty{}, nil) require.NoError(t, err) fixture := &fixture{ t: t, app: integrationApp, cdc: cdc, - ctx: newCtx, authKeeper: authKeeper, accountsKeeper: accountsKeeper, bankKeeper: bankKeeper, diff --git a/tests/integration/auth/keeper/accounts_retro_compatibility_test.go b/tests/integration/auth/keeper/accounts_retro_compatibility_test.go index eb27f4ce36b9..8b388b41a70d 100644 --- a/tests/integration/auth/keeper/accounts_retro_compatibility_test.go +++ b/tests/integration/auth/keeper/accounts_retro_compatibility_test.go @@ -74,7 +74,7 @@ func TestAuthToAccountsGRPCCompat(t *testing.T) { // init three accounts for n, a := range accs { - _, addr, err := f.accountsKeeper.Init(f.ctx, n, []byte("me"), &gogotypes.Empty{}, nil) + _, addr, err := f.accountsKeeper.Init(f.app.Context(), n, []byte("me"), &gogotypes.Empty{}, nil) require.NoError(t, err) a.(*mockRetroCompatAccount).address = addr } @@ -82,13 +82,13 @@ func TestAuthToAccountsGRPCCompat(t *testing.T) { qs := authkeeper.NewQueryServer(f.authKeeper) t.Run("account supports info and account query", func(t *testing.T) { - infoResp, err := qs.AccountInfo(f.ctx, &authtypes.QueryAccountInfoRequest{ + infoResp, err := qs.AccountInfo(f.app.Context(), &authtypes.QueryAccountInfoRequest{ Address: f.mustAddr(valid.address), }) require.NoError(t, err) require.Equal(t, infoResp.Info, valid.retroCompat.Base) - accountResp, err := qs.Account(f.ctx, &authtypes.QueryAccountRequest{ + accountResp, err := qs.Account(f.app.Context(), &authtypes.QueryAccountRequest{ Address: f.mustAddr(noInfo.address), }) require.NoError(t, err) @@ -96,13 +96,13 @@ func TestAuthToAccountsGRPCCompat(t *testing.T) { }) t.Run("account only supports account query, not info", func(t *testing.T) { - _, err := qs.AccountInfo(f.ctx, &authtypes.QueryAccountInfoRequest{ + _, err := qs.AccountInfo(f.app.Context(), &authtypes.QueryAccountInfoRequest{ Address: f.mustAddr(noInfo.address), }) require.Error(t, err) require.Equal(t, status.Code(err), codes.NotFound) - resp, err := qs.Account(f.ctx, &authtypes.QueryAccountRequest{ + resp, err := qs.Account(f.app.Context(), &authtypes.QueryAccountRequest{ Address: f.mustAddr(noInfo.address), }) require.NoError(t, err) @@ -110,13 +110,13 @@ func TestAuthToAccountsGRPCCompat(t *testing.T) { }) t.Run("account does not support any retro compat", func(t *testing.T) { - _, err := qs.AccountInfo(f.ctx, &authtypes.QueryAccountInfoRequest{ + _, err := qs.AccountInfo(f.app.Context(), &authtypes.QueryAccountInfoRequest{ Address: f.mustAddr(noImplement.address), }) require.Error(t, err) require.Equal(t, status.Code(err), codes.NotFound) - _, err = qs.Account(f.ctx, &authtypes.QueryAccountRequest{ + _, err = qs.Account(f.app.Context(), &authtypes.QueryAccountRequest{ Address: f.mustAddr(noImplement.address), }) @@ -132,22 +132,22 @@ func TestAccountsBaseAccountRetroCompat(t *testing.T) { require.NoError(t, err) // we init two accounts to have account num not be zero. - _, _, err = f.accountsKeeper.Init(f.ctx, "base", []byte("me"), &basev1.MsgInit{PubKey: anyPk}, nil) + _, _, err = f.accountsKeeper.Init(f.app.Context(), "base", []byte("me"), &basev1.MsgInit{PubKey: anyPk}, nil) require.NoError(t, err) - _, addr, err := f.accountsKeeper.Init(f.ctx, "base", []byte("me"), &basev1.MsgInit{PubKey: anyPk}, nil) + _, addr, err := f.accountsKeeper.Init(f.app.Context(), "base", []byte("me"), &basev1.MsgInit{PubKey: anyPk}, nil) require.NoError(t, err) // try to query it via auth qs := authkeeper.NewQueryServer(f.authKeeper) - r, err := qs.Account(f.ctx, &authtypes.QueryAccountRequest{ + r, err := qs.Account(f.app.Context(), &authtypes.QueryAccountRequest{ Address: f.mustAddr(addr), }) require.NoError(t, err) require.NotNil(t, r.Account) - info, err := qs.AccountInfo(f.ctx, &authtypes.QueryAccountInfoRequest{ + info, err := qs.AccountInfo(f.app.Context(), &authtypes.QueryAccountInfoRequest{ Address: f.mustAddr(addr), }) require.NoError(t, err) diff --git a/tests/integration/auth/keeper/fixture_test.go b/tests/integration/auth/keeper/fixture_test.go index f8a2d10ba871..d32d1d0787bf 100644 --- a/tests/integration/auth/keeper/fixture_test.go +++ b/tests/integration/auth/keeper/fixture_test.go @@ -36,7 +36,6 @@ type fixture struct { app *integration.App cdc codec.Codec - ctx sdk.Context authKeeper authkeeper.AccountKeeper accountsKeeper accounts.Keeper @@ -57,9 +56,6 @@ func initFixture(t *testing.T, extraAccs map[string]accountstd.Interface) *fixtu cdc := encodingCfg.Codec logger := log.NewTestLogger(t) - cms := integration.CreateMultiStore(keys, logger) - - newCtx := sdk.NewContext(cms, true, logger) router := baseapp.NewMsgServiceRouter() queryRouter := baseapp.NewGRPCQueryRouter() @@ -109,14 +105,11 @@ func initFixture(t *testing.T, extraAccs map[string]accountstd.Interface) *fixtu authority.String(), ) - params := banktypes.DefaultParams() - assert.NilError(t, bankKeeper.SetParams(newCtx, params)) - accountsModule := accounts.NewAppModule(cdc, accountsKeeper) authModule := auth.NewAppModule(cdc, authKeeper, accountsKeeper, authsims.RandomGenesisAccounts, nil) bankModule := bank.NewAppModule(cdc, bankKeeper, authKeeper) - integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ @@ -136,7 +129,6 @@ func initFixture(t *testing.T, extraAccs map[string]accountstd.Interface) *fixtu return &fixture{ app: integrationApp, cdc: cdc, - ctx: newCtx, accountsKeeper: accountsKeeper, authKeeper: authKeeper, bankKeeper: bankKeeper, diff --git a/tests/integration/auth/keeper/migrate_x_accounts_test.go b/tests/integration/auth/keeper/migrate_x_accounts_test.go index 452a7e1d9666..b7da225c84e6 100644 --- a/tests/integration/auth/keeper/migrate_x_accounts_test.go +++ b/tests/integration/auth/keeper/migrate_x_accounts_test.go @@ -29,20 +29,20 @@ func TestMigrateToAccounts(t *testing.T) { Name: "cookies", Permissions: nil, } - updatedMod := f.authKeeper.NewAccount(f.ctx, modAcc) - f.authKeeper.SetAccount(f.ctx, updatedMod) + updatedMod := f.authKeeper.NewAccount(f.app.Context(), modAcc) + f.authKeeper.SetAccount(f.app.Context(), updatedMod) // create account msgSrv := authkeeper.NewMsgServerImpl(f.authKeeper) privKey := secp256k1.GenPrivKey() addr := sdk.AccAddress(privKey.PubKey().Address()) - acc := f.authKeeper.NewAccountWithAddress(f.ctx, addr) + acc := f.authKeeper.NewAccountWithAddress(f.app.Context(), addr) require.NoError(t, acc.SetPubKey(privKey.PubKey())) - f.authKeeper.SetAccount(f.ctx, acc) + f.authKeeper.SetAccount(f.app.Context(), acc) t.Run("account does not exist", func(t *testing.T) { - resp, err := msgSrv.MigrateAccount(f.ctx, &authtypes.MsgMigrateAccount{ + resp, err := msgSrv.MigrateAccount(f.app.Context(), &authtypes.MsgMigrateAccount{ Signer: f.mustAddr([]byte("notexist")), AccountType: "base", AccountInitMsg: nil, @@ -52,7 +52,7 @@ func TestMigrateToAccounts(t *testing.T) { }) t.Run("invalid account type", func(t *testing.T) { - resp, err := msgSrv.MigrateAccount(f.ctx, &authtypes.MsgMigrateAccount{ + resp, err := msgSrv.MigrateAccount(f.app.Context(), &authtypes.MsgMigrateAccount{ Signer: f.mustAddr(updatedMod.GetAddress()), AccountType: "base", AccountInitMsg: nil, @@ -73,7 +73,7 @@ func TestMigrateToAccounts(t *testing.T) { initMsgAny, err := codectypes.NewAnyWithValue(migrateMsg) require.NoError(t, err) - resp, err := msgSrv.MigrateAccount(f.ctx, &authtypes.MsgMigrateAccount{ + resp, err := msgSrv.MigrateAccount(f.app.Context(), &authtypes.MsgMigrateAccount{ Signer: f.mustAddr(addr), AccountType: "base", AccountInitMsg: initMsgAny, @@ -85,15 +85,15 @@ func TestMigrateToAccounts(t *testing.T) { require.NotNil(t, resp.InitResponse.Value) // check the account was removed from x/auth and added to x/accounts - require.Nil(t, f.authKeeper.GetAccount(f.ctx, addr)) - require.True(t, f.accountsKeeper.IsAccountsModuleAccount(f.ctx, addr)) + require.Nil(t, f.authKeeper.GetAccount(f.app.Context(), addr)) + require.True(t, f.accountsKeeper.IsAccountsModuleAccount(f.app.Context(), addr)) // check the init information is correctly propagated. - seq, err := f.accountsKeeper.Query(f.ctx, addr, &basev1.QuerySequence{}) + seq, err := f.accountsKeeper.Query(f.app.Context(), addr, &basev1.QuerySequence{}) require.NoError(t, err) require.Equal(t, migrateMsg.InitSequence, seq.(*basev1.QuerySequenceResponse).Sequence) - pkResp, err := f.accountsKeeper.Query(f.ctx, addr, &basev1.QueryPubKey{}) + pkResp, err := f.accountsKeeper.Query(f.app.Context(), addr, &basev1.QueryPubKey{}) require.NoError(t, err) require.Equal(t, migrateMsg.PubKey, pkResp.(*basev1.QueryPubKeyResponse).PubKey) }) diff --git a/tests/integration/auth/keeper/msg_server_test.go b/tests/integration/auth/keeper/msg_server_test.go index 076f33620508..d42468c9c674 100644 --- a/tests/integration/auth/keeper/msg_server_test.go +++ b/tests/integration/auth/keeper/msg_server_test.go @@ -40,7 +40,7 @@ func TestAsyncExec(t *testing.T) { addrs := simtestutil.CreateIncrementalAccounts(2) coins := sdk.NewCoins(sdk.NewCoin("stake", sdkmath.NewInt(10))) - assert.NilError(t, testutil.FundAccount(f.ctx, f.bankKeeper, addrs[0], sdk.NewCoins(sdk.NewInt64Coin("stake", 500)))) + assert.NilError(t, testutil.FundAccount(f.app.Context(), f.bankKeeper, addrs[0], sdk.NewCoins(sdk.NewInt64Coin("stake", 500)))) msg := &banktypes.MsgSend{ FromAddress: addrs[0].String(), diff --git a/tests/integration/bank/keeper/deterministic_test.go b/tests/integration/bank/keeper/deterministic_test.go index 7233a4d0ee86..fb5bd8b170c2 100644 --- a/tests/integration/bank/keeper/deterministic_test.go +++ b/tests/integration/bank/keeper/deterministic_test.go @@ -72,10 +72,6 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture { cdc := encodingCfg.Codec logger := log.NewTestLogger(t) - cms := integration.CreateMultiStore(keys, logger) - - newCtx := sdk.NewContext(cms, true, logger) - authority := authtypes.NewModuleAddress("gov") maccPerms := map[string][]string{ @@ -114,12 +110,10 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture { authority.String(), ) - assert.NilError(t, bankKeeper.SetParams(newCtx, banktypes.DefaultParams())) - authModule := auth.NewAppModule(cdc, accountKeeper, acctsModKeeper, authsims.RandomGenesisAccounts, nil) bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) - integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/distribution/keeper/msg_server_test.go index b942275d61bc..39879d8c3f6e 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -81,10 +81,6 @@ func initFixture(t *testing.T) *fixture { cdc := encodingCfg.Codec logger := log.NewTestLogger(t) - cms := integration.CreateMultiStore(keys, logger) - - newCtx := sdk.NewContext(cms, true, logger) - authority := authtypes.NewModuleAddress("gov") maccPerms := map[string][]string{ @@ -128,15 +124,12 @@ func initFixture(t *testing.T) *fixture { authority.String(), ) - assert.NilError(t, bankKeeper.SetParams(newCtx, banktypes.DefaultParams())) - msgRouter := baseapp.NewMsgServiceRouter() grpcRouter := baseapp.NewGRPCQueryRouter() cometService := runtime.NewContextAwareCometInfoService() consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensustypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(grpcRouter), runtime.EnvWithMsgRouterService(msgRouter)), authtypes.NewModuleAddress("gov").String()) stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(grpcRouter), runtime.EnvWithMsgRouterService(msgRouter)), accountKeeper, bankKeeper, consensusParamsKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), cometService) - require.NoError(t, stakingKeeper.Params.Set(newCtx, stakingtypes.DefaultParams())) poolKeeper := poolkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[pooltypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String()) @@ -155,23 +148,7 @@ func initFixture(t *testing.T) *fixture { valAddr := sdk.ValAddress(addr) valConsAddr := sdk.ConsAddress(valConsPk0.Address()) - // set proposer and vote infos - ctx := newCtx.WithProposer(valConsAddr).WithCometInfo(comet.Info{ - LastCommit: comet.CommitInfo{ - Votes: []comet.VoteInfo{ - { - Validator: comet.Validator{ - Address: valAddr, - Power: 100, - }, - BlockIDFlag: comet.BlockIDFlagCommit, - }, - }, - }, - ProposerAddress: valConsAddr, - }) - - integrationApp := integration.NewIntegrationApp(ctx, logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ @@ -186,7 +163,21 @@ func initFixture(t *testing.T) *fixture { grpcRouter, ) - sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context()) + // set proposer and vote infos + sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context()).WithProposer(valConsAddr).WithCometInfo(comet.Info{ + LastCommit: comet.CommitInfo{ + Votes: []comet.VoteInfo{ + { + Validator: comet.Validator{ + Address: valAddr, + Power: 100, + }, + BlockIDFlag: comet.BlockIDFlagCommit, + }, + }, + }, + ProposerAddress: valConsAddr, + }) // Register MsgServer and QueryServer distrtypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), distrkeeper.NewMsgServerImpl(distrKeeper)) diff --git a/tests/integration/evidence/keeper/infraction_test.go b/tests/integration/evidence/keeper/infraction_test.go index 745407688cb2..a739456fd631 100644 --- a/tests/integration/evidence/keeper/infraction_test.go +++ b/tests/integration/evidence/keeper/infraction_test.go @@ -99,10 +99,6 @@ func initFixture(tb testing.TB) *fixture { grpcQueryRouter := baseapp.NewGRPCQueryRouter() logger := log.NewTestLogger(tb) - cms := integration.CreateMultiStore(keys, logger) - - newCtx := sdk.NewContext(cms, true, logger) - authority := authtypes.NewModuleAddress("gov") // gomock initializations @@ -144,8 +140,6 @@ func initFixture(tb testing.TB) *fixture { authority.String(), ) - assert.NilError(tb, bankKeeper.SetParams(newCtx, banktypes.DefaultParams())) - consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(grpcQueryRouter), runtime.EnvWithMsgRouterService(msgRouter)), authtypes.NewModuleAddress("gov").String()) stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(grpcQueryRouter), runtime.EnvWithMsgRouterService(msgRouter)), accountKeeper, bankKeeper, consensusParamsKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), runtime.NewContextAwareCometInfoService()) @@ -166,7 +160,7 @@ func initFixture(tb testing.TB) *fixture { evidenceModule := evidence.NewAppModule(cdc, *evidenceKeeper, cometInfoService) consensusModule := consensus.NewAppModule(cdc, consensusParamsKeeper) - integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ diff --git a/tests/integration/example/example_test.go b/tests/integration/example/example_test.go index 02b22a1a54fa..c3a26297649e 100644 --- a/tests/integration/example/example_test.go +++ b/tests/integration/example/example_test.go @@ -44,9 +44,6 @@ func Example() { // replace the logger by testing values in a real test case (e.g. log.NewTestLogger(t)) logger := log.NewNopLogger() - cms := integration.CreateMultiStore(keys, logger) - newCtx := sdk.NewContext(cms, true, logger) - // gomock initializations ctrl := gomock.NewController(&testing.T{}) acctsModKeeper := authtestutil.NewMockAccountsModKeeper(ctrl) @@ -78,7 +75,6 @@ func Example() { // create the application and register all the modules from the previous step integrationApp := integration.NewIntegrationApp( - newCtx, logger, keys, encodingCfg.Codec, @@ -148,9 +144,6 @@ func Example_oneModule() { // replace the logger by testing values in a real test case (e.g. log.NewTestLogger(t)) logger := log.NewLogger(io.Discard) - cms := integration.CreateMultiStore(keys, logger) - newCtx := sdk.NewContext(cms, true, logger) - // gomock initializations ctrl := gomock.NewController(&testing.T{}) acctsModKeeper := authtestutil.NewMockAccountsModKeeper(ctrl) @@ -177,7 +170,6 @@ func Example_oneModule() { // create the application and register all the modules from the previous step integrationApp := integration.NewIntegrationApp( - newCtx, logger, keys, encodingCfg.Codec, diff --git a/tests/integration/gov/keeper/grpc_query_test.go b/tests/integration/gov/keeper/grpc_query_test.go index edd583c4dd9e..44fc1ccc103e 100644 --- a/tests/integration/gov/keeper/grpc_query_test.go +++ b/tests/integration/gov/keeper/grpc_query_test.go @@ -16,9 +16,7 @@ func TestLegacyGRPCQueryTally(t *testing.T) { t.Parallel() f := initFixture(t) - ctx, queryClient := f.ctx, f.legacyQueryClient - addrs, _ := createValidators(t, f, []int64{5, 5, 5}) var ( diff --git a/tests/integration/gov/keeper/keeper_test.go b/tests/integration/gov/keeper/keeper_test.go index 314a5ed5909f..4722bc9c5760 100644 --- a/tests/integration/gov/keeper/keeper_test.go +++ b/tests/integration/gov/keeper/keeper_test.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/golang/mock/gomock" - "gotest.tools/v3/assert" "cosmossdk.io/core/appmodule" "cosmossdk.io/log" @@ -63,10 +62,6 @@ func initFixture(tb testing.TB) *fixture { cdc := encodingCfg.Codec logger := log.NewTestLogger(tb) - cms := integration.CreateMultiStore(keys, logger) - - newCtx := sdk.NewContext(cms, true, logger) - authority := authtypes.NewModuleAddress(types.ModuleName) maccPerms := map[string][]string{ @@ -111,8 +106,6 @@ func initFixture(tb testing.TB) *fixture { authority.String(), ) - assert.NilError(tb, bankKeeper.SetParams(newCtx, banktypes.DefaultParams())) - router := baseapp.NewMsgServiceRouter() queryRouter := baseapp.NewGRPCQueryRouter() consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(router)), authtypes.NewModuleAddress("gov").String()) @@ -121,10 +114,6 @@ func initFixture(tb testing.TB) *fixture { poolKeeper := poolkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[pooltypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, authority.String()) - // set default staking params - err := stakingKeeper.Params.Set(newCtx, stakingtypes.DefaultParams()) - assert.NilError(tb, err) - // Create MsgServiceRouter, but don't populate it before creating the gov // keeper. router.SetInterfaceRegistry(cdc.InterfaceRegistry()) @@ -140,12 +129,9 @@ func initFixture(tb testing.TB) *fixture { keeper.DefaultConfig(), authority.String(), ) - assert.NilError(tb, govKeeper.ProposalID.Set(newCtx, 1)) govRouter := v1beta1.NewRouter() govRouter.AddRoute(types.RouterKey, v1beta1.ProposalHandler) govKeeper.SetLegacyRouter(govRouter) - err = govKeeper.Params.Set(newCtx, v1.DefaultParams()) - assert.NilError(tb, err) authModule := auth.NewAppModule(cdc, accountKeeper, acctsModKeeper, authsims.RandomGenesisAccounts, nil) bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper) @@ -153,7 +139,7 @@ func initFixture(tb testing.TB) *fixture { govModule := gov.NewAppModule(cdc, govKeeper, accountKeeper, bankKeeper, poolKeeper) consensusModule := consensus.NewAppModule(cdc, consensusParamsKeeper) - integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index e961dc68233d..c70c7fa76b2d 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -67,11 +67,6 @@ func initFixture(tb testing.TB) *fixture { encodingCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, auth.AppModule{}) cdc := encodingCfg.Codec - logger := log.NewTestLogger(tb) - cms := integration.CreateMultiStore(keys, logger) - - newCtx := sdk.NewContext(cms, true, logger) - authority := authtypes.NewModuleAddress("gov") maccPerms := map[string][]string{ @@ -115,8 +110,6 @@ func initFixture(tb testing.TB) *fixture { authority.String(), ) - assert.NilError(tb, bankKeeper.SetParams(newCtx, banktypes.DefaultParams())) - cometInfoService := runtime.NewContextAwareCometInfoService() consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensustypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(msgRouter)), authtypes.NewModuleAddress("gov").String()) @@ -130,7 +123,7 @@ func initFixture(tb testing.TB) *fixture { slashingModule := slashing.NewAppModule(cdc, slashingKeeper, accountKeeper, bankKeeper, stakingKeeper, cdc.InterfaceRegistry(), cometInfoService) consensusModule := consensus.NewAppModule(cdc, consensusParamsKeeper) - integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(log.NewNopLogger(), keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ @@ -150,10 +143,8 @@ func initFixture(tb testing.TB) *fixture { slashingtypes.RegisterQueryServer(integrationApp.QueryHelper(), slashingkeeper.NewQuerier(slashingKeeper)) // set default staking params - err := stakingKeeper.Params.Set(sdkCtx, stakingtypes.DefaultParams()) - assert.NilError(tb, err) // TestParams set the SignedBlocksWindow to 1000 and MaxMissedBlocksPerWindow to 500 - err = slashingKeeper.Params.Set(sdkCtx, testutil.TestParams()) + err := slashingKeeper.Params.Set(sdkCtx, testutil.TestParams()) assert.NilError(tb, err) addrDels := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, sdkCtx, 6, stakingKeeper.TokensFromConsensusPower(sdkCtx, 200)) valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels) diff --git a/tests/integration/staking/keeper/common_test.go b/tests/integration/staking/keeper/common_test.go index e3963efb7bb7..0830f08e6433 100644 --- a/tests/integration/staking/keeper/common_test.go +++ b/tests/integration/staking/keeper/common_test.go @@ -122,10 +122,6 @@ func initFixture(tb testing.TB) *fixture { queryRouter := baseapp.NewGRPCQueryRouter() logger := log.NewTestLogger(tb) - cms := integration.CreateMultiStore(keys, logger) - - newCtx := sdk.NewContext(cms, true, logger) - authority := authtypes.NewModuleAddress("gov") maccPerms := map[string][]string{ @@ -139,6 +135,11 @@ func initFixture(tb testing.TB) *fixture { // gomock initializations ctrl := gomock.NewController(tb) acctsModKeeper := authtestutil.NewMockAccountsModKeeper(ctrl) + var lastAccNum uint64 + acctsModKeeper.EXPECT().NextAccountNumber(gomock.Any()).AnyTimes().DoAndReturn(func(ctx context.Context) (uint64, error) { + lastAccNum++ + return lastAccNum, nil + }) accountKeeper := authkeeper.NewAccountKeeper( runtime.NewEnvironment(runtime.NewKVStoreService(keys[authtypes.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(msgRouter)), @@ -162,8 +163,6 @@ func initFixture(tb testing.TB) *fixture { authority.String(), ) - assert.NilError(tb, bankKeeper.SetParams(newCtx, banktypes.DefaultParams())) - consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensustypes.StoreKey]), log.NewNopLogger()), authtypes.NewModuleAddress("gov").String()) stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[types.StoreKey]), log.NewNopLogger(), runtime.EnvWithQueryRouterService(queryRouter), runtime.EnvWithMsgRouterService(msgRouter)), accountKeeper, bankKeeper, consensusParamsKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), runtime.NewContextAwareCometInfoService()) @@ -173,7 +172,7 @@ func initFixture(tb testing.TB) *fixture { stakingModule := staking.NewAppModule(cdc, stakingKeeper) consensusModule := consensus.NewAppModule(cdc, consensusParamsKeeper) - integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ diff --git a/tests/integration/staking/keeper/deterministic_test.go b/tests/integration/staking/keeper/deterministic_test.go index 4a15c7775a35..d848a8cb3582 100644 --- a/tests/integration/staking/keeper/deterministic_test.go +++ b/tests/integration/staking/keeper/deterministic_test.go @@ -80,10 +80,6 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture { cdc := encodingCfg.Codec logger := log.NewTestLogger(t) - cms := integration.CreateMultiStore(keys, logger) - - newCtx := sdk.NewContext(cms, true, logger) - authority := authtypes.NewModuleAddress("gov") maccPerms := map[string][]string{ @@ -125,8 +121,6 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture { authority.String(), ) - assert.NilError(t, bankKeeper.SetParams(newCtx, banktypes.DefaultParams())) - consensusParamsKeeper := consensusparamkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[consensusparamtypes.StoreKey]), log.NewNopLogger()), authtypes.NewModuleAddress("gov").String()) stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewEnvironment(runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), log.NewNopLogger()), accountKeeper, bankKeeper, consensusParamsKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr), runtime.NewContextAwareCometInfoService()) @@ -136,7 +130,7 @@ func initDeterministicFixture(t *testing.T) *deterministicFixture { stakingModule := staking.NewAppModule(cdc, stakingKeeper) consensusModule := consensus.NewAppModule(cdc, consensusParamsKeeper) - integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ diff --git a/testutil/integration/helpers.go b/testutil/integration/helpers.go new file mode 100644 index 000000000000..ea844c17411b --- /dev/null +++ b/testutil/integration/helpers.go @@ -0,0 +1,22 @@ +package integration + +import ( + coretesting "cosmossdk.io/core/testing" + "cosmossdk.io/log" + "cosmossdk.io/store" + "cosmossdk.io/store/metrics" + storetypes "cosmossdk.io/store/types" +) + +// CreateMultiStore is a helper for setting up multiple stores for provided modules. +func CreateMultiStore(keys map[string]*storetypes.KVStoreKey, logger log.Logger) storetypes.CommitMultiStore { + db := coretesting.NewMemDB() + cms := store.NewCommitMultiStore(db, logger, metrics.NewNoOpMetrics()) + + for key := range keys { + cms.MountStoreWithDB(keys[key], storetypes.StoreTypeIAVL, db) + } + + _ = cms.LoadLatestVersion() + return cms +} diff --git a/testutil/integration/router.go b/testutil/integration/router.go index 07bbe3d4c206..a65766847f29 100644 --- a/testutil/integration/router.go +++ b/testutil/integration/router.go @@ -14,8 +14,6 @@ import ( corestore "cosmossdk.io/core/store" coretesting "cosmossdk.io/core/testing" "cosmossdk.io/log" - "cosmossdk.io/store" - "cosmossdk.io/store/metrics" storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/baseapp" @@ -37,16 +35,14 @@ const ( type App struct { *baseapp.BaseApp - ctx sdk.Context - logger log.Logger - moduleManager module.Manager - queryHelper *baseapp.QueryServiceTestHelper + ctx sdk.Context + logger log.Logger + queryHelper *baseapp.QueryServiceTestHelper } // NewIntegrationApp creates an application for testing purposes. This application // is able to route messages to their respective handlers. func NewIntegrationApp( - sdkCtx sdk.Context, logger log.Logger, keys map[string]*storetypes.KVStoreKey, appCodec codec.Codec, @@ -67,22 +63,26 @@ func NewIntegrationApp( bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), append(baseAppOptions, baseapp.SetChainID(appName))...) bApp.MountKVStores(keys) - bApp.SetInitChainer(func(_ sdk.Context, _ *cmtabcitypes.InitChainRequest) (*cmtabcitypes.InitChainResponse, error) { + bApp.SetInitChainer(func(sdkCtx sdk.Context, _ *cmtabcitypes.InitChainRequest) (*cmtabcitypes.InitChainResponse, error) { for _, mod := range modules { if m, ok := mod.(module.HasGenesis); ok { if err := m.InitGenesis(sdkCtx, m.DefaultGenesis()); err != nil { return nil, err } + } else if m, ok := mod.(module.HasABCIGenesis); ok { + if _, err := m.InitGenesis(sdkCtx, m.DefaultGenesis()); err != nil { + return nil, err + } } } return &cmtabcitypes.InitChainResponse{}, nil }) - bApp.SetBeginBlocker(func(_ sdk.Context) (sdk.BeginBlock, error) { + bApp.SetBeginBlocker(func(sdkCtx sdk.Context) (sdk.BeginBlock, error) { return moduleManager.BeginBlock(sdkCtx) }) - bApp.SetEndBlocker(func(_ sdk.Context) (sdk.EndBlock, error) { + bApp.SetEndBlocker(func(sdkCtx sdk.Context) (sdk.EndBlock, error) { return moduleManager.EndBlock(sdkCtx) }) @@ -91,15 +91,14 @@ func NewIntegrationApp( grpcRouter.SetInterfaceRegistry(interfaceRegistry) bApp.SetGRPCQueryRouter(grpcRouter) - if keys[consensus] != nil { - cps := newParamStore(runtime.NewKVStoreService(keys[consensus]), appCodec) - bApp.SetParamStore(cps) - - params := cmttypes.ConsensusParamsFromProto(*simtestutil.DefaultConsensusParams) // This fills up missing param sections - err := cps.Set(sdkCtx, params.ToProto()) - if err != nil { + if consensusKey := keys[consensus]; consensusKey != nil { + _ = bApp.CommitMultiStore().LoadLatestVersion() + cps := newParamStore(runtime.NewKVStoreService(consensusKey), appCodec) + params := cmttypes.ConsensusParamsFromProto(*simtestutil.DefaultConsensusParams) // This fills up missing param sections + if err := cps.Set(sdk.NewContext(bApp.CommitMultiStore(), true, logger), params.ToProto()); err != nil { // at this point, because we haven't written state we don't have a real context panic(fmt.Errorf("failed to set consensus params: %w", err)) } + bApp.SetParamStore(cps) if err := bApp.LoadLatestVersion(); err != nil { panic(fmt.Errorf("failed to load application version from store: %w", err)) @@ -118,19 +117,18 @@ func NewIntegrationApp( } } + bApp.SimWriteState() // forcing state write from init genesis like in sims _, err := bApp.Commit() if err != nil { panic(err) } - ctx := sdkCtx.WithBlockHeader(cmtproto.Header{ChainID: appName}).WithIsCheckTx(true) - + sdkCtx := bApp.NewContext(true).WithBlockHeader(cmtproto.Header{ChainID: appName}) return &App{ - BaseApp: bApp, - logger: logger, - ctx: ctx, - moduleManager: *moduleManager, - queryHelper: baseapp.NewQueryServerTestHelper(ctx, interfaceRegistry), + BaseApp: bApp, + logger: logger, + ctx: sdkCtx, + queryHelper: baseapp.NewQueryServerTestHelper(sdkCtx, interfaceRegistry), } } @@ -158,7 +156,7 @@ func (app *App) RunMsg(msg sdk.Msg, option ...Option) (*codectypes.Any, error) { if cfg.AutomaticFinalizeBlock { height := app.LastBlockHeight() + 1 - if _, err := app.FinalizeBlock(&cmtabcitypes.FinalizeBlockRequest{Height: height, DecidedLastCommit: cmtabcitypes.CommitInfo{Votes: []cmtabcitypes.VoteInfo{{}}}}); err != nil { + if _, err := app.FinalizeBlock(&cmtabcitypes.FinalizeBlockRequest{Height: height, DecidedLastCommit: cmtabcitypes.CommitInfo{Votes: []cmtabcitypes.VoteInfo{}}}); err != nil { return nil, fmt.Errorf("failed to run finalize block: %w", err) } } @@ -188,6 +186,21 @@ func (app *App) RunMsg(msg sdk.Msg, option ...Option) (*codectypes.Any, error) { return response, nil } +// NextBlock advances the chain height and returns the new height. +func (app *App) NextBlock(txsblob ...[]byte) (int64, error) { + height := app.LastBlockHeight() + 1 + if _, err := app.FinalizeBlock(&cmtabcitypes.FinalizeBlockRequest{ + Txs: txsblob, // txsBlob are raw txs to be executed in the block + Height: height, + DecidedLastCommit: cmtabcitypes.CommitInfo{Votes: []cmtabcitypes.VoteInfo{}}, + }); err != nil { + return 0, fmt.Errorf("failed to run finalize block: %w", err) + } + + _, err := app.Commit() + return height, err +} + // Context returns the application context. It can be unwrapped to a sdk.Context, // with the sdk.UnwrapSDKContext function. func (app *App) Context() context.Context { @@ -200,19 +213,6 @@ func (app *App) QueryHelper() *baseapp.QueryServiceTestHelper { return app.queryHelper } -// CreateMultiStore is a helper for setting up multiple stores for provided modules. -func CreateMultiStore(keys map[string]*storetypes.KVStoreKey, logger log.Logger) storetypes.CommitMultiStore { - db := coretesting.NewMemDB() - cms := store.NewCommitMultiStore(db, logger, metrics.NewNoOpMetrics()) - - for key := range keys { - cms.MountStoreWithDB(keys[key], storetypes.StoreTypeIAVL, db) - } - - _ = cms.LoadLatestVersion() - return cms -} - type paramStoreService struct { ParamsStore collections.Item[cmtproto.ConsensusParams] } diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index 929ff2e50285..5a178410553f 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -113,7 +113,7 @@ func (k BaseSendKeeper) GetAuthority() string { // GetParams returns the total set of bank parameters. func (k BaseSendKeeper) GetParams(ctx context.Context) (params types.Params) { - p, _ := k.Params.Get(ctx) + p, _ := k.Params.Get(ctx) // TODO: pretty bad, as it will just return empty params if it fails! return p }