From dab4f61d7a2c398e756823e9143ba3665daefc82 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 14:47:29 -0500 Subject: [PATCH 01/24] header service --- core/testing/context.go | 4 +++- core/testing/header.go | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 core/testing/header.go diff --git a/core/testing/context.go b/core/testing/context.go index 39218f1f90f6..2427742e9f66 100644 --- a/core/testing/context.go +++ b/core/testing/context.go @@ -2,8 +2,8 @@ package coretesting import ( "context" - "cosmossdk.io/core/event" + "cosmossdk.io/core/header" "cosmossdk.io/core/store" "cosmossdk.io/core/transaction" ) @@ -28,6 +28,8 @@ type dummyCtx struct { events map[string][]event.Event // maps proto events emitted by the actor. protoEvents map[string][]transaction.Msg + // header is the header set by a test runner + header header.Info } func unwrap(ctx context.Context) *dummyCtx { diff --git a/core/testing/header.go b/core/testing/header.go new file mode 100644 index 000000000000..ac19145cc587 --- /dev/null +++ b/core/testing/header.go @@ -0,0 +1,15 @@ +package coretesting + +import ( + "context" + + "cosmossdk.io/core/header" +) + +var _ header.Service = &MemHeaderService{} + +type MemHeaderService struct{} + +func (e MemHeaderService) HeaderInfo(ctx context.Context) header.Info { + return unwrap(ctx).header +} From ccdbad44bb540b44368c98b9e745e676c9278136 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 14:49:30 -0500 Subject: [PATCH 02/24] update --- core/testing/context.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/core/testing/context.go b/core/testing/context.go index 2427742e9f66..740b6b73cecb 100644 --- a/core/testing/context.go +++ b/core/testing/context.go @@ -15,12 +15,21 @@ func Context() context.Context { stores: map[string]store.KVStore{}, events: map[string][]event.Event{}, protoEvents: map[string][]transaction.Msg{}, + header: header.Info{}, } ctx := context.WithValue(context.Background(), dummyKey{}, dummy) return ctx } +// WithHeader sets the header on a testing ctx and returns the updated ctx. +func WithHeader(ctx context.Context, info header.Info) context.Context { + dummy := unwrap(ctx) + dummy.header = info + + return context.WithValue(ctx, dummyKey{}, dummy) +} + type dummyCtx struct { // maps store by the actor. stores map[string]store.KVStore From ef438eb1de72f2eca08a0603a5908cbc94b69f9e Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 14:53:35 -0500 Subject: [PATCH 03/24] basic env --- core/testing/environment.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 core/testing/environment.go diff --git a/core/testing/environment.go b/core/testing/environment.go new file mode 100644 index 000000000000..1e96c0a87f40 --- /dev/null +++ b/core/testing/environment.go @@ -0,0 +1,23 @@ +package coretesting + +import ( + "context" + appmodulev2 "cosmossdk.io/core/appmodule/v2" +) + +func SetupTestEnvironment(moduleName string) (context.Context, appmodulev2.Environment) { + ctx := Context() + + return ctx, appmodulev2.Environment{ + Logger: nil, + BranchService: nil, + EventService: EventsService(ctx, moduleName), + GasService: nil, + HeaderService: MemHeaderService{}, + QueryRouterService: nil, + MsgRouterService: nil, + TransactionService: nil, + KVStoreService: KVStoreService(ctx, moduleName), + MemStoreService: nil, + } +} From 9dfae05f184ba341ee346e1149dabe69a34f37b0 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 15:22:16 -0500 Subject: [PATCH 04/24] transaction service --- core/testing/context.go | 55 +++++++++++++++++++++++++++++++------ core/testing/environment.go | 5 ++-- core/testing/transaction.go | 16 +++++++++++ 3 files changed, 65 insertions(+), 11 deletions(-) create mode 100644 core/testing/transaction.go diff --git a/core/testing/context.go b/core/testing/context.go index 740b6b73cecb..f78bfbfc4c34 100644 --- a/core/testing/context.go +++ b/core/testing/context.go @@ -2,6 +2,8 @@ package coretesting import ( "context" + "time" + "cosmossdk.io/core/event" "cosmossdk.io/core/header" "cosmossdk.io/core/store" @@ -10,24 +12,60 @@ import ( type dummyKey struct{} -func Context() context.Context { +var _ context.Context = &TestContext{} + +type TestContext struct { + ctx context.Context +} + +func Context() TestContext { dummy := &dummyCtx{ stores: map[string]store.KVStore{}, events: map[string][]event.Event{}, protoEvents: map[string][]transaction.Msg{}, header: header.Info{}, + execMode: transaction.ExecModeFinalize, + } + + return TestContext{ + ctx: context.WithValue(context.Background(), dummyKey{}, dummy), } +} - ctx := context.WithValue(context.Background(), dummyKey{}, dummy) - return ctx +func (t TestContext) Deadline() (deadline time.Time, ok bool) { + return t.ctx.Deadline() +} + +func (t TestContext) Done() <-chan struct{} { + return t.ctx.Done() +} + +func (t TestContext) Err() error { + return t.ctx.Err() +} + +func (t TestContext) Value(key any) any { + return t.ctx.Value(key) } // WithHeader sets the header on a testing ctx and returns the updated ctx. -func WithHeader(ctx context.Context, info header.Info) context.Context { - dummy := unwrap(ctx) +func (t TestContext) WithHeader(info header.Info) TestContext { + dummy := unwrap(t.ctx) dummy.header = info - return context.WithValue(ctx, dummyKey{}, dummy) + return TestContext{ + ctx: context.WithValue(t.ctx, dummyKey{}, dummy), + } +} + +// WithExecMode sets the exec mode on a testing ctx and returns the updated ctx. +func (t TestContext) WithExecMode(mode transaction.ExecMode) context.Context { + dummy := unwrap(t.ctx) + dummy.execMode = mode + + return TestContext{ + ctx: context.WithValue(t.ctx, dummyKey{}, dummy), + } } type dummyCtx struct { @@ -37,8 +75,9 @@ type dummyCtx struct { events map[string][]event.Event // maps proto events emitted by the actor. protoEvents map[string][]transaction.Msg - // header is the header set by a test runner - header header.Info + + header header.Info + execMode transaction.ExecMode } func unwrap(ctx context.Context) *dummyCtx { diff --git a/core/testing/environment.go b/core/testing/environment.go index 1e96c0a87f40..33789bd7a7b2 100644 --- a/core/testing/environment.go +++ b/core/testing/environment.go @@ -1,11 +1,10 @@ package coretesting import ( - "context" appmodulev2 "cosmossdk.io/core/appmodule/v2" ) -func SetupTestEnvironment(moduleName string) (context.Context, appmodulev2.Environment) { +func SetupTestEnvironment(moduleName string) (TestContext, appmodulev2.Environment) { ctx := Context() return ctx, appmodulev2.Environment{ @@ -16,7 +15,7 @@ func SetupTestEnvironment(moduleName string) (context.Context, appmodulev2.Envir HeaderService: MemHeaderService{}, QueryRouterService: nil, MsgRouterService: nil, - TransactionService: nil, + TransactionService: MemTransactionService{}, KVStoreService: KVStoreService(ctx, moduleName), MemStoreService: nil, } diff --git a/core/testing/transaction.go b/core/testing/transaction.go new file mode 100644 index 000000000000..eb53622b923b --- /dev/null +++ b/core/testing/transaction.go @@ -0,0 +1,16 @@ +package coretesting + +import ( + "context" + "cosmossdk.io/core/transaction" +) + +var _ transaction.Service = &MemTransactionService{} + +type MemTransactionService struct{} + +func (m MemTransactionService) ExecMode(ctx context.Context) transaction.ExecMode { + dummy := unwrap(ctx) + + return dummy.execMode +} From 779bd849d24c03bcbce9a9d58d14b6599dbc00f3 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 15:36:48 -0500 Subject: [PATCH 05/24] refit --- core/testing/context.go | 15 ++++ core/testing/environment.go | 9 +- core/testing/gas.go | 22 +++++ core/testing/router.go | 159 ++++++++++++++++++++++++++++++++++ core/testing/services_test.go | 4 +- 5 files changed, 203 insertions(+), 6 deletions(-) create mode 100644 core/testing/gas.go create mode 100644 core/testing/router.go diff --git a/core/testing/context.go b/core/testing/context.go index f78bfbfc4c34..b074d52481ff 100644 --- a/core/testing/context.go +++ b/core/testing/context.go @@ -5,6 +5,7 @@ import ( "time" "cosmossdk.io/core/event" + "cosmossdk.io/core/gas" "cosmossdk.io/core/header" "cosmossdk.io/core/store" "cosmossdk.io/core/transaction" @@ -68,6 +69,17 @@ func (t TestContext) WithExecMode(mode transaction.ExecMode) context.Context { } } +// WithGas sets the gas config and meter on a testing ctx and returns the updated ctx. +func (t TestContext) WithGas(gasConfig gas.GasConfig, gasMeter gas.Meter) context.Context { + dummy := unwrap(t.ctx) + dummy.gasConfig = gasConfig + dummy.gasMeter = gasMeter + + return TestContext{ + ctx: context.WithValue(t.ctx, dummyKey{}, dummy), + } +} + type dummyCtx struct { // maps store by the actor. stores map[string]store.KVStore @@ -78,6 +90,9 @@ type dummyCtx struct { header header.Info execMode transaction.ExecMode + + gasMeter gas.Meter + gasConfig gas.GasConfig } func unwrap(ctx context.Context) *dummyCtx { diff --git a/core/testing/environment.go b/core/testing/environment.go index 33789bd7a7b2..0b6f8fe02f74 100644 --- a/core/testing/environment.go +++ b/core/testing/environment.go @@ -2,19 +2,20 @@ package coretesting import ( appmodulev2 "cosmossdk.io/core/appmodule/v2" + "cosmossdk.io/core/router" ) -func SetupTestEnvironment(moduleName string) (TestContext, appmodulev2.Environment) { +func SetupTestEnvironment(moduleName string, msgRouter, queryRouter router.Service) (TestContext, appmodulev2.Environment) { ctx := Context() return ctx, appmodulev2.Environment{ Logger: nil, BranchService: nil, EventService: EventsService(ctx, moduleName), - GasService: nil, + GasService: MemGasService{}, HeaderService: MemHeaderService{}, - QueryRouterService: nil, - MsgRouterService: nil, + QueryRouterService: queryRouter, + MsgRouterService: msgRouter, TransactionService: MemTransactionService{}, KVStoreService: KVStoreService(ctx, moduleName), MemStoreService: nil, diff --git a/core/testing/gas.go b/core/testing/gas.go new file mode 100644 index 000000000000..89b64a140a06 --- /dev/null +++ b/core/testing/gas.go @@ -0,0 +1,22 @@ +package coretesting + +import ( + "context" + "cosmossdk.io/core/gas" +) + +var _ gas.Service = &MemGasService{} + +type MemGasService struct{} + +func (m MemGasService) GasMeter(ctx context.Context) gas.Meter { + dummy := unwrap(ctx) + + return dummy.gasMeter +} + +func (m MemGasService) GasConfig(ctx context.Context) gas.GasConfig { + dummy := unwrap(ctx) + + return dummy.gasConfig +} diff --git a/core/testing/router.go b/core/testing/router.go new file mode 100644 index 000000000000..1d9546d3d4dd --- /dev/null +++ b/core/testing/router.go @@ -0,0 +1,159 @@ +package coretesting + +import ( + "context" + "errors" + "fmt" + "reflect" + + appmodulev2 "cosmossdk.io/core/appmodule/v2" + "cosmossdk.io/core/router" + "cosmossdk.io/core/transaction" +) + +var ErrNoHandler = errors.New("no handler") + +// NewMsgRouterBuilder is a router that routes messages to their respective handlers. +func NewMsgRouterBuilder() *ReflectionRouterBuilder { + return &ReflectionRouterBuilder{ + handlers: make(map[string]appmodulev2.HandlerFunc), + preHandlers: make(map[string][]appmodulev2.PreMsgHandler), + postHandlers: make(map[string][]appmodulev2.PostMsgHandler), + } +} + +type ReflectionRouterBuilder struct { + handlers map[string]appmodulev2.HandlerFunc + globalPreHandlers []appmodulev2.PreMsgHandler + preHandlers map[string][]appmodulev2.PreMsgHandler + postHandlers map[string][]appmodulev2.PostMsgHandler + globalPostHandlers []appmodulev2.PostMsgHandler +} + +func (b *ReflectionRouterBuilder) RegisterHandler(msgType string, handler appmodulev2.HandlerFunc) error { + // panic on override + if _, ok := b.handlers[msgType]; ok { + return fmt.Errorf("handler already registered: %s", msgType) + } + b.handlers[msgType] = handler + return nil +} + +func (b *ReflectionRouterBuilder) RegisterGlobalPreMsgHandler(handler appmodulev2.PreMsgHandler) { + b.globalPreHandlers = append(b.globalPreHandlers, handler) +} + +func (b *ReflectionRouterBuilder) RegisterPreMsgHandler(msgType string, handler appmodulev2.PreMsgHandler) { + b.preHandlers[msgType] = append(b.preHandlers[msgType], handler) +} + +func (b *ReflectionRouterBuilder) RegisterPostMsgHandler(msgType string, handler appmodulev2.PostMsgHandler) { + b.postHandlers[msgType] = append(b.postHandlers[msgType], handler) +} + +func (b *ReflectionRouterBuilder) RegisterGlobalPostMsgHandler(handler appmodulev2.PostMsgHandler) { + b.globalPostHandlers = append(b.globalPostHandlers, handler) +} + +func (b *ReflectionRouterBuilder) HandlerExists(msgType string) bool { + _, ok := b.handlers[msgType] + return ok +} + +func (b *ReflectionRouterBuilder) Build() (ReflectionRouter, error) { + handlers := make(map[string]appmodulev2.HandlerFunc) + + globalPreHandler := func(ctx context.Context, msg transaction.Msg) error { + for _, h := range b.globalPreHandlers { + err := h(ctx, msg) + if err != nil { + return err + } + } + return nil + } + + globalPostHandler := func(ctx context.Context, msg, msgResp transaction.Msg) error { + for _, h := range b.globalPostHandlers { + err := h(ctx, msg, msgResp) + if err != nil { + return err + } + } + return nil + } + + for msgType, handler := range b.handlers { + // find pre handler + preHandlers := b.preHandlers[msgType] + // find post handler + postHandlers := b.postHandlers[msgType] + // build the handler + handlers[msgType] = buildHandler(handler, preHandlers, globalPreHandler, postHandlers, globalPostHandler) + } + + return ReflectionRouter{ + handlers: handlers, + }, nil +} + +func buildHandler( + handler appmodulev2.HandlerFunc, + preHandlers []appmodulev2.PreMsgHandler, + globalPreHandler appmodulev2.PreMsgHandler, + postHandlers []appmodulev2.PostMsgHandler, + globalPostHandler appmodulev2.PostMsgHandler, +) appmodulev2.HandlerFunc { + return func(ctx context.Context, msg transaction.Msg) (msgResp transaction.Msg, err error) { + if len(preHandlers) != 0 { + for _, preHandler := range preHandlers { + if err := preHandler(ctx, msg); err != nil { + return nil, err + } + } + } + err = globalPreHandler(ctx, msg) + if err != nil { + return nil, err + } + msgResp, err = handler(ctx, msg) + if err != nil { + return nil, err + } + + if len(postHandlers) != 0 { + for _, postHandler := range postHandlers { + if err := postHandler(ctx, msg, msgResp); err != nil { + return nil, err + } + } + } + err = globalPostHandler(ctx, msg, msgResp) + return msgResp, err + } +} + +var _ router.Service = (*ReflectionRouter)(nil) + +// ReflectionRouter implements the STF router for msg and query handlers. +type ReflectionRouter struct { + handlers map[string]appmodulev2.HandlerFunc +} + +func (r ReflectionRouter) CanInvoke(_ context.Context, typeURL string) error { + _, exists := r.handlers[typeURL] + if !exists { + return fmt.Errorf("%w: %s", ErrNoHandler, typeURL) + } + return nil +} + +func (r ReflectionRouter) Invoke(ctx context.Context, req transaction.Msg) (res transaction.Msg, err error) { + typeName := reflect.TypeOf(req).String() + handler, exists := r.handlers[typeName] + if !exists { + return nil, fmt.Errorf("%w: %s", ErrNoHandler, typeName) + } + + return handler(ctx, req) +} diff --git a/core/testing/services_test.go b/core/testing/services_test.go index 2f226e6e04c3..6c1a2dddb3dc 100644 --- a/core/testing/services_test.go +++ b/core/testing/services_test.go @@ -6,8 +6,8 @@ import ( ) func TestKVStoreService(t *testing.T) { - ctx := Context() - svc1 := KVStoreService(ctx, "bank") + ctx, env := SetupTestEnvironment("bank", nil, nil) + svc1 := env.KVStoreService // must panic t.Run("must panic on invalid ctx", func(t *testing.T) { From 2e7ca6db6471687ed19643d79cdb51d0b7ae70f0 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 15:49:58 -0500 Subject: [PATCH 06/24] register --- x/bank/v2/keeper/handlers.go | 16 +++++++++++++++- x/bank/v2/module.go | 9 ++------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/x/bank/v2/keeper/handlers.go b/x/bank/v2/keeper/handlers.go index e998aceecb72..c9da64b9940c 100644 --- a/x/bank/v2/keeper/handlers.go +++ b/x/bank/v2/keeper/handlers.go @@ -3,6 +3,7 @@ package keeper import ( "bytes" "context" + appmodulev2 "cosmossdk.io/core/appmodule/v2" "errors" "fmt" @@ -25,7 +26,20 @@ func NewHandlers(k *Keeper) handlers { return handlers{k} } -// UpdateParams updates the parameters of the bank/v2 module. +// RegisterMsgHandlers registers the message handlers to the router. +func (h handlers) RegisterMsgHandlers(router appmodulev2.MsgRouter) { + appmodulev2.RegisterMsgHandler(router, h.MsgUpdateParams) + appmodulev2.RegisterMsgHandler(router, h.MsgSend) + appmodulev2.RegisterMsgHandler(router, h.MsgMint) +} + +// RegisterQueryHandlers registers the query handlers to the router. +func (h handlers) RegisterQueryHandlers(router appmodulev2.QueryRouter) { + appmodulev2.RegisterMsgHandler(router, h.QueryParams) + appmodulev2.RegisterMsgHandler(router, h.QueryBalance) +} + +// MsgUpdateParams updates the parameters of the bank/v2 module. func (h handlers) MsgUpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { authorityBytes, err := h.addressCodec.StringToBytes(msg.Authority) if err != nil { diff --git a/x/bank/v2/module.go b/x/bank/v2/module.go index 99d5ab2ab7d4..c8f6880a1ef1 100644 --- a/x/bank/v2/module.go +++ b/x/bank/v2/module.go @@ -94,18 +94,13 @@ func (am AppModule) ExportGenesis(ctx context.Context) (json.RawMessage, error) // RegisterMsgHandlers registers the message handlers for the bank module. func (am AppModule) RegisterMsgHandlers(router appmodulev2.MsgRouter) { handlers := keeper.NewHandlers(am.keeper) - - appmodulev2.RegisterMsgHandler(router, handlers.MsgUpdateParams) - appmodulev2.RegisterMsgHandler(router, handlers.MsgSend) - appmodulev2.RegisterMsgHandler(router, handlers.MsgMint) + handlers.RegisterMsgHandlers(router) } // RegisterQueryHandlers registers the query handlers for the bank module. func (am AppModule) RegisterQueryHandlers(router appmodulev2.QueryRouter) { handlers := keeper.NewHandlers(am.keeper) - - appmodulev2.RegisterMsgHandler(router, handlers.QueryParams) - appmodulev2.RegisterMsgHandler(router, handlers.QueryBalance) + handlers.RegisterQueryHandlers(router) } // GetTxCmd returns the root tx command for the bank/v2 module. From 6161b6a0e9dcea831e4f53e74251779e81782c90 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 16:52:57 -0500 Subject: [PATCH 07/24] utd --- core/testing/context.go | 4 +- core/testing/environment.go | 62 +++++++++++++++++----- core/testing/services_test.go | 10 +++- x/bank/go.mod | 5 +- x/bank/go.sum | 2 - x/bank/keeper/grpc_query_test.go | 4 +- x/bank/keeper/keeper_test.go | 90 +++++++++++++++++++------------- 7 files changed, 121 insertions(+), 56 deletions(-) diff --git a/core/testing/context.go b/core/testing/context.go index b074d52481ff..a8a3c3ec4255 100644 --- a/core/testing/context.go +++ b/core/testing/context.go @@ -49,8 +49,8 @@ func (t TestContext) Value(key any) any { return t.ctx.Value(key) } -// WithHeader sets the header on a testing ctx and returns the updated ctx. -func (t TestContext) WithHeader(info header.Info) TestContext { +// WithHeaderInfo sets the header on a testing ctx and returns the updated ctx. +func (t TestContext) WithHeaderInfo(info header.Info) TestContext { dummy := unwrap(t.ctx) dummy.header = info diff --git a/core/testing/environment.go b/core/testing/environment.go index 0b6f8fe02f74..32cec6e1290d 100644 --- a/core/testing/environment.go +++ b/core/testing/environment.go @@ -2,22 +2,60 @@ package coretesting import ( appmodulev2 "cosmossdk.io/core/appmodule/v2" + corelog "cosmossdk.io/core/log" "cosmossdk.io/core/router" + "cosmossdk.io/core/store" ) -func SetupTestEnvironment(moduleName string, msgRouter, queryRouter router.Service) (TestContext, appmodulev2.Environment) { +type TestEnvironmentConfig struct { + ModuleName string + Logger corelog.Logger + MsgRouter router.Service + QueryRouter router.Service +} + +type TestEnvironment struct { + env appmodulev2.Environment + memEventsService MemEventsService + memHeaderService MemHeaderService +} + +func NewTestEnvironment(cfg TestEnvironmentConfig) (TestContext, TestEnvironment) { ctx := Context() - return ctx, appmodulev2.Environment{ - Logger: nil, - BranchService: nil, - EventService: EventsService(ctx, moduleName), - GasService: MemGasService{}, - HeaderService: MemHeaderService{}, - QueryRouterService: queryRouter, - MsgRouterService: msgRouter, - TransactionService: MemTransactionService{}, - KVStoreService: KVStoreService(ctx, moduleName), - MemStoreService: nil, + memEventService := EventsService(ctx, cfg.ModuleName) + memHeaderService := MemHeaderService{} + + return ctx, TestEnvironment{ + env: appmodulev2.Environment{ + Logger: cfg.Logger, + BranchService: nil, + EventService: memEventService, + GasService: MemGasService{}, + HeaderService: memHeaderService, + QueryRouterService: cfg.QueryRouter, + MsgRouterService: cfg.MsgRouter, + TransactionService: MemTransactionService{}, + KVStoreService: KVStoreService(ctx, cfg.ModuleName), + MemStoreService: nil, + }, + memEventsService: memEventService, + memHeaderService: memHeaderService, } } + +func (env TestEnvironment) MemEventsService() MemEventsService { + return env.memEventsService +} + +func (env TestEnvironment) Environment() appmodulev2.Environment { + return env.env +} + +func (env TestEnvironment) KVStoreService() store.KVStoreService { + return env.env.KVStoreService +} + +func (env TestEnvironment) HeaderService() MemHeaderService { + return env.memHeaderService +} diff --git a/core/testing/services_test.go b/core/testing/services_test.go index 6c1a2dddb3dc..969f5fa8190a 100644 --- a/core/testing/services_test.go +++ b/core/testing/services_test.go @@ -6,8 +6,14 @@ import ( ) func TestKVStoreService(t *testing.T) { - ctx, env := SetupTestEnvironment("bank", nil, nil) - svc1 := env.KVStoreService + cfg := TestEnvironmentConfig{ + ModuleName: "bank", + Logger: nil, + MsgRouter: nil, + QueryRouter: nil, + } + ctx, env := NewTestEnvironment(cfg) + svc1 := env.KVStoreService() // must panic t.Run("must panic on invalid ctx", func(t *testing.T) { diff --git a/x/bank/go.mod b/x/bank/go.mod index 8a1a942988df..cea53a298129 100644 --- a/x/bank/go.mod +++ b/x/bank/go.mod @@ -173,7 +173,10 @@ require ( golang.org/x/arch v0.12.0 // indirect ) -replace github.com/cosmos/cosmos-sdk => ../../. +replace ( + cosmossdk.io/core/testing => ../../core/testing + github.com/cosmos/cosmos-sdk => ../../. +) // TODO remove post spinning out all modules replace cosmossdk.io/x/staking => ../staking diff --git a/x/bank/go.sum b/x/bank/go.sum index 0d5a1827a617..31c68d442b91 100644 --- a/x/bank/go.sum +++ b/x/bank/go.sum @@ -10,8 +10,6 @@ cosmossdk.io/collections v1.0.0-rc.1 h1:Mzv0YKZJ6aloy4oSnMnyl8b6PtM2dTdDlzRR/079 cosmossdk.io/collections v1.0.0-rc.1/go.mod h1:nOgrEpyMFOWBy8QmSbq/T6Tgtm2IyOFvxDRWk+DI97k= cosmossdk.io/core v1.0.0-alpha.6 h1:5ukC4JcQKmemLQXcAgu/QoOvJI50hpBkIIg4ZT2EN8E= cosmossdk.io/core v1.0.0-alpha.6/go.mod h1:3u9cWq1FAVtiiCrDPpo4LhR+9V6k/ycSG4/Y/tREWCY= -cosmossdk.io/core/testing v0.0.1 h1:gYCTaftcRrz+HoNXmK7r9KgbG1jgBJ8pNzm/Pa/erFQ= -cosmossdk.io/core/testing v0.0.1/go.mod h1:2VDNz/25qtxgPa0+j8LW5e8Ev/xObqoJA7QuJS9/wIQ= cosmossdk.io/depinject v1.1.0 h1:wLan7LG35VM7Yo6ov0jId3RHWCGRhe8E8bsuARorl5E= cosmossdk.io/depinject v1.1.0/go.mod h1:kkI5H9jCGHeKeYWXTqYdruogYrEeWvBQCw1Pj4/eCFI= cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0= diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index 4878bf24ce50..45eefcbbda55 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -760,7 +760,7 @@ func (suite *KeeperTestSuite) TestGRPCDenomOwners() { for name, tc := range testCases { suite.Run(name, func() { - resp, err := suite.queryClient.DenomOwners(gocontext.Background(), tc.req) + resp, err := suite.queryClient.DenomOwners(suite.ctx, tc.req) if tc.expPass { suite.NoError(err) suite.NotNil(resp) @@ -998,7 +998,7 @@ func (suite *KeeperTestSuite) TestGRPCDenomOwnersByQuery() { for name, tc := range testCases { suite.Run(name, func() { - resp, err := suite.queryClient.DenomOwnersByQuery(gocontext.Background(), tc.req) + resp, err := suite.queryClient.DenomOwnersByQuery(suite.ctx, tc.req) if tc.expPass { suite.NoError(err) suite.NotNil(resp) diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index e9f5bd0f645d..ad0d864fc161 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -18,6 +18,7 @@ import ( "cosmossdk.io/core/header" coretesting "cosmossdk.io/core/testing" errorsmod "cosmossdk.io/errors" + "cosmossdk.io/log" "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/bank/keeper" @@ -27,7 +28,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" "github.com/cosmos/cosmos-sdk/runtime" - "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -112,12 +112,13 @@ func addIBCMetadata(ctx context.Context, k keeper.BaseKeeper) { type KeeperTestSuite struct { suite.Suite - ctx context.Context + ctx coretesting.TestContext + env coretesting.TestEnvironment bankKeeper keeper.BaseKeeper addrCdc address.Codec authKeeper *banktestutil.MockAccountKeeper - queryClient banktypes.QueryClient + queryClient banktypes.QueryServer msgServer banktypes.MsgServer encCfg moduletestutil.TestEncodingConfig @@ -128,12 +129,22 @@ func TestKeeperTestSuite(t *testing.T) { } func (suite *KeeperTestSuite) SetupTest() { - key := storetypes.NewKVStoreKey(banktypes.StoreKey) - testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) - ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) + //key := storetypes.NewKVStoreKey(banktypes.StoreKey) + //testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) + //ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}) - env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) + testEnironmentConfig := coretesting.TestEnvironmentConfig{ + ModuleName: banktypes.ModuleName, + Logger: log.NewNopLogger(), + MsgRouter: nil, + QueryRouter: nil, + } + + newCtx, newEnv := coretesting.NewTestEnvironment(testEnironmentConfig) + newCtx = newCtx.WithHeaderInfo(header.Info{Time: time.Now()}) + // env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) + ctx := newCtx ac := codectestutil.CodecOptions{}.GetAddressCodec() addr, err := ac.BytesToString(accAddrs[4]) @@ -145,11 +156,11 @@ func (suite *KeeperTestSuite) SetupTest() { ctrl := gomock.NewController(suite.T()) authKeeper := banktestutil.NewMockAccountKeeper(ctrl) authKeeper.EXPECT().AddressCodec().Return(ac).AnyTimes() - suite.ctx = ctx + suite.ctx = newCtx suite.authKeeper = authKeeper suite.addrCdc = ac suite.bankKeeper = keeper.NewBaseKeeper( - env, + newEnv.Environment(), encCfg.Codec, suite.authKeeper, map[string]bool{addr: true}, @@ -162,13 +173,12 @@ func (suite *KeeperTestSuite) SetupTest() { banktypes.RegisterInterfaces(encCfg.InterfaceRegistry) - queryHelper := baseapp.NewQueryServerTestHelper(ctx, encCfg.InterfaceRegistry) - banktypes.RegisterQueryServer(queryHelper, suite.bankKeeper) - queryClient := banktypes.NewQueryClient(queryHelper) + queryServer := keeper.NewQuerier(&suite.bankKeeper) - suite.queryClient = queryClient + suite.queryClient = queryServer suite.msgServer = keeper.NewMsgServerImpl(suite.bankKeeper) suite.encCfg = encCfg + suite.env = newEnv } func (suite *KeeperTestSuite) mockQueryClient(ctx sdk.Context) banktypes.QueryClient { @@ -1403,7 +1413,7 @@ func (suite *KeeperTestSuite) TestMsgSendEvents() { } func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { - ctx := sdk.UnwrapSDKContext(suite.ctx) + ctx := suite.ctx require := suite.Require() acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) @@ -1431,7 +1441,7 @@ func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { suite.authKeeper.EXPECT().GetAccount(suite.ctx, accAddrs[0]).Return(acc0) require.Error(suite.bankKeeper.InputOutputCoins(ctx, input, outputs)) - events := ctx.EventManager().ABCIEvents() + events := suite.env.MemEventsService().GetEvents(suite.ctx) require.Equal(0, len(events)) // Set addr's coins but not accAddrs[1]'s coins @@ -1441,7 +1451,7 @@ func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { suite.mockInputOutputCoins([]sdk.AccountI{acc0}, accAddrs[2:4]) require.NoError(suite.bankKeeper.InputOutputCoins(ctx, input, outputs)) - events = ctx.EventManager().ABCIEvents() + events = suite.env.MemEventsService().GetEvents(suite.ctx) require.Equal(10, len(events)) // 10 events because account funding causes extra minting + coin_spent + coin_recv events // Set addr's coins and accAddrs[1]'s coins @@ -1456,7 +1466,7 @@ func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { suite.mockInputOutputCoins([]sdk.AccountI{acc0}, accAddrs[2:4]) require.NoError(suite.bankKeeper.InputOutputCoins(ctx, input, outputs)) - events = ctx.EventManager().ABCIEvents() + events = suite.env.MemEventsService().GetEvents(suite.ctx) require.Equal(25, len(events)) // 25 due to account funding + coin_spent + coin_recv events event1 := coreevent.Event{ @@ -1485,21 +1495,29 @@ func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { require.Equal(event1.Type, events[22].Type) attrs1, err := event1.Attributes() require.NoError(err) + + attrs, err := events[22].Attributes() + require.NoError(err) + for i := range attrs1 { - require.Equal(attrs1[i].Key, events[22].Attributes[i].Key) - require.Equal(attrs1[i].Value, events[22].Attributes[i].Value) + require.Equal(attrs1[i].Key, attrs[i].Key) + require.Equal(attrs1[i].Value, attrs[i].Value) } require.Equal(event2.Type, events[24].Type) attrs2, err := event2.Attributes() require.NoError(err) + + attrs, err = events[24].Attributes() + require.NoError(err) + for i := range attrs2 { - require.Equal(attrs2[i].Key, events[24].Attributes[i].Key) - require.Equal(attrs2[i].Value, events[24].Attributes[i].Value) + require.Equal(attrs2[i].Key, attrs[i].Key) + require.Equal(attrs2[i].Value, attrs[i].Value) } } func (suite *KeeperTestSuite) TestSpendableCoins() { - ctx := sdk.UnwrapSDKContext(suite.ctx) + ctx := suite.ctx require := suite.Require() now := time.Now() endTime := now.Add(24 * time.Hour) @@ -1539,7 +1557,7 @@ func (suite *KeeperTestSuite) TestSpendableCoins() { suite.Require().NoError(err) // Go back to the suite's context since mockFundAccount uses that; FundAccount would fail for bad mocking otherwise. - ctx = sdk.UnwrapSDKContext(suite.ctx) + ctx = suite.ctx suite.mockFundAccount(accAddrs[2]) require.NoError(banktestutil.FundAccount(ctx, suite.bankKeeper, accAddrs[2], balanceCoins2)) suite.mockSpendableCoins(ctx, vacc2) @@ -1691,7 +1709,7 @@ func (suite *KeeperTestSuite) TestPeriodicVestingAccountReceive() { } func (suite *KeeperTestSuite) TestDelegateCoins() { - ctx := sdk.UnwrapSDKContext(suite.ctx) + ctx := suite.ctx require := suite.Require() now := time.Now() endTime := now.Add(24 * time.Hour) @@ -1701,7 +1719,7 @@ func (suite *KeeperTestSuite) TestDelegateCoins() { acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) acc1 := authtypes.NewBaseAccountWithAddress(accAddrs[1]) - vacc, err := vesting.NewContinuousVestingAccount(acc0, origCoins, ctx.HeaderInfo().Time.Unix(), endTime.Unix()) + vacc, err := vesting.NewContinuousVestingAccount(acc0, origCoins, suite.env.HeaderService().HeaderInfo(suite.ctx).Time.Unix(), endTime.Unix()) suite.Require().NoError(err) suite.mockFundAccount(accAddrs[0]) @@ -1917,34 +1935,36 @@ func (suite *KeeperTestSuite) TestBalanceTrackingEvents() { balances := make(map[string]sdk.Coins) - ctx := sdk.UnwrapSDKContext(suite.ctx) + events := suite.env.MemEventsService().GetEvents(suite.ctx) - for _, e := range ctx.EventManager().ABCIEvents() { + for _, e := range events { + attributes, err := e.Attributes() + suite.Require().NoError(err) switch e.Type { case banktypes.EventTypeCoinBurn: - burnedCoins, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) + burnedCoins, err := sdk.ParseCoinsNormalized(attributes[1].Value) require.NoError(err) supply = supply.Sub(burnedCoins...) case banktypes.EventTypeCoinMint: - mintedCoins, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) + mintedCoins, err := sdk.ParseCoinsNormalized(attributes[1].Value) require.NoError(err) supply = supply.Add(mintedCoins...) case banktypes.EventTypeCoinSpent: - coinsSpent, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) + coinsSpent, err := sdk.ParseCoinsNormalized(attributes[1].Value) require.NoError(err) - _, err = suite.addrCdc.StringToBytes(e.Attributes[0].Value) + _, err = suite.addrCdc.StringToBytes(attributes[0].Value) require.NoError(err) - balances[e.Attributes[0].Value] = balances[e.Attributes[0].Value].Sub(coinsSpent...) + balances[attributes[0].Value] = balances[attributes[0].Value].Sub(coinsSpent...) case banktypes.EventTypeCoinReceived: - coinsRecv, err := sdk.ParseCoinsNormalized(e.Attributes[1].Value) + coinsRecv, err := sdk.ParseCoinsNormalized(attributes[1].Value) require.NoError(err) - _, err = suite.addrCdc.StringToBytes(e.Attributes[0].Value) + _, err = suite.addrCdc.StringToBytes(attributes[0].Value) require.NoError(err) - balances[e.Attributes[0].Value] = balances[e.Attributes[0].Value].Add(coinsRecv...) + balances[attributes[0].Value] = balances[attributes[0].Value].Add(coinsRecv...) } } From 46a30d37c924d1dd73f303dfb13dd6096ce01a80 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 17:34:26 -0500 Subject: [PATCH 08/24] bank --- x/bank/keeper/grpc_query_test.go | 62 +++++++++++++++++--------------- x/bank/keeper/keeper_test.go | 32 ++++++++--------- 2 files changed, 47 insertions(+), 47 deletions(-) diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index 45eefcbbda55..c8bd5096d50c 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -1,7 +1,6 @@ package keeper_test import ( - gocontext "context" "fmt" "time" @@ -84,7 +83,7 @@ func (suite *KeeperTestSuite) TestQueryBalance() { for _, tc := range testCases { suite.Run(tc.name, func() { - res, err := queryClient.Balance(gocontext.Background(), tc.req) + res, err := queryClient.Balance(ctx, tc.req) if tc.expectErrMsg == "" { suite.Require().NoError(err) suite.Require().NotNil(res) @@ -102,7 +101,7 @@ func (suite *KeeperTestSuite) TestQueryBalance() { func (suite *KeeperTestSuite) TestQueryAllBalances() { ctx, queryClient := suite.ctx, suite.queryClient _, _, addr := testdata.KeyTestPubAddr() - _, err := queryClient.AllBalances(gocontext.Background(), &types.QueryAllBalancesRequest{}) + _, err := queryClient.AllBalances(ctx, &types.QueryAllBalancesRequest{}) suite.Require().Error(err) addrStr, err := suite.addrCdc.BytesToString(addr) @@ -114,7 +113,7 @@ func (suite *KeeperTestSuite) TestQueryAllBalances() { CountTotal: false, } req := types.NewQueryAllBalancesRequest(addrStr, pageReq, false) - res, err := queryClient.AllBalances(gocontext.Background(), req) + res, err := queryClient.AllBalances(ctx, req) suite.Require().NoError(err) suite.Require().NotNil(res) suite.True(res.Balances.IsZero()) @@ -130,7 +129,7 @@ func (suite *KeeperTestSuite) TestQueryAllBalances() { addIBCMetadata(ctx, suite.bankKeeper) - res, err = queryClient.AllBalances(gocontext.Background(), req) + res, err = queryClient.AllBalances(ctx, req) suite.Require().NoError(err) suite.Require().NotNil(res) suite.Equal(res.Balances.Len(), 1) @@ -143,7 +142,7 @@ func (suite *KeeperTestSuite) TestQueryAllBalances() { CountTotal: true, } req = types.NewQueryAllBalancesRequest(addrStr, pageReq, false) - res, err = queryClient.AllBalances(gocontext.Background(), req) + res, err = queryClient.AllBalances(ctx, req) suite.Require().NoError(err) suite.Equal(res.Balances.Len(), 1) suite.NotNil(res.Pagination.NextKey) @@ -157,7 +156,7 @@ func (suite *KeeperTestSuite) TestQueryAllBalances() { CountTotal: true, } req = types.NewQueryAllBalancesRequest(addrStr, pageReq, false) - res, err = queryClient.AllBalances(gocontext.Background(), req) + res, err = queryClient.AllBalances(ctx, req) suite.Require().NoError(err) suite.Equal(res.Balances.Len(), 1) suite.Equal(res.Balances[0].Denom, ibcCoins.Denom) @@ -169,7 +168,7 @@ func (suite *KeeperTestSuite) TestQueryAllBalances() { CountTotal: true, } req = types.NewQueryAllBalancesRequest(addrStr, pageReq, true) - res, err = queryClient.AllBalances(gocontext.Background(), req) + res, err = queryClient.AllBalances(ctx, req) suite.Require().NoError(err) suite.Equal(res.Balances.Len(), 1) suite.Equal(res.Balances[0].Denom, ibcPath+"/"+ibcBaseDenom) @@ -181,9 +180,9 @@ func (suite *KeeperTestSuite) TestSpendableBalances() { addrStr, err := suite.addrCdc.BytesToString(addr) suite.Require().NoError(err) - ctx := sdk.UnwrapSDKContext(suite.ctx) + ctx := suite.ctx ctx = ctx.WithHeaderInfo(header.Info{Time: time.Now()}) - queryClient := suite.mockQueryClient(ctx) + queryClient := suite.queryClient _, err = queryClient.SpendableBalances(ctx, &types.QuerySpendableBalancesRequest{}) suite.Require().Error(err) @@ -205,12 +204,14 @@ func (suite *KeeperTestSuite) TestSpendableBalances() { fooCoins := newFooCoin(50) barCoins := newBarCoin(30) + currentBlockTime := suite.env.HeaderService().HeaderInfo(ctx).Time + origCoins := sdk.NewCoins(fooCoins, barCoins) vacc, err := vestingtypes.NewContinuousVestingAccount( acc, sdk.NewCoins(fooCoins), - ctx.HeaderInfo().Time.Unix(), - ctx.HeaderInfo().Time.Add(time.Hour).Unix(), + currentBlockTime.Unix(), + currentBlockTime.Add(time.Hour).Unix(), ) suite.Require().NoError(err) @@ -218,8 +219,8 @@ func (suite *KeeperTestSuite) TestSpendableBalances() { suite.Require().NoError(testutil.FundAccount(suite.ctx, suite.bankKeeper, addr, origCoins)) // move time forward for some tokens to vest - ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(30 * time.Minute)}) - queryClient = suite.mockQueryClient(ctx) + ctx = ctx.WithHeaderInfo(header.Info{Time: currentBlockTime.Add(30 * time.Minute)}) + queryClient = suite.queryClient suite.mockSpendableCoins(ctx, vacc) res, err = queryClient.SpendableBalances(ctx, req) @@ -233,10 +234,10 @@ func (suite *KeeperTestSuite) TestSpendableBalances() { func (suite *KeeperTestSuite) TestSpendableBalanceByDenom() { _, _, addr := testdata.KeyTestPubAddr() + ctx := suite.ctx - ctx := sdk.UnwrapSDKContext(suite.ctx) ctx = ctx.WithHeaderInfo(header.Info{Time: time.Now()}) - queryClient := suite.mockQueryClient(ctx) + queryClient := suite.queryClient _, err := queryClient.SpendableBalanceByDenom(ctx, &types.QuerySpendableBalanceByDenomRequest{}) suite.Require().Error(err) @@ -256,12 +257,14 @@ func (suite *KeeperTestSuite) TestSpendableBalanceByDenom() { fooCoins := newFooCoin(100) barCoins := newBarCoin(30) + currentBlockTime := suite.env.HeaderService().HeaderInfo(ctx).Time + origCoins := sdk.NewCoins(fooCoins, barCoins) vacc, err := vestingtypes.NewContinuousVestingAccount( acc, sdk.NewCoins(fooCoins), - ctx.HeaderInfo().Time.Unix(), - ctx.HeaderInfo().Time.Add(time.Hour).Unix(), + currentBlockTime.Unix(), + currentBlockTime.Add(time.Hour).Unix(), ) suite.Require().NoError(err) @@ -269,8 +272,8 @@ func (suite *KeeperTestSuite) TestSpendableBalanceByDenom() { suite.Require().NoError(testutil.FundAccount(suite.ctx, suite.bankKeeper, addr, origCoins)) // move time forward for half of the tokens to vest - ctx = ctx.WithHeaderInfo(header.Info{Time: ctx.HeaderInfo().Time.Add(30 * time.Minute)}) - queryClient = suite.mockQueryClient(ctx) + ctx = ctx.WithHeaderInfo(header.Info{Time: currentBlockTime.Add(30 * time.Minute)}) + queryClient = suite.queryClient // check fooCoins first, it has some vested and some vesting suite.mockSpendableCoins(ctx, vacc) @@ -290,7 +293,7 @@ func (suite *KeeperTestSuite) TestSpendableBalanceByDenom() { func (suite *KeeperTestSuite) TestQueryTotalSupply() { ctx, queryClient := suite.ctx, suite.queryClient - res, err := queryClient.TotalSupply(gocontext.Background(), &types.QueryTotalSupplyRequest{}) + res, err := queryClient.TotalSupply(ctx, &types.QueryTotalSupplyRequest{}) suite.Require().NoError(err) suite.Require().NotNil(res) genesisSupply := res.Supply @@ -299,7 +302,7 @@ func (suite *KeeperTestSuite) TestQueryTotalSupply() { suite.mockMintCoins(mintAcc) suite.Require().NoError(suite.bankKeeper.MintCoins(ctx, types.MintModuleName, testCoins)) - res, err = queryClient.TotalSupply(gocontext.Background(), &types.QueryTotalSupplyRequest{}) + res, err = queryClient.TotalSupply(ctx, &types.QueryTotalSupplyRequest{}) suite.Require().NoError(err) suite.Require().NotNil(res) @@ -318,32 +321,33 @@ func (suite *KeeperTestSuite) TestQueryTotalSupplyOf() { suite.mockMintCoins(mintAcc) suite.Require().NoError(suite.bankKeeper.MintCoins(ctx, types.MintModuleName, expectedTotalSupply)) - _, err := queryClient.SupplyOf(gocontext.Background(), &types.QuerySupplyOfRequest{}) + _, err := queryClient.SupplyOf(ctx, &types.QuerySupplyOfRequest{}) suite.Require().Error(err) - res, err := queryClient.SupplyOf(gocontext.Background(), &types.QuerySupplyOfRequest{Denom: test1Supply.Denom}) + res, err := queryClient.SupplyOf(ctx, &types.QuerySupplyOfRequest{Denom: test1Supply.Denom}) suite.Require().NoError(err) suite.Require().NotNil(res) suite.Require().Equal(test1Supply, res.Amount) // total supply bogus denom - res, err = queryClient.SupplyOf(gocontext.Background(), &types.QuerySupplyOfRequest{Denom: "bogus"}) + res, err = queryClient.SupplyOf(ctx, &types.QuerySupplyOfRequest{Denom: "bogus"}) suite.Require().NoError(err) suite.Require().NotNil(res) suite.Require().Equal(sdk.NewInt64Coin("bogus", 0), res.Amount) } func (suite *KeeperTestSuite) TestQueryParams() { - res, err := suite.queryClient.Params(gocontext.Background(), &types.QueryParamsRequest{}) + ctx, queryClient := suite.ctx, suite.queryClient + res, err := queryClient.Params(ctx, &types.QueryParamsRequest{}) suite.Require().NoError(err) suite.Require().NotNil(res) - suite.Require().Equal(suite.bankKeeper.GetParams(suite.ctx), res.GetParams()) + suite.Require().Equal(suite.bankKeeper.GetParams(ctx), res.GetParams()) } func (suite *KeeperTestSuite) TestQueryDenomsMetadata() { var ( req *types.QueryDenomsMetadataRequest - expMetadata = []types.Metadata(nil) + expMetadata = []types.Metadata{} ) testCases := []struct { @@ -892,7 +896,7 @@ func (suite *KeeperTestSuite) TestQuerySendEnabled() { for _, tc := range tests { suite.Run(tc.name, func() { - resp, err := suite.queryClient.SendEnabled(gocontext.Background(), tc.req) + resp, err := suite.queryClient.SendEnabled(ctx, tc.req) suite.Require().NoError(err) if !suite.Assert().Equal(tc.exp, resp) { if !suite.Assert().Len(resp.SendEnabled, len(tc.exp.SendEnabled)) { diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index ad0d864fc161..16c852d9c1e1 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -25,7 +25,6 @@ import ( banktestutil "cosmossdk.io/x/bank/testutil" banktypes "cosmossdk.io/x/bank/types" - "github.com/cosmos/cosmos-sdk/baseapp" codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" @@ -181,12 +180,6 @@ func (suite *KeeperTestSuite) SetupTest() { suite.env = newEnv } -func (suite *KeeperTestSuite) mockQueryClient(ctx sdk.Context) banktypes.QueryClient { - queryHelper := baseapp.NewQueryServerTestHelper(ctx, suite.encCfg.InterfaceRegistry) - banktypes.RegisterQueryServer(queryHelper, suite.bankKeeper) - return banktypes.NewQueryClient(queryHelper) -} - func (suite *KeeperTestSuite) mockMintCoins(moduleAcc *authtypes.ModuleAccount) { suite.authKeeper.EXPECT().GetModuleAccount(suite.ctx, moduleAcc.Name).Return(moduleAcc) } @@ -230,7 +223,7 @@ func (suite *KeeperTestSuite) mockValidateBalance(acc sdk.AccountI) { suite.authKeeper.EXPECT().GetAccount(suite.ctx, acc.GetAddress()).Return(acc) } -func (suite *KeeperTestSuite) mockSpendableCoins(ctx sdk.Context, acc sdk.AccountI) { +func (suite *KeeperTestSuite) mockSpendableCoins(ctx context.Context, acc sdk.AccountI) { suite.authKeeper.EXPECT().GetAccount(ctx, acc.GetAddress()).Return(acc) } @@ -1399,16 +1392,19 @@ func (suite *KeeperTestSuite) TestMsgSendEvents() { }, } - ctx := sdk.UnwrapSDKContext(suite.ctx) + events := suite.env.MemEventsService().GetEvents(suite.ctx) // events are shifted due to the funding account events - events := ctx.EventManager().Events() require.Equal(8, len(events)) require.Equal(event1.Type, events[7].Type) attrs, err := event1.Attributes() require.NoError(err) + + attrs, err = events[7].Attributes() + require.NoError(err) + for i := range attrs { - require.Equal(attrs[i].Key, events[7].Attributes[i].Key) - require.Equal(attrs[i].Value, events[7].Attributes[i].Value) + require.Equal(attrs[i].Key, attrs[i].Key) + require.Equal(attrs[i].Value, attrs[i].Value) } } @@ -1573,7 +1569,7 @@ func (suite *KeeperTestSuite) TestSpendableCoins() { } func (suite *KeeperTestSuite) TestVestingAccountSend() { - ctx := sdk.UnwrapSDKContext(suite.ctx) + ctx := suite.ctx require := suite.Require() now := time.Now() endTime := now.Add(24 * time.Hour) @@ -1603,7 +1599,7 @@ func (suite *KeeperTestSuite) TestVestingAccountSend() { } func (suite *KeeperTestSuite) TestPeriodicVestingAccountSend() { - ctx := sdk.UnwrapSDKContext(suite.ctx) + ctx := suite.ctx require := suite.Require() now := time.Now() origCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 100)) @@ -1638,7 +1634,7 @@ func (suite *KeeperTestSuite) TestPeriodicVestingAccountSend() { } func (suite *KeeperTestSuite) TestVestingAccountReceive() { - ctx := sdk.UnwrapSDKContext(suite.ctx) + ctx := suite.ctx require := suite.Require() now := time.Now() endTime := now.Add(24 * time.Hour) @@ -1671,7 +1667,7 @@ func (suite *KeeperTestSuite) TestVestingAccountReceive() { } func (suite *KeeperTestSuite) TestPeriodicVestingAccountReceive() { - ctx := sdk.UnwrapSDKContext(suite.ctx) + ctx := suite.ctx require := suite.Require() now := time.Now() @@ -1767,7 +1763,7 @@ func (suite *KeeperTestSuite) TestDelegateCoins_Invalid() { } func (suite *KeeperTestSuite) TestUndelegateCoins() { - ctx := sdk.UnwrapSDKContext(suite.ctx) + ctx := suite.ctx require := suite.Require() now := time.Now() endTime := now.Add(24 * time.Hour) @@ -1777,7 +1773,7 @@ func (suite *KeeperTestSuite) TestUndelegateCoins() { acc0 := authtypes.NewBaseAccountWithAddress(accAddrs[0]) acc1 := authtypes.NewBaseAccountWithAddress(accAddrs[1]) - vacc, err := vesting.NewContinuousVestingAccount(acc0, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix()) + vacc, err := vesting.NewContinuousVestingAccount(acc0, origCoins, suite.env.HeaderService().HeaderInfo(ctx).Time.Unix(), endTime.Unix()) suite.Require().NoError(err) suite.mockFundAccount(accAddrs[0]) From 89e5b265f6e92eaec7e9117f1a1478fd1358bbc2 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 17:38:25 -0500 Subject: [PATCH 09/24] no more sdk.context --- x/bank/types/restrictions_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/x/bank/types/restrictions_test.go b/x/bank/types/restrictions_test.go index 9f0813b2ab64..bddd05161026 100644 --- a/x/bank/types/restrictions_test.go +++ b/x/bank/types/restrictions_test.go @@ -83,7 +83,7 @@ func (s *MintingRestrictionTestHelper) TestActual(t *testing.T, tp *MintingRestr } else { require.NotNil(t, actual, "resulting MintingRestrictionFn") s.Calls = s.Calls[:0] - err := actual(sdk.Context{}, tp.Coins) + err := actual(context.Background(), tp.Coins) if len(tp.ExpErr) != 0 { assert.EqualError(t, err, tp.ExpErr, "composite MintingRestrictionFn output error") } else { @@ -389,7 +389,7 @@ func TestComposeMintingRestrictions(t *testing.T) { func TestNoOpMintingRestrictionFn(t *testing.T) { var err error testFunc := func() { - err = types.NoOpMintingRestrictionFn(sdk.Context{}, sdk.Coins{}) + err = types.NoOpMintingRestrictionFn(context.Background(), sdk.Coins{}) } require.NotPanics(t, testFunc, "NoOpMintingRestrictionFn") assert.NoError(t, err, "NoOpSendRestrictionFn error") @@ -483,7 +483,7 @@ func (s *SendRestrictionTestHelper) TestActual(t *testing.T, tp *SendRestriction } else { require.NotNil(t, actual, "resulting SendRestrictionFn") s.Calls = s.Calls[:0] - addr, err := actual(sdk.Context{}, tp.FromAddr, tp.ToAddr, tp.Coins) + addr, err := actual(context.Background(), tp.FromAddr, tp.ToAddr, tp.Coins) if len(tp.ExpErr) != 0 { assert.EqualError(t, err, tp.ExpErr, "composite SendRestrictionFn output error") } else { @@ -912,7 +912,7 @@ func TestNoOpSendRestrictionFn(t *testing.T) { var addr sdk.AccAddress var err error testFunc := func() { - addr, err = types.NoOpSendRestrictionFn(sdk.Context{}, sdk.AccAddress("first_addr"), expAddr, sdk.Coins{}) + addr, err = types.NoOpSendRestrictionFn(context.Background(), sdk.AccAddress("first_addr"), expAddr, sdk.Coins{}) } require.NotPanics(t, testFunc, "NoOpSendRestrictionFn") assert.NoError(t, err, "NoOpSendRestrictionFn error") From 05a85771730b92888b6bcf85450e64f701af7b97 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 17:53:44 -0500 Subject: [PATCH 10/24] working --- core/testing/context.go | 6 ++++-- core/testing/environment.go | 9 ++++++++- x/bank/types/send_authorization_test.go | 27 +++++++++---------------- 3 files changed, 22 insertions(+), 20 deletions(-) diff --git a/core/testing/context.go b/core/testing/context.go index a8a3c3ec4255..d7688e7a9bad 100644 --- a/core/testing/context.go +++ b/core/testing/context.go @@ -26,6 +26,8 @@ func Context() TestContext { protoEvents: map[string][]transaction.Msg{}, header: header.Info{}, execMode: transaction.ExecModeFinalize, + gasConfig: gas.GasConfig{}, + gasMeter: nil, } return TestContext{ @@ -60,7 +62,7 @@ func (t TestContext) WithHeaderInfo(info header.Info) TestContext { } // WithExecMode sets the exec mode on a testing ctx and returns the updated ctx. -func (t TestContext) WithExecMode(mode transaction.ExecMode) context.Context { +func (t TestContext) WithExecMode(mode transaction.ExecMode) TestContext { dummy := unwrap(t.ctx) dummy.execMode = mode @@ -70,7 +72,7 @@ func (t TestContext) WithExecMode(mode transaction.ExecMode) context.Context { } // WithGas sets the gas config and meter on a testing ctx and returns the updated ctx. -func (t TestContext) WithGas(gasConfig gas.GasConfig, gasMeter gas.Meter) context.Context { +func (t TestContext) WithGas(gasConfig gas.GasConfig, gasMeter gas.Meter) TestContext { dummy := unwrap(t.ctx) dummy.gasConfig = gasConfig dummy.gasMeter = gasMeter diff --git a/core/testing/environment.go b/core/testing/environment.go index 32cec6e1290d..a7b8b82eaf70 100644 --- a/core/testing/environment.go +++ b/core/testing/environment.go @@ -1,7 +1,10 @@ package coretesting import ( + "context" + appmodulev2 "cosmossdk.io/core/appmodule/v2" + corecontext "cosmossdk.io/core/context" corelog "cosmossdk.io/core/log" "cosmossdk.io/core/router" "cosmossdk.io/core/store" @@ -26,7 +29,7 @@ func NewTestEnvironment(cfg TestEnvironmentConfig) (TestContext, TestEnvironment memEventService := EventsService(ctx, cfg.ModuleName) memHeaderService := MemHeaderService{} - return ctx, TestEnvironment{ + env := TestEnvironment{ env: appmodulev2.Environment{ Logger: cfg.Logger, BranchService: nil, @@ -42,6 +45,10 @@ func NewTestEnvironment(cfg TestEnvironmentConfig) (TestContext, TestEnvironment memEventsService: memEventService, memHeaderService: memHeaderService, } + + // set internal context to point to environment + ctx.ctx = context.WithValue(ctx.ctx, corecontext.EnvironmentContextKey, env.env) + return ctx, env } func (env TestEnvironment) MemEventsService() MemEventsService { diff --git a/x/bank/types/send_authorization_test.go b/x/bank/types/send_authorization_test.go index bb12f5d2a5f7..cc61b60a1ace 100644 --- a/x/bank/types/send_authorization_test.go +++ b/x/bank/types/send_authorization_test.go @@ -2,21 +2,18 @@ package types_test import ( "context" + "cosmossdk.io/log" "fmt" "testing" "github.com/stretchr/testify/require" - appmodulev2 "cosmossdk.io/core/appmodule/v2" - corecontext "cosmossdk.io/core/context" coregas "cosmossdk.io/core/gas" - coreheader "cosmossdk.io/core/header" + coretesting "cosmossdk.io/core/testing" sdkmath "cosmossdk.io/math" - storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/bank/types" codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" - "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -29,17 +26,11 @@ var ( unknownAddrStr = "cosmos1ta047h6lw4hxkmn0wah97h6lta0sml880l" ) -type headerService struct{} - -func (h headerService) HeaderInfo(ctx context.Context) coreheader.Info { - return sdk.UnwrapSDKContext(ctx).HeaderInfo() -} - type mockGasService struct { coregas.Service } -func (m mockGasService) GasMeter(ctx context.Context) coregas.Meter { +func (m mockGasService) GasMeter(_ context.Context) coregas.Meter { return mockGasMeter{} } @@ -53,11 +44,13 @@ func (m mockGasMeter) Consume(amount coregas.Gas, descriptor string) error { func TestSendAuthorization(t *testing.T) { ac := codectestutil.CodecOptions{}.GetAddressCodec() - sdkCtx := testutil.DefaultContextWithDB(t, storetypes.NewKVStoreKey(types.StoreKey), storetypes.NewTransientStoreKey("transient_test")).Ctx.WithHeaderInfo(coreheader.Info{}) - ctx := context.WithValue(sdkCtx.Context(), corecontext.EnvironmentContextKey, appmodulev2.Environment{ - HeaderService: headerService{}, - GasService: mockGasService{}, - }) + cfg := coretesting.TestEnvironmentConfig{ + ModuleName: "bank", + Logger: log.NewNopLogger(), + } + + ctx, _ := coretesting.NewTestEnvironment(cfg) + ctx = ctx.WithGas(coregas.GasConfig{}, mockGasMeter{}) allowList := make([]sdk.AccAddress, 1) allowList[0] = toAddr From f827e73124a1dbb9951c2f4518211b09f4072546 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 18:00:10 -0500 Subject: [PATCH 11/24] lint fixes --- core/testing/gas.go | 1 + core/testing/transaction.go | 1 + x/bank/keeper/keeper_test.go | 26 ++++++++++--------------- x/bank/types/send_authorization_test.go | 13 ++----------- 4 files changed, 14 insertions(+), 27 deletions(-) diff --git a/core/testing/gas.go b/core/testing/gas.go index 89b64a140a06..1aca2a784ade 100644 --- a/core/testing/gas.go +++ b/core/testing/gas.go @@ -2,6 +2,7 @@ package coretesting import ( "context" + "cosmossdk.io/core/gas" ) diff --git a/core/testing/transaction.go b/core/testing/transaction.go index eb53622b923b..7ff46d6f1016 100644 --- a/core/testing/transaction.go +++ b/core/testing/transaction.go @@ -2,6 +2,7 @@ package coretesting import ( "context" + "cosmossdk.io/core/transaction" ) diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 16c852d9c1e1..dc905715b3c3 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -128,11 +128,7 @@ func TestKeeperTestSuite(t *testing.T) { } func (suite *KeeperTestSuite) SetupTest() { - //key := storetypes.NewKVStoreKey(banktypes.StoreKey) - //testCtx := testutil.DefaultContextWithDB(suite.T(), key, storetypes.NewTransientStoreKey("transient_test")) - //ctx := testCtx.Ctx.WithHeaderInfo(header.Info{Time: time.Now()}) encCfg := moduletestutil.MakeTestEncodingConfig(codectestutil.CodecOptions{}) - testEnironmentConfig := coretesting.TestEnvironmentConfig{ ModuleName: banktypes.ModuleName, Logger: log.NewNopLogger(), @@ -140,10 +136,8 @@ func (suite *KeeperTestSuite) SetupTest() { QueryRouter: nil, } - newCtx, newEnv := coretesting.NewTestEnvironment(testEnironmentConfig) - newCtx = newCtx.WithHeaderInfo(header.Info{Time: time.Now()}) - // env := runtime.NewEnvironment(runtime.NewKVStoreService(key), coretesting.NewNopLogger()) - ctx := newCtx + ctx, env := coretesting.NewTestEnvironment(testEnironmentConfig) + ctx = ctx.WithHeaderInfo(header.Info{Time: time.Now()}) ac := codectestutil.CodecOptions{}.GetAddressCodec() addr, err := ac.BytesToString(accAddrs[4]) @@ -155,11 +149,11 @@ func (suite *KeeperTestSuite) SetupTest() { ctrl := gomock.NewController(suite.T()) authKeeper := banktestutil.NewMockAccountKeeper(ctrl) authKeeper.EXPECT().AddressCodec().Return(ac).AnyTimes() - suite.ctx = newCtx + suite.ctx = ctx suite.authKeeper = authKeeper suite.addrCdc = ac suite.bankKeeper = keeper.NewBaseKeeper( - newEnv.Environment(), + env.Environment(), encCfg.Codec, suite.authKeeper, map[string]bool{addr: true}, @@ -177,7 +171,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.queryClient = queryServer suite.msgServer = keeper.NewMsgServerImpl(suite.bankKeeper) suite.encCfg = encCfg - suite.env = newEnv + suite.env = env } func (suite *KeeperTestSuite) mockMintCoins(moduleAcc *authtypes.ModuleAccount) { @@ -1396,15 +1390,15 @@ func (suite *KeeperTestSuite) TestMsgSendEvents() { // events are shifted due to the funding account events require.Equal(8, len(events)) require.Equal(event1.Type, events[7].Type) - attrs, err := event1.Attributes() + attrs1, err := event1.Attributes() require.NoError(err) - attrs, err = events[7].Attributes() + attrs, err := events[7].Attributes() require.NoError(err) - for i := range attrs { - require.Equal(attrs[i].Key, attrs[i].Key) - require.Equal(attrs[i].Value, attrs[i].Value) + for i := range attrs1 { + require.Equal(attrs1[i].Key, attrs[i].Key) + require.Equal(attrs1[i].Value, attrs[i].Value) } } diff --git a/x/bank/types/send_authorization_test.go b/x/bank/types/send_authorization_test.go index cc61b60a1ace..8f84eb45bc76 100644 --- a/x/bank/types/send_authorization_test.go +++ b/x/bank/types/send_authorization_test.go @@ -1,8 +1,6 @@ package types_test import ( - "context" - "cosmossdk.io/log" "fmt" "testing" @@ -10,6 +8,7 @@ import ( coregas "cosmossdk.io/core/gas" coretesting "cosmossdk.io/core/testing" + "cosmossdk.io/log" sdkmath "cosmossdk.io/math" "cosmossdk.io/x/bank/types" @@ -26,19 +25,11 @@ var ( unknownAddrStr = "cosmos1ta047h6lw4hxkmn0wah97h6lta0sml880l" ) -type mockGasService struct { - coregas.Service -} - -func (m mockGasService) GasMeter(_ context.Context) coregas.Meter { - return mockGasMeter{} -} - type mockGasMeter struct { coregas.Meter } -func (m mockGasMeter) Consume(amount coregas.Gas, descriptor string) error { +func (m mockGasMeter) Consume(_ coregas.Gas, _ string) error { return nil } From 6c7dc2a1329a3b46bb1abd244bd8861fd9ab4af6 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 20 Dec 2024 18:01:23 -0500 Subject: [PATCH 12/24] format --- x/bank/v2/keeper/handlers.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x/bank/v2/keeper/handlers.go b/x/bank/v2/keeper/handlers.go index c9da64b9940c..9d36a241ca45 100644 --- a/x/bank/v2/keeper/handlers.go +++ b/x/bank/v2/keeper/handlers.go @@ -3,10 +3,11 @@ package keeper import ( "bytes" "context" - appmodulev2 "cosmossdk.io/core/appmodule/v2" "errors" "fmt" + appmodulev2 "cosmossdk.io/core/appmodule/v2" + "google.golang.org/grpc/codes" "google.golang.org/grpc/status" From 49560834cf1cad1ed94226030c351c9d1188d36c Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 3 Jan 2025 12:25:49 -0500 Subject: [PATCH 13/24] lint --- x/bank/v2/keeper/handlers.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/x/bank/v2/keeper/handlers.go b/x/bank/v2/keeper/handlers.go index 9d36a241ca45..fcd883e948da 100644 --- a/x/bank/v2/keeper/handlers.go +++ b/x/bank/v2/keeper/handlers.go @@ -6,11 +6,10 @@ import ( "errors" "fmt" - appmodulev2 "cosmossdk.io/core/appmodule/v2" - "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + appmodulev2 "cosmossdk.io/core/appmodule/v2" errorsmod "cosmossdk.io/errors" "cosmossdk.io/x/bank/v2/types" From c7bc69dad1a953a3d784679cffd9f3a76ed833c9 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Fri, 3 Jan 2025 12:32:13 -0500 Subject: [PATCH 14/24] tidy all --- x/bank/go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/bank/go.mod b/x/bank/go.mod index fa3680161159..4f9b06f71e77 100644 --- a/x/bank/go.mod +++ b/x/bank/go.mod @@ -8,7 +8,7 @@ require ( cosmossdk.io/core v1.0.0-alpha.6 cosmossdk.io/depinject v1.1.0 cosmossdk.io/errors v1.0.1 - cosmossdk.io/log v1.5.0 // indirect + cosmossdk.io/log v1.5.0 cosmossdk.io/math v1.4.0 cosmossdk.io/store v1.10.0-rc.1 github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect From d42ac1f1fe366a9b1c4f2e41c3a5b127a28e9108 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Mon, 6 Jan 2025 14:29:52 -0500 Subject: [PATCH 15/24] clean --- core/testing/context.go | 34 +++++-------------- core/testing/environment.go | 13 +++---- .../integration/distribution/genesis_test.go | 9 ++--- x/bank/keeper/keeper_test.go | 2 +- 4 files changed, 19 insertions(+), 39 deletions(-) diff --git a/core/testing/context.go b/core/testing/context.go index d7688e7a9bad..ec3248e6405e 100644 --- a/core/testing/context.go +++ b/core/testing/context.go @@ -2,8 +2,6 @@ package coretesting import ( "context" - "time" - "cosmossdk.io/core/event" "cosmossdk.io/core/gas" "cosmossdk.io/core/header" @@ -16,7 +14,7 @@ type dummyKey struct{} var _ context.Context = &TestContext{} type TestContext struct { - ctx context.Context + context.Context } func Context() TestContext { @@ -31,54 +29,38 @@ func Context() TestContext { } return TestContext{ - ctx: context.WithValue(context.Background(), dummyKey{}, dummy), + Context: context.WithValue(context.Background(), dummyKey{}, dummy), } } -func (t TestContext) Deadline() (deadline time.Time, ok bool) { - return t.ctx.Deadline() -} - -func (t TestContext) Done() <-chan struct{} { - return t.ctx.Done() -} - -func (t TestContext) Err() error { - return t.ctx.Err() -} - -func (t TestContext) Value(key any) any { - return t.ctx.Value(key) -} - // WithHeaderInfo sets the header on a testing ctx and returns the updated ctx. func (t TestContext) WithHeaderInfo(info header.Info) TestContext { - dummy := unwrap(t.ctx) + dummy := unwrap(t.Context) dummy.header = info return TestContext{ - ctx: context.WithValue(t.ctx, dummyKey{}, dummy), + Context: context.WithValue(t.Context, dummyKey{}, dummy), } } // WithExecMode sets the exec mode on a testing ctx and returns the updated ctx. func (t TestContext) WithExecMode(mode transaction.ExecMode) TestContext { - dummy := unwrap(t.ctx) + dummy := unwrap(t.Context) dummy.execMode = mode return TestContext{ - ctx: context.WithValue(t.ctx, dummyKey{}, dummy), + Context: context.WithValue(t.Context, dummyKey{}, dummy), } } // WithGas sets the gas config and meter on a testing ctx and returns the updated ctx. func (t TestContext) WithGas(gasConfig gas.GasConfig, gasMeter gas.Meter) TestContext { - dummy := unwrap(t.ctx) + dummy := unwrap(t.Context) dummy.gasConfig = gasConfig dummy.gasMeter = gasMeter return TestContext{ - ctx: context.WithValue(t.ctx, dummyKey{}, dummy), + Context: context.WithValue(t.Context, dummyKey{}, dummy), } } diff --git a/core/testing/environment.go b/core/testing/environment.go index a7b8b82eaf70..e3f50f6d014d 100644 --- a/core/testing/environment.go +++ b/core/testing/environment.go @@ -18,7 +18,8 @@ type TestEnvironmentConfig struct { } type TestEnvironment struct { - env appmodulev2.Environment + appmodulev2.Environment + memEventsService MemEventsService memHeaderService MemHeaderService } @@ -30,7 +31,7 @@ func NewTestEnvironment(cfg TestEnvironmentConfig) (TestContext, TestEnvironment memHeaderService := MemHeaderService{} env := TestEnvironment{ - env: appmodulev2.Environment{ + Environment: appmodulev2.Environment{ Logger: cfg.Logger, BranchService: nil, EventService: memEventService, @@ -47,7 +48,7 @@ func NewTestEnvironment(cfg TestEnvironmentConfig) (TestContext, TestEnvironment } // set internal context to point to environment - ctx.ctx = context.WithValue(ctx.ctx, corecontext.EnvironmentContextKey, env.env) + ctx.Context = context.WithValue(ctx.Context, corecontext.EnvironmentContextKey, env.Environment) return ctx, env } @@ -55,12 +56,8 @@ func (env TestEnvironment) MemEventsService() MemEventsService { return env.memEventsService } -func (env TestEnvironment) Environment() appmodulev2.Environment { - return env.env -} - func (env TestEnvironment) KVStoreService() store.KVStoreService { - return env.env.KVStoreService + return env.Environment.KVStoreService } func (env TestEnvironment) HeaderService() MemHeaderService { diff --git a/tests/integration/distribution/genesis_test.go b/tests/integration/distribution/genesis_test.go index a113341496ae..a7612713ae60 100644 --- a/tests/integration/distribution/genesis_test.go +++ b/tests/integration/distribution/genesis_test.go @@ -4,22 +4,23 @@ import ( "encoding/json" "testing" + abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" + "github.com/stretchr/testify/suite" + corestore "cosmossdk.io/core/store" coretesting "cosmossdk.io/core/testing" "cosmossdk.io/depinject" "cosmossdk.io/log" sdkmath "cosmossdk.io/math" + bankkeeper "cosmossdk.io/x/bank/keeper" "cosmossdk.io/x/distribution/keeper" "cosmossdk.io/x/distribution/types" stakingkeeper "cosmossdk.io/x/staking/keeper" - abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/runtime" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - bankkeeper "cosmossdk.io/x/bank/keeper" _ "github.com/cosmos/cosmos-sdk/x/auth" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" ) diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index dc905715b3c3..82bebe171a87 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -153,7 +153,7 @@ func (suite *KeeperTestSuite) SetupTest() { suite.authKeeper = authKeeper suite.addrCdc = ac suite.bankKeeper = keeper.NewBaseKeeper( - env.Environment(), + env.Environment, encCfg.Codec, suite.authKeeper, map[string]bool{addr: true}, From a6ffa04033ba05db262f03247abacb813770cb59 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Mon, 6 Jan 2025 15:55:39 -0500 Subject: [PATCH 16/24] use mocked query client --- core/testing/context.go | 1 + schema/appdata/mux.go | 2 +- testutil/queryclient/queryclient.go | 131 ++++++++++++++++++++++++++++ x/bank/keeper/grpc_query_test.go | 2 +- x/bank/keeper/keeper_test.go | 9 +- 5 files changed, 139 insertions(+), 6 deletions(-) create mode 100644 testutil/queryclient/queryclient.go diff --git a/core/testing/context.go b/core/testing/context.go index ec3248e6405e..bd036705bcef 100644 --- a/core/testing/context.go +++ b/core/testing/context.go @@ -2,6 +2,7 @@ package coretesting import ( "context" + "cosmossdk.io/core/event" "cosmossdk.io/core/gas" "cosmossdk.io/core/header" diff --git a/schema/appdata/mux.go b/schema/appdata/mux.go index 1eab8b69a6fe..9be2942549d9 100644 --- a/schema/appdata/mux.go +++ b/schema/appdata/mux.go @@ -139,7 +139,7 @@ func ListenerMux(listeners ...Listener) Listener { mux.onBatch = func(batch PacketBatch) error { for _, listener := range listeners { - err := batch.apply(&listener) //nolint:gosec // aliasing is safe here + err := batch.apply(&listener) if err != nil { return err } diff --git a/testutil/queryclient/queryclient.go b/testutil/queryclient/queryclient.go new file mode 100644 index 000000000000..57c2a329e2e1 --- /dev/null +++ b/testutil/queryclient/queryclient.go @@ -0,0 +1,131 @@ +package queryclient + +import ( + "context" + "fmt" + + abci "github.com/cometbft/cometbft/api/cometbft/abci/v1" + gogogrpc "github.com/cosmos/gogoproto/grpc" + "google.golang.org/grpc" + "google.golang.org/grpc/encoding" + + "github.com/cosmos/cosmos-sdk/client/grpc/reflection" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" +) + +var ( + _ gogogrpc.ClientConn = &QueryHelper{} + _ gogogrpc.ClientConn = &QueryHelper{} +) + +// QueryHelper is a test utility for building a query client from a proto interface registry. +type QueryHelper struct { + cdc encoding.Codec + routes map[string]GRPCQueryHandler +} + +func NewQueryHelper(interfaceRegistry codectypes.InterfaceRegistry) *QueryHelper { + // instantiate the codec + cdc := codec.NewProtoCodec(interfaceRegistry).GRPCCodec() + // Once we have an interface registry, we can register the interface + // registry reflection gRPC service. + + qH := &QueryHelper{ + cdc: cdc, + routes: map[string]GRPCQueryHandler{}, + } + + reflection.RegisterReflectionServiceServer(qH, reflection.NewReflectionServiceServer(interfaceRegistry)) + + return qH +} + +// Invoke implements the grpc ClientConn.Invoke method +func (q *QueryHelper) Invoke(ctx context.Context, method string, args, reply interface{}, _ ...grpc.CallOption) error { + querier := q.Route(method) + if querier == nil { + return fmt.Errorf("handler not found for %s", method) + } + reqBz, err := q.cdc.Marshal(args) + if err != nil { + return err + } + + res, err := querier(ctx, &abci.QueryRequest{Data: reqBz}) + if err != nil { + return err + } + + err = q.cdc.Unmarshal(res.Value, reply) + if err != nil { + return err + } + + return nil +} + +// NewStream implements the grpc ClientConn.NewStream method +func (q *QueryHelper) NewStream(context.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) { + panic("not implemented") +} + +// GRPCQueryHandler defines a function type which handles ABCI Query requests +// using gRPC +type GRPCQueryHandler = func(ctx context.Context, req *abci.QueryRequest) (*abci.QueryResponse, error) + +// Route returns the GRPCQueryHandler for a given query route path or nil +// if not found +func (qrt *QueryHelper) Route(path string) GRPCQueryHandler { + handler, found := qrt.routes[path] + if !found { + return nil + } + return handler +} + +// RegisterService implements the gRPC Server.RegisterService method. sd is a gRPC +// service description, handler is an object which implements that gRPC service/ +// +// This functions PANICS: +// - if a protobuf service is registered twice. +func (qrt *QueryHelper) RegisterService(sd *grpc.ServiceDesc, handler interface{}) { + // adds a top-level query handler based on the gRPC service name + for _, method := range sd.Methods { + qrt.registerABCIQueryHandler(sd, method, handler) + } +} + +func (qrt *QueryHelper) registerABCIQueryHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) { + fqName := fmt.Sprintf("/%s/%s", sd.ServiceName, method.MethodName) + methodHandler := method.Handler + + _, found := qrt.routes[fqName] + if found { + panic(fmt.Sprintf("handler for %s already registered", fqName)) + } + + qrt.routes[fqName] = func(ctx context.Context, req *abci.QueryRequest) (*abci.QueryResponse, error) { + // call the method handler from the service description with the handler object, + // a wrapped sdk.Context with proto-unmarshaled data from the ABCI request data + res, err := methodHandler(handler, ctx, func(i interface{}) error { + return qrt.cdc.Unmarshal(req.Data, i) + }, nil) + if err != nil { + return nil, err + } + + // proto marshal the result bytes + var resBytes []byte + resBytes, err = qrt.cdc.Marshal(res) + if err != nil { + return nil, err + } + + // return the result bytes as the response value + return &abci.QueryResponse{ + Height: req.Height, + Value: resBytes, + }, nil + } +} diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index c8bd5096d50c..f1e13dc4d93f 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -347,7 +347,7 @@ func (suite *KeeperTestSuite) TestQueryParams() { func (suite *KeeperTestSuite) TestQueryDenomsMetadata() { var ( req *types.QueryDenomsMetadataRequest - expMetadata = []types.Metadata{} + expMetadata []types.Metadata ) testCases := []struct { diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 82bebe171a87..31ec3e9974d4 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -27,6 +27,7 @@ import ( codectestutil "github.com/cosmos/cosmos-sdk/codec/testutil" "github.com/cosmos/cosmos-sdk/runtime" + "github.com/cosmos/cosmos-sdk/testutil/queryclient" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" @@ -117,7 +118,7 @@ type KeeperTestSuite struct { addrCdc address.Codec authKeeper *banktestutil.MockAccountKeeper - queryClient banktypes.QueryServer + queryClient banktypes.QueryClient msgServer banktypes.MsgServer encCfg moduletestutil.TestEncodingConfig @@ -164,11 +165,11 @@ func (suite *KeeperTestSuite) SetupTest() { DefaultSendEnabled: banktypes.DefaultDefaultSendEnabled, })) + queryHelper := queryclient.NewQueryHelper(encCfg.InterfaceRegistry) + banktypes.RegisterQueryServer(queryHelper, suite.bankKeeper) banktypes.RegisterInterfaces(encCfg.InterfaceRegistry) - queryServer := keeper.NewQuerier(&suite.bankKeeper) - - suite.queryClient = queryServer + suite.queryClient = banktypes.NewQueryClient(queryHelper) suite.msgServer = keeper.NewMsgServerImpl(suite.bankKeeper) suite.encCfg = encCfg suite.env = env From fb556645a4a7e33e0adbd6e2cd6ae1bc441a8c37 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Mon, 6 Jan 2025 16:10:04 -0500 Subject: [PATCH 17/24] clean up --- core/testing/environment.go | 28 ++++++++++++++-------------- core/testing/event.go | 22 +++++++++++----------- core/testing/gas.go | 8 ++++---- core/testing/header.go | 6 +++--- core/testing/router.go | 1 - core/testing/transaction.go | 6 +++--- x/bank/keeper/keeper_test.go | 10 +++++----- 7 files changed, 40 insertions(+), 41 deletions(-) diff --git a/core/testing/environment.go b/core/testing/environment.go index e3f50f6d014d..a89bbdb78f2d 100644 --- a/core/testing/environment.go +++ b/core/testing/environment.go @@ -20,31 +20,31 @@ type TestEnvironmentConfig struct { type TestEnvironment struct { appmodulev2.Environment - memEventsService MemEventsService - memHeaderService MemHeaderService + testEventService TestEventService + testHeaderService TestHeaderService } func NewTestEnvironment(cfg TestEnvironmentConfig) (TestContext, TestEnvironment) { ctx := Context() - memEventService := EventsService(ctx, cfg.ModuleName) - memHeaderService := MemHeaderService{} + testEventService := NewTestEventService(ctx, cfg.ModuleName) + testHeaderService := TestHeaderService{} env := TestEnvironment{ Environment: appmodulev2.Environment{ Logger: cfg.Logger, BranchService: nil, - EventService: memEventService, - GasService: MemGasService{}, - HeaderService: memHeaderService, + EventService: testEventService, + GasService: TestGasService{}, + HeaderService: testHeaderService, QueryRouterService: cfg.QueryRouter, MsgRouterService: cfg.MsgRouter, - TransactionService: MemTransactionService{}, + TransactionService: TestTransactionService{}, KVStoreService: KVStoreService(ctx, cfg.ModuleName), MemStoreService: nil, }, - memEventsService: memEventService, - memHeaderService: memHeaderService, + testEventService: testEventService, + testHeaderService: testHeaderService, } // set internal context to point to environment @@ -52,14 +52,14 @@ func NewTestEnvironment(cfg TestEnvironmentConfig) (TestContext, TestEnvironment return ctx, env } -func (env TestEnvironment) MemEventsService() MemEventsService { - return env.memEventsService +func (env TestEnvironment) EventService() TestEventService { + return env.testEventService } func (env TestEnvironment) KVStoreService() store.KVStoreService { return env.Environment.KVStoreService } -func (env TestEnvironment) HeaderService() MemHeaderService { - return env.memHeaderService +func (env TestEnvironment) HeaderService() TestHeaderService { + return env.testHeaderService } diff --git a/core/testing/event.go b/core/testing/event.go index 97385280fdda..d4f61aa2c850 100644 --- a/core/testing/event.go +++ b/core/testing/event.go @@ -7,29 +7,29 @@ import ( "cosmossdk.io/core/transaction" ) -var _ event.Service = (*MemEventsService)(nil) +var _ event.Service = &TestEventService{} -// EventsService attaches an event service to the context. +type TestEventService struct { + moduleName string +} + +// NewTestEventService attaches an event service to the context. // Adding an existing module will reset the events. -func EventsService(ctx context.Context, moduleName string) MemEventsService { +func NewTestEventService(ctx context.Context, moduleName string) TestEventService { unwrap(ctx).events[moduleName] = nil unwrap(ctx).protoEvents[moduleName] = nil - return MemEventsService{moduleName: moduleName} -} - -type MemEventsService struct { - moduleName string + return TestEventService{moduleName: moduleName} } -func (e MemEventsService) EventManager(ctx context.Context) event.Manager { +func (e TestEventService) EventManager(ctx context.Context) event.Manager { return eventManager{moduleName: e.moduleName, ctx: unwrap(ctx)} } -func (e MemEventsService) GetEvents(ctx context.Context) []event.Event { +func (e TestEventService) GetEvents(ctx context.Context) []event.Event { return unwrap(ctx).events[e.moduleName] } -func (e MemEventsService) GetProtoEvents(ctx context.Context) []transaction.Msg { +func (e TestEventService) GetProtoEvents(ctx context.Context) []transaction.Msg { return unwrap(ctx).protoEvents[e.moduleName] } diff --git a/core/testing/gas.go b/core/testing/gas.go index 1aca2a784ade..ba66b45fdfce 100644 --- a/core/testing/gas.go +++ b/core/testing/gas.go @@ -6,17 +6,17 @@ import ( "cosmossdk.io/core/gas" ) -var _ gas.Service = &MemGasService{} +var _ gas.Service = &TestGasService{} -type MemGasService struct{} +type TestGasService struct{} -func (m MemGasService) GasMeter(ctx context.Context) gas.Meter { +func (m TestGasService) GasMeter(ctx context.Context) gas.Meter { dummy := unwrap(ctx) return dummy.gasMeter } -func (m MemGasService) GasConfig(ctx context.Context) gas.GasConfig { +func (m TestGasService) GasConfig(ctx context.Context) gas.GasConfig { dummy := unwrap(ctx) return dummy.gasConfig diff --git a/core/testing/header.go b/core/testing/header.go index ac19145cc587..50ee97e3f828 100644 --- a/core/testing/header.go +++ b/core/testing/header.go @@ -6,10 +6,10 @@ import ( "cosmossdk.io/core/header" ) -var _ header.Service = &MemHeaderService{} +var _ header.Service = &TestHeaderService{} -type MemHeaderService struct{} +type TestHeaderService struct{} -func (e MemHeaderService) HeaderInfo(ctx context.Context) header.Info { +func (e TestHeaderService) HeaderInfo(ctx context.Context) header.Info { return unwrap(ctx).header } diff --git a/core/testing/router.go b/core/testing/router.go index 1d9546d3d4dd..cff995394b96 100644 --- a/core/testing/router.go +++ b/core/testing/router.go @@ -31,7 +31,6 @@ type ReflectionRouterBuilder struct { } func (b *ReflectionRouterBuilder) RegisterHandler(msgType string, handler appmodulev2.HandlerFunc) error { - // panic on override if _, ok := b.handlers[msgType]; ok { return fmt.Errorf("handler already registered: %s", msgType) } diff --git a/core/testing/transaction.go b/core/testing/transaction.go index 7ff46d6f1016..689a3c932016 100644 --- a/core/testing/transaction.go +++ b/core/testing/transaction.go @@ -6,11 +6,11 @@ import ( "cosmossdk.io/core/transaction" ) -var _ transaction.Service = &MemTransactionService{} +var _ transaction.Service = &TestTransactionService{} -type MemTransactionService struct{} +type TestTransactionService struct{} -func (m MemTransactionService) ExecMode(ctx context.Context) transaction.ExecMode { +func (m TestTransactionService) ExecMode(ctx context.Context) transaction.ExecMode { dummy := unwrap(ctx) return dummy.execMode diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 31ec3e9974d4..b73b44967f68 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -1387,7 +1387,7 @@ func (suite *KeeperTestSuite) TestMsgSendEvents() { }, } - events := suite.env.MemEventsService().GetEvents(suite.ctx) + events := suite.env.EventService().GetEvents(suite.ctx) // events are shifted due to the funding account events require.Equal(8, len(events)) require.Equal(event1.Type, events[7].Type) @@ -1432,7 +1432,7 @@ func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { suite.authKeeper.EXPECT().GetAccount(suite.ctx, accAddrs[0]).Return(acc0) require.Error(suite.bankKeeper.InputOutputCoins(ctx, input, outputs)) - events := suite.env.MemEventsService().GetEvents(suite.ctx) + events := suite.env.EventService().GetEvents(suite.ctx) require.Equal(0, len(events)) // Set addr's coins but not accAddrs[1]'s coins @@ -1442,7 +1442,7 @@ func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { suite.mockInputOutputCoins([]sdk.AccountI{acc0}, accAddrs[2:4]) require.NoError(suite.bankKeeper.InputOutputCoins(ctx, input, outputs)) - events = suite.env.MemEventsService().GetEvents(suite.ctx) + events = suite.env.EventService().GetEvents(suite.ctx) require.Equal(10, len(events)) // 10 events because account funding causes extra minting + coin_spent + coin_recv events // Set addr's coins and accAddrs[1]'s coins @@ -1457,7 +1457,7 @@ func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { suite.mockInputOutputCoins([]sdk.AccountI{acc0}, accAddrs[2:4]) require.NoError(suite.bankKeeper.InputOutputCoins(ctx, input, outputs)) - events = suite.env.MemEventsService().GetEvents(suite.ctx) + events = suite.env.EventService().GetEvents(suite.ctx) require.Equal(25, len(events)) // 25 due to account funding + coin_spent + coin_recv events event1 := coreevent.Event{ @@ -1926,7 +1926,7 @@ func (suite *KeeperTestSuite) TestBalanceTrackingEvents() { balances := make(map[string]sdk.Coins) - events := suite.env.MemEventsService().GetEvents(suite.ctx) + events := suite.env.EventService().GetEvents(suite.ctx) for _, e := range events { attributes, err := e.Attributes() From 87fb4f916e1823f6f96a45e2b5a82715c70fae4e Mon Sep 17 00:00:00 2001 From: aljo242 Date: Mon, 6 Jan 2025 16:15:30 -0500 Subject: [PATCH 18/24] lint --- schema/appdata/mux.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/schema/appdata/mux.go b/schema/appdata/mux.go index 9be2942549d9..81a4fa795db8 100644 --- a/schema/appdata/mux.go +++ b/schema/appdata/mux.go @@ -139,7 +139,7 @@ func ListenerMux(listeners ...Listener) Listener { mux.onBatch = func(batch PacketBatch) error { for _, listener := range listeners { - err := batch.apply(&listener) + err := batch.apply(&listener) if err != nil { return err } From e18d8090bef72856c0ead57298d098aa8b774b9b Mon Sep 17 00:00:00 2001 From: aljo242 Date: Mon, 6 Jan 2025 16:19:52 -0500 Subject: [PATCH 19/24] server check --- testutil/queryclient/queryclient.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testutil/queryclient/queryclient.go b/testutil/queryclient/queryclient.go index 57c2a329e2e1..1e4a84aa1e22 100644 --- a/testutil/queryclient/queryclient.go +++ b/testutil/queryclient/queryclient.go @@ -16,7 +16,7 @@ import ( var ( _ gogogrpc.ClientConn = &QueryHelper{} - _ gogogrpc.ClientConn = &QueryHelper{} + _ gogogrpc.Server = &QueryHelper{} ) // QueryHelper is a test utility for building a query client from a proto interface registry. From f67b33fc00d46ebcc29a7b0cc9f758b3f089132c Mon Sep 17 00:00:00 2001 From: aljo242 Date: Tue, 7 Jan 2025 09:46:10 -0500 Subject: [PATCH 20/24] lint-fix --- x/bank/keeper/grpc_query_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index 896901f406c3..9560645cb94a 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -147,7 +147,7 @@ func (suite *KeeperTestSuite) TestQueryAllBalances() { } req = types.NewQueryAllBalancesRequest(addrStr, pageReq, true) testFunc := func() { - res, err = queryClient.AllBalances(gocontext.Background(), req) + res, err = queryClient.AllBalances(ctx, req) } suite.Require().NotPanics(testFunc, "AllBalances with resolve denom + incomplete metadata") suite.Require().NoError(err) From 47a681e0401075bdc5f1af4cf2b50758c56b5f46 Mon Sep 17 00:00:00 2001 From: aljo242 Date: Wed, 8 Jan 2025 09:52:38 -0500 Subject: [PATCH 21/24] init test --- core/testing/router_test.go | 1 + 1 file changed, 1 insertion(+) create mode 100644 core/testing/router_test.go diff --git a/core/testing/router_test.go b/core/testing/router_test.go new file mode 100644 index 000000000000..77ead1aa96a0 --- /dev/null +++ b/core/testing/router_test.go @@ -0,0 +1 @@ +package coretesting From 9f5432413dd567147d500808a6f11afce159d3da Mon Sep 17 00:00:00 2001 From: aljo242 Date: Wed, 8 Jan 2025 14:43:27 -0500 Subject: [PATCH 22/24] rm --- core/testing/router.go | 158 ------------------------------------ core/testing/router_test.go | 1 - 2 files changed, 159 deletions(-) delete mode 100644 core/testing/router.go delete mode 100644 core/testing/router_test.go diff --git a/core/testing/router.go b/core/testing/router.go deleted file mode 100644 index cff995394b96..000000000000 --- a/core/testing/router.go +++ /dev/null @@ -1,158 +0,0 @@ -package coretesting - -import ( - "context" - "errors" - "fmt" - "reflect" - - appmodulev2 "cosmossdk.io/core/appmodule/v2" - "cosmossdk.io/core/router" - "cosmossdk.io/core/transaction" -) - -var ErrNoHandler = errors.New("no handler") - -// NewMsgRouterBuilder is a router that routes messages to their respective handlers. -func NewMsgRouterBuilder() *ReflectionRouterBuilder { - return &ReflectionRouterBuilder{ - handlers: make(map[string]appmodulev2.HandlerFunc), - preHandlers: make(map[string][]appmodulev2.PreMsgHandler), - postHandlers: make(map[string][]appmodulev2.PostMsgHandler), - } -} - -type ReflectionRouterBuilder struct { - handlers map[string]appmodulev2.HandlerFunc - globalPreHandlers []appmodulev2.PreMsgHandler - preHandlers map[string][]appmodulev2.PreMsgHandler - postHandlers map[string][]appmodulev2.PostMsgHandler - globalPostHandlers []appmodulev2.PostMsgHandler -} - -func (b *ReflectionRouterBuilder) RegisterHandler(msgType string, handler appmodulev2.HandlerFunc) error { - if _, ok := b.handlers[msgType]; ok { - return fmt.Errorf("handler already registered: %s", msgType) - } - b.handlers[msgType] = handler - return nil -} - -func (b *ReflectionRouterBuilder) RegisterGlobalPreMsgHandler(handler appmodulev2.PreMsgHandler) { - b.globalPreHandlers = append(b.globalPreHandlers, handler) -} - -func (b *ReflectionRouterBuilder) RegisterPreMsgHandler(msgType string, handler appmodulev2.PreMsgHandler) { - b.preHandlers[msgType] = append(b.preHandlers[msgType], handler) -} - -func (b *ReflectionRouterBuilder) RegisterPostMsgHandler(msgType string, handler appmodulev2.PostMsgHandler) { - b.postHandlers[msgType] = append(b.postHandlers[msgType], handler) -} - -func (b *ReflectionRouterBuilder) RegisterGlobalPostMsgHandler(handler appmodulev2.PostMsgHandler) { - b.globalPostHandlers = append(b.globalPostHandlers, handler) -} - -func (b *ReflectionRouterBuilder) HandlerExists(msgType string) bool { - _, ok := b.handlers[msgType] - return ok -} - -func (b *ReflectionRouterBuilder) Build() (ReflectionRouter, error) { - handlers := make(map[string]appmodulev2.HandlerFunc) - - globalPreHandler := func(ctx context.Context, msg transaction.Msg) error { - for _, h := range b.globalPreHandlers { - err := h(ctx, msg) - if err != nil { - return err - } - } - return nil - } - - globalPostHandler := func(ctx context.Context, msg, msgResp transaction.Msg) error { - for _, h := range b.globalPostHandlers { - err := h(ctx, msg, msgResp) - if err != nil { - return err - } - } - return nil - } - - for msgType, handler := range b.handlers { - // find pre handler - preHandlers := b.preHandlers[msgType] - // find post handler - postHandlers := b.postHandlers[msgType] - // build the handler - handlers[msgType] = buildHandler(handler, preHandlers, globalPreHandler, postHandlers, globalPostHandler) - } - - return ReflectionRouter{ - handlers: handlers, - }, nil -} - -func buildHandler( - handler appmodulev2.HandlerFunc, - preHandlers []appmodulev2.PreMsgHandler, - globalPreHandler appmodulev2.PreMsgHandler, - postHandlers []appmodulev2.PostMsgHandler, - globalPostHandler appmodulev2.PostMsgHandler, -) appmodulev2.HandlerFunc { - return func(ctx context.Context, msg transaction.Msg) (msgResp transaction.Msg, err error) { - if len(preHandlers) != 0 { - for _, preHandler := range preHandlers { - if err := preHandler(ctx, msg); err != nil { - return nil, err - } - } - } - err = globalPreHandler(ctx, msg) - if err != nil { - return nil, err - } - msgResp, err = handler(ctx, msg) - if err != nil { - return nil, err - } - - if len(postHandlers) != 0 { - for _, postHandler := range postHandlers { - if err := postHandler(ctx, msg, msgResp); err != nil { - return nil, err - } - } - } - err = globalPostHandler(ctx, msg, msgResp) - return msgResp, err - } -} - -var _ router.Service = (*ReflectionRouter)(nil) - -// ReflectionRouter implements the STF router for msg and query handlers. -type ReflectionRouter struct { - handlers map[string]appmodulev2.HandlerFunc -} - -func (r ReflectionRouter) CanInvoke(_ context.Context, typeURL string) error { - _, exists := r.handlers[typeURL] - if !exists { - return fmt.Errorf("%w: %s", ErrNoHandler, typeURL) - } - return nil -} - -func (r ReflectionRouter) Invoke(ctx context.Context, req transaction.Msg) (res transaction.Msg, err error) { - typeName := reflect.TypeOf(req).String() - handler, exists := r.handlers[typeName] - if !exists { - return nil, fmt.Errorf("%w: %s", ErrNoHandler, typeName) - } - - return handler(ctx, req) -} diff --git a/core/testing/router_test.go b/core/testing/router_test.go deleted file mode 100644 index 77ead1aa96a0..000000000000 --- a/core/testing/router_test.go +++ /dev/null @@ -1 +0,0 @@ -package coretesting From 1838bbf777b87c91d59453bc436a124198c3b6e6 Mon Sep 17 00:00:00 2001 From: Alex | Interchain Labs Date: Thu, 9 Jan 2025 12:43:46 -0500 Subject: [PATCH 23/24] Update testutil/queryclient/queryclient.go Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com> --- testutil/queryclient/queryclient.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/testutil/queryclient/queryclient.go b/testutil/queryclient/queryclient.go index 1e4a84aa1e22..406a754deea3 100644 --- a/testutil/queryclient/queryclient.go +++ b/testutil/queryclient/queryclient.go @@ -31,14 +31,14 @@ func NewQueryHelper(interfaceRegistry codectypes.InterfaceRegistry) *QueryHelper // Once we have an interface registry, we can register the interface // registry reflection gRPC service. - qH := &QueryHelper{ + qh := &QueryHelper{ cdc: cdc, routes: map[string]GRPCQueryHandler{}, } - reflection.RegisterReflectionServiceServer(qH, reflection.NewReflectionServiceServer(interfaceRegistry)) + reflection.RegisterReflectionServiceServer(qh, reflection.NewReflectionServiceServer(interfaceRegistry)) - return qH + return qh } // Invoke implements the grpc ClientConn.Invoke method From e932ea5719b1ae445abf4e54a6807f7fee6dec9d Mon Sep 17 00:00:00 2001 From: aljo242 Date: Thu, 9 Jan 2025 12:45:20 -0500 Subject: [PATCH 24/24] q --- testutil/queryclient/queryclient.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/testutil/queryclient/queryclient.go b/testutil/queryclient/queryclient.go index 406a754deea3..8502fcb5d5bd 100644 --- a/testutil/queryclient/queryclient.go +++ b/testutil/queryclient/queryclient.go @@ -76,8 +76,8 @@ type GRPCQueryHandler = func(ctx context.Context, req *abci.QueryRequest) (*abci // Route returns the GRPCQueryHandler for a given query route path or nil // if not found -func (qrt *QueryHelper) Route(path string) GRPCQueryHandler { - handler, found := qrt.routes[path] +func (q *QueryHelper) Route(path string) GRPCQueryHandler { + handler, found := q.routes[path] if !found { return nil } @@ -89,27 +89,27 @@ func (qrt *QueryHelper) Route(path string) GRPCQueryHandler { // // This functions PANICS: // - if a protobuf service is registered twice. -func (qrt *QueryHelper) RegisterService(sd *grpc.ServiceDesc, handler interface{}) { +func (q *QueryHelper) RegisterService(sd *grpc.ServiceDesc, handler interface{}) { // adds a top-level query handler based on the gRPC service name for _, method := range sd.Methods { - qrt.registerABCIQueryHandler(sd, method, handler) + q.registerABCIQueryHandler(sd, method, handler) } } -func (qrt *QueryHelper) registerABCIQueryHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) { +func (q *QueryHelper) registerABCIQueryHandler(sd *grpc.ServiceDesc, method grpc.MethodDesc, handler interface{}) { fqName := fmt.Sprintf("/%s/%s", sd.ServiceName, method.MethodName) methodHandler := method.Handler - _, found := qrt.routes[fqName] + _, found := q.routes[fqName] if found { panic(fmt.Sprintf("handler for %s already registered", fqName)) } - qrt.routes[fqName] = func(ctx context.Context, req *abci.QueryRequest) (*abci.QueryResponse, error) { + q.routes[fqName] = func(ctx context.Context, req *abci.QueryRequest) (*abci.QueryResponse, error) { // call the method handler from the service description with the handler object, // a wrapped sdk.Context with proto-unmarshaled data from the ABCI request data res, err := methodHandler(handler, ctx, func(i interface{}) error { - return qrt.cdc.Unmarshal(req.Data, i) + return q.cdc.Unmarshal(req.Data, i) }, nil) if err != nil { return nil, err @@ -117,7 +117,7 @@ func (qrt *QueryHelper) registerABCIQueryHandler(sd *grpc.ServiceDesc, method gr // proto marshal the result bytes var resBytes []byte - resBytes, err = qrt.cdc.Marshal(res) + resBytes, err = q.cdc.Marshal(res) if err != nil { return nil, err }