From 5b3b793b3db96460fdc1ffd3e42e10842112c9f0 Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Thu, 21 Nov 2024 18:11:56 +0100 Subject: [PATCH 1/6] fix(testutil/integration): use only one context in integration test framework --- client/grpc_query_test.go | 3 - tests/integration/accounts/fixture_test.go | 13 +--- tests/integration/auth/keeper/fixture_test.go | 10 +-- .../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 | 8 +-- .../integration/staking/keeper/common_test.go | 8 +-- .../staking/keeper/deterministic_test.go | 8 +-- testutil/integration/helpers.go | 22 +++++++ testutil/integration/router.go | 63 +++++++------------ x/bank/keeper/send.go | 2 +- 15 files changed, 74 insertions(+), 146 deletions(-) create mode 100644 testutil/integration/helpers.go diff --git a/client/grpc_query_test.go b/client/grpc_query_test.go index d0d43a6d3023..d1e73d2de211 100644 --- a/client/grpc_query_test.go +++ b/client/grpc_query_test.go @@ -15,7 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/testutil" "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil/integration" "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/testutil/x/counter" counterkeeper "github.com/cosmos/cosmos-sdk/testutil/x/counter/keeper" @@ -38,8 +37,6 @@ func (s *IntegrationTestSuite) SetupSuite() { logger := log.NewNopLogger() keys := storetypes.NewKVStoreKeys(countertypes.StoreKey) - cms := integration.CreateMultiStore(keys, logger) - s.ctx = sdk.NewContext(cms, true, logger) cfg := moduletestutil.MakeTestEncodingConfig(testutil.CodecOptions{}, counter.AppModule{}) s.cdc = cfg.Codec diff --git a/tests/integration/accounts/fixture_test.go b/tests/integration/accounts/fixture_test.go index 63c301bbf4df..b7ce9cfa6b02 100644 --- a/tests/integration/accounts/fixture_test.go +++ b/tests/integration/accounts/fixture_test.go @@ -119,10 +119,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 +165,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 +187,14 @@ 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, + ctx: sdk.UnwrapSDKContext(integrationApp.Context()), authKeeper: authKeeper, accountsKeeper: accountsKeeper, bankKeeper: bankKeeper, diff --git a/tests/integration/auth/keeper/fixture_test.go b/tests/integration/auth/keeper/fixture_test.go index f8a2d10ba871..f4108846350b 100644 --- a/tests/integration/auth/keeper/fixture_test.go +++ b/tests/integration/auth/keeper/fixture_test.go @@ -57,9 +57,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 +106,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 +130,7 @@ func initFixture(t *testing.T, extraAccs map[string]accountstd.Interface) *fixtu return &fixture{ app: integrationApp, cdc: cdc, - ctx: newCtx, + ctx: sdk.UnwrapSDKContext(integrationApp.Context()), accountsKeeper: accountsKeeper, authKeeper: authKeeper, bankKeeper: bankKeeper, diff --git a/tests/integration/bank/keeper/deterministic_test.go b/tests/integration/bank/keeper/deterministic_test.go index 7764352f69a7..2a7af76a866f 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 debc76c1b3ec..3fc0d2d265d9 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 b82bc1fae114..76f47fb59efe 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 c1deca500aab..6d4d57c3f356 100644 --- a/tests/integration/example/example_test.go +++ b/tests/integration/example/example_test.go @@ -45,9 +45,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) @@ -79,7 +76,6 @@ func Example() { // create the application and register all the modules from the previous step integrationApp := integration.NewIntegrationApp( - newCtx, logger, keys, encodingCfg.Codec, @@ -149,9 +145,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) @@ -178,7 +171,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 c6d270a161dc..c40e847cc632 100644 --- a/tests/integration/gov/keeper/keeper_test.go +++ b/tests/integration/gov/keeper/keeper_test.go @@ -5,7 +5,6 @@ import ( "testing" "go.uber.org/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 c10c56543414..d2d2205c1a64 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -68,10 +68,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("gov") maccPerms := map[string][]string{ @@ -115,8 +111,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 +124,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(logger, keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ diff --git a/tests/integration/staking/keeper/common_test.go b/tests/integration/staking/keeper/common_test.go index 06e9c059486d..dd3864b2955c 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{ @@ -162,8 +158,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 +167,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 4a47dc2fa6f5..5ce5a66c0b4f 100644 --- a/tests/integration/staking/keeper/deterministic_test.go +++ b/tests/integration/staking/keeper/deterministic_test.go @@ -82,10 +82,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{ @@ -127,8 +123,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()) @@ -138,7 +132,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..83fe3739d598 100644 --- a/testutil/integration/router.go +++ b/testutil/integration/router.go @@ -14,15 +14,13 @@ 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/runtime" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "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" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" @@ -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), } } @@ -200,19 +198,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 6afa29b9f21c..49f278a2dfce 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 } From c5e98126e4989e37303ad0523c5513194c05ed2e Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Thu, 21 Nov 2024 21:13:19 +0100 Subject: [PATCH 2/6] updates --- client/grpc_query_test.go | 3 +++ tests/integration/accounts/fixture_test.go | 11 ++++------ .../accounts_retro_compatibility_test.go | 22 +++++++++---------- tests/integration/auth/keeper/fixture_test.go | 2 -- .../auth/keeper/migrate_x_accounts_test.go | 22 +++++++++---------- .../auth/keeper/msg_server_test.go | 2 +- tests/integration/type_check.go | 4 ++-- testutil/integration/router.go | 4 ++-- 8 files changed, 34 insertions(+), 36 deletions(-) diff --git a/client/grpc_query_test.go b/client/grpc_query_test.go index d1e73d2de211..d0d43a6d3023 100644 --- a/client/grpc_query_test.go +++ b/client/grpc_query_test.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/testutil" "github.com/cosmos/cosmos-sdk/runtime" + "github.com/cosmos/cosmos-sdk/testutil/integration" "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/cosmos/cosmos-sdk/testutil/x/counter" counterkeeper "github.com/cosmos/cosmos-sdk/testutil/x/counter/keeper" @@ -37,6 +38,8 @@ func (s *IntegrationTestSuite) SetupSuite() { logger := log.NewNopLogger() keys := storetypes.NewKVStoreKeys(countertypes.StoreKey) + cms := integration.CreateMultiStore(keys, logger) + s.ctx = sdk.NewContext(cms, true, logger) cfg := moduletestutil.MakeTestEncodingConfig(testutil.CodecOptions{}, counter.AppModule{}) s.cdc = cfg.Codec diff --git a/tests/integration/accounts/fixture_test.go b/tests/integration/accounts/fixture_test.go index b7ce9cfa6b02..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, }) @@ -194,7 +192,6 @@ func initFixture(t *testing.T, f func(ctx context.Context, msg *account_abstract t: t, app: integrationApp, cdc: cdc, - ctx: sdk.UnwrapSDKContext(integrationApp.Context()), 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 f4108846350b..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 @@ -130,7 +129,6 @@ func initFixture(t *testing.T, extraAccs map[string]accountstd.Interface) *fixtu return &fixture{ app: integrationApp, cdc: cdc, - ctx: sdk.UnwrapSDKContext(integrationApp.Context()), 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/type_check.go b/tests/integration/type_check.go index 9885981eb2a4..2982f79ea639 100644 --- a/tests/integration/type_check.go +++ b/tests/integration/type_check.go @@ -1,9 +1,9 @@ package integration import ( - coretesting "cosmossdk.io/core/testing" - db "github.com/cosmos/cosmos-db" + + coretesting "cosmossdk.io/core/testing" ) // This file contains a list of type checks that are used to ensure that implementations diff --git a/testutil/integration/router.go b/testutil/integration/router.go index 83fe3739d598..9b85d313a609 100644 --- a/testutil/integration/router.go +++ b/testutil/integration/router.go @@ -15,12 +15,12 @@ import ( coretesting "cosmossdk.io/core/testing" "cosmossdk.io/log" storetypes "cosmossdk.io/store/types" - "github.com/cosmos/cosmos-sdk/runtime" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "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" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" From 3ab3fa21656b5c5bc3a376168f0c49fb1a62bfd2 Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Fri, 22 Nov 2024 17:31:28 +0100 Subject: [PATCH 3/6] cl --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d88d88ad2d0..dc35a28c4c68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,9 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i ### Improvements +* (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 From 6bcb81a0288fdf3a3d205fa8732b5e27546f445c Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Fri, 22 Nov 2024 21:08:14 +0100 Subject: [PATCH 4/6] updates --- tests/integration/staking/keeper/common_test.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/integration/staking/keeper/common_test.go b/tests/integration/staking/keeper/common_test.go index dd3864b2955c..bcce987fc4f5 100644 --- a/tests/integration/staking/keeper/common_test.go +++ b/tests/integration/staking/keeper/common_test.go @@ -135,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)), From a4c026aec029b02338aa1c84b0e5ffa8cca14b73 Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Mon, 25 Nov 2024 11:23:55 +0100 Subject: [PATCH 5/6] fixes --- .../integration/slashing/keeper/keeper_test.go | 7 ++----- testutil/integration/router.go | 17 ++++++++++++++++- types/module/module.go | 8 ++++---- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index d2d2205c1a64..74ccf5da61f8 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -67,7 +67,6 @@ func initFixture(tb testing.TB) *fixture { encodingCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}, auth.AppModule{}) cdc := encodingCfg.Codec - logger := log.NewTestLogger(tb) authority := authtypes.NewModuleAddress("gov") maccPerms := map[string][]string{ @@ -124,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(logger, keys, cdc, + integrationApp := integration.NewIntegrationApp(log.NewNopLogger(), keys, cdc, encodingCfg.InterfaceRegistry.SigningContext().AddressCodec(), encodingCfg.InterfaceRegistry.SigningContext().ValidatorAddressCodec(), map[string]appmodule.AppModule{ @@ -144,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/testutil/integration/router.go b/testutil/integration/router.go index 9b85d313a609..a65766847f29 100644 --- a/testutil/integration/router.go +++ b/testutil/integration/router.go @@ -156,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) } } @@ -186,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 { diff --git a/types/module/module.go b/types/module/module.go index 7d865930b26b..354fddc81c69 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -727,7 +727,7 @@ func (m *Manager) PreBlock(ctx sdk.Context) error { for _, moduleName := range m.OrderPreBlockers { if module, ok := m.Modules[moduleName].(appmodule.HasPreBlocker); ok { if err := module.PreBlock(ctx); err != nil { - return err + return fmt.Errorf("module %s PreBlock failed: %w", moduleName, err) } } } @@ -742,7 +742,7 @@ func (m *Manager) BeginBlock(ctx sdk.Context) (sdk.BeginBlock, error) { for _, moduleName := range m.OrderBeginBlockers { if module, ok := m.Modules[moduleName].(appmodule.HasBeginBlocker); ok { if err := module.BeginBlock(ctx); err != nil { - return sdk.BeginBlock{}, err + return sdk.BeginBlock{}, fmt.Errorf("module %s BeginBlock failed: %w", moduleName, err) } } } @@ -763,12 +763,12 @@ func (m *Manager) EndBlock(ctx sdk.Context) (sdk.EndBlock, error) { if module, ok := m.Modules[moduleName].(appmodule.HasEndBlocker); ok { err := module.EndBlock(ctx) if err != nil { - return sdk.EndBlock{}, err + return sdk.EndBlock{}, fmt.Errorf("module %s EndBlock failed: %w", moduleName, err) } } else if module, ok := m.Modules[moduleName].(HasABCIEndBlock); ok { moduleValUpdates, err := module.EndBlock(ctx) if err != nil { - return sdk.EndBlock{}, err + return sdk.EndBlock{}, fmt.Errorf("module %s EndBlock failed: %w", moduleName, err) } // use these validator updates if provided, the module manager assumes // only one module will update the validator set From 135ddd17a36baee3c39157f424bfc18ab025b63d Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Mon, 25 Nov 2024 11:40:38 +0100 Subject: [PATCH 6/6] revert debug lines --- types/module/module.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/module/module.go b/types/module/module.go index 354fddc81c69..7d865930b26b 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -727,7 +727,7 @@ func (m *Manager) PreBlock(ctx sdk.Context) error { for _, moduleName := range m.OrderPreBlockers { if module, ok := m.Modules[moduleName].(appmodule.HasPreBlocker); ok { if err := module.PreBlock(ctx); err != nil { - return fmt.Errorf("module %s PreBlock failed: %w", moduleName, err) + return err } } } @@ -742,7 +742,7 @@ func (m *Manager) BeginBlock(ctx sdk.Context) (sdk.BeginBlock, error) { for _, moduleName := range m.OrderBeginBlockers { if module, ok := m.Modules[moduleName].(appmodule.HasBeginBlocker); ok { if err := module.BeginBlock(ctx); err != nil { - return sdk.BeginBlock{}, fmt.Errorf("module %s BeginBlock failed: %w", moduleName, err) + return sdk.BeginBlock{}, err } } } @@ -763,12 +763,12 @@ func (m *Manager) EndBlock(ctx sdk.Context) (sdk.EndBlock, error) { if module, ok := m.Modules[moduleName].(appmodule.HasEndBlocker); ok { err := module.EndBlock(ctx) if err != nil { - return sdk.EndBlock{}, fmt.Errorf("module %s EndBlock failed: %w", moduleName, err) + return sdk.EndBlock{}, err } } else if module, ok := m.Modules[moduleName].(HasABCIEndBlock); ok { moduleValUpdates, err := module.EndBlock(ctx) if err != nil { - return sdk.EndBlock{}, fmt.Errorf("module %s EndBlock failed: %w", moduleName, err) + return sdk.EndBlock{}, err } // use these validator updates if provided, the module manager assumes // only one module will update the validator set