Skip to content

Commit

Permalink
refactor: Use mocks for x/authz testing (cosmos#12799)
Browse files Browse the repository at this point in the history
## Description

Closes: cosmos#12761 



---

### Author Checklist

*All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.*

I have...

- [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] added `!` to the type prefix if API or client breaking change
- [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#pr-targeting))
- [ ] provided a link to the relevant issue or specification
- [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/main/docs/building-modules)
- [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#testing)
- [ ] added a changelog entry to `CHANGELOG.md`
- [ ] included comments for [documenting Go code](https://blog.golang.org/godoc)
- [ ] updated the relevant documentation or specification
- [ ] reviewed "Files changed" and left comments if necessary
- [ ] confirmed all CI checks have passed

### Reviewers Checklist

*All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.*

I have...

- [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] confirmed `!` in the type prefix if API or client breaking change
- [ ] confirmed all author checklist items have been addressed 
- [ ] reviewed state machine logic
- [ ] reviewed API design and naming
- [ ] reviewed documentation is accurate
- [ ] reviewed tests and test coverage
- [ ] manually tested (if applicable)
  • Loading branch information
likhita-809 authored Aug 10, 2022
1 parent 2bb48e8 commit f7e46ae
Show file tree
Hide file tree
Showing 10 changed files with 277 additions and 77 deletions.
1 change: 1 addition & 0 deletions scripts/mockgen.sh
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ $mockgen_cmd -source=x/params/proposal_handler_test.go -package testutil -destin
$mockgen_cmd -source=x/crisis/types/expected_keepers.go -package testutil -destination x/crisis/testutil/expected_keepers_mocks.go
$mockgen_cmd -source=x/auth/types/expected_keepers.go -package testutil -destination x/auth/testutil/expected_keepers_mocks.go
$mockgen_cmd -source=x/auth/ante/expected_keepers.go -package testutil -destination x/auth/ante/testutil/expected_keepers_mocks.go
$mockgen_cmd -source=x/authz/expected_keepers.go -package testutil -destination x/authz/testutil/expected_keepers_mocks.go
$mockgen_cmd -source=x/bank/types/expected_keepers.go -package testutil -destination x/bank/testutil/expected_keepers_mocks.go
$mockgen_cmd -source=x/evidence/types/expected_keepers.go -package testutil -destination x/evidence/testutil/expected_keepers_mocks.go
42 changes: 33 additions & 9 deletions x/authz/keeper/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,55 @@ import (
"time"

"github.com/stretchr/testify/suite"
"github.com/tendermint/tendermint/libs/log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"

"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/authz/keeper"
"github.com/cosmos/cosmos-sdk/x/authz/testutil"
authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module"
authztestutil "github.com/cosmos/cosmos-sdk/x/authz/testutil"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/golang/mock/gomock"
)

type GenesisTestSuite struct {
suite.Suite

ctx sdk.Context
keeper keeper.Keeper
ctx sdk.Context
keeper keeper.Keeper
baseApp *baseapp.BaseApp
accountKeeper *authztestutil.MockAccountKeeper
encCfg moduletestutil.TestEncodingConfig
}

func (suite *GenesisTestSuite) SetupTest() {
app, err := simtestutil.Setup(
testutil.AppConfig,
&suite.keeper,
key := sdk.NewKVStoreKey(keeper.StoreKey)
testCtx := testutil.DefaultContextWithDB(suite.T(), key, sdk.NewTransientStoreKey("transient_test"))
suite.ctx = testCtx.Ctx.WithBlockHeader(tmproto.Header{Height: 1})
suite.encCfg = moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{})

// gomock initializations
ctrl := gomock.NewController(suite.T())
suite.accountKeeper = authztestutil.NewMockAccountKeeper(ctrl)

suite.baseApp = baseapp.NewBaseApp(
"authz",
log.NewNopLogger(),
testCtx.DB,
suite.encCfg.TxConfig.TxDecoder(),
)
suite.Require().NoError(err)
suite.baseApp.SetCMS(testCtx.CMS)

bank.RegisterInterfaces(suite.encCfg.InterfaceRegistry)

msr := suite.baseApp.MsgServiceRouter()
msr.SetInterfaceRegistry(suite.encCfg.InterfaceRegistry)

suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{Height: 1})
suite.keeper = keeper.NewKeeper(key, suite.encCfg.Codec, msr, suite.accountKeeper)
}

var (
Expand Down
4 changes: 2 additions & 2 deletions x/authz/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (suite *TestSuite) TestGRPCQueryAuthorization() {
func(require *require.Assertions, res *authz.QueryGrantsResponse) {
var auth authz.Authorization
require.Equal(1, len(res.Grants))
err := suite.interfaceRegistry.UnpackAny(res.Grants[0].Authorization, &auth)
err := suite.encCfg.InterfaceRegistry.UnpackAny(res.Grants[0].Authorization, &auth)
require.NoError(err)
require.NotNil(auth)
require.Equal(auth.String(), expAuthorization.String())
Expand Down Expand Up @@ -135,7 +135,7 @@ func (suite *TestSuite) TestGRPCQueryAuthorizations() {
func(res *authz.QueryGrantsResponse) {
var auth authz.Authorization
suite.Require().Equal(1, len(res.Grants))
err := suite.interfaceRegistry.UnpackAny(res.Grants[0].Authorization, &auth)
err := suite.encCfg.InterfaceRegistry.UnpackAny(res.Grants[0].Authorization, &auth)
suite.Require().NoError(err)
suite.Require().NotNil(auth)
suite.Require().Equal(auth.String(), expAuthorization.String())
Expand Down
65 changes: 37 additions & 28 deletions x/authz/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@ import (
"testing"
"time"

"github.com/golang/mock/gomock"
"github.com/stretchr/testify/suite"
tmtime "github.com/tendermint/tendermint/libs/time"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"

"github.com/cosmos/cosmos-sdk/baseapp"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/testutil"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/authz"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
"github.com/cosmos/cosmos-sdk/x/authz/testutil"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module"
authztestutil "github.com/cosmos/cosmos-sdk/x/authz/testutil"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/tendermint/tendermint/libs/log"
)

var (
Expand All @@ -34,34 +36,46 @@ type TestSuite struct {
ctx sdk.Context
addrs []sdk.AccAddress
authzKeeper authzkeeper.Keeper
bankKeeper bankkeeper.Keeper
accountKeeper *authztestutil.MockAccountKeeper
bankKeeper *authztestutil.MockBankKeeper
interfaceRegistry codectypes.InterfaceRegistry
baseApp *baseapp.BaseApp
encCfg moduletestutil.TestEncodingConfig
queryClient authz.QueryClient
}

func (s *TestSuite) SetupTest() {
var stakingKeeper *stakingkeeper.Keeper

app, err := simtestutil.Setup(
testutil.AppConfig,
&s.bankKeeper,
&stakingKeeper,
&s.authzKeeper,
&s.interfaceRegistry,
key := sdk.NewKVStoreKey(authzkeeper.StoreKey)
testCtx := testutil.DefaultContextWithDB(s.T(), key, sdk.NewTransientStoreKey("transient_test"))
s.ctx = testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: tmtime.Now()})
s.encCfg = moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{})

s.baseApp = baseapp.NewBaseApp(
"authz",
log.NewNopLogger(),
testCtx.DB,
s.encCfg.TxConfig.TxDecoder(),
)
s.Require().NoError(err)
s.baseApp.SetCMS(testCtx.CMS)
s.baseApp.SetInterfaceRegistry(s.encCfg.InterfaceRegistry)

ctx := app.BaseApp.NewContext(false, tmproto.Header{})
now := tmtime.Now()
ctx = ctx.WithBlockHeader(tmproto.Header{Time: now})
queryHelper := baseapp.NewQueryServerTestHelper(ctx, s.interfaceRegistry)
s.addrs = simtestutil.CreateIncrementalAccounts(3)

// gomock initializations
ctrl := gomock.NewController(s.T())
s.accountKeeper = authztestutil.NewMockAccountKeeper(ctrl)
s.bankKeeper = authztestutil.NewMockBankKeeper(ctrl)
banktypes.RegisterInterfaces(s.encCfg.InterfaceRegistry)
banktypes.RegisterMsgServer(s.baseApp.MsgServiceRouter(), s.bankKeeper)

s.authzKeeper = authzkeeper.NewKeeper(key, s.encCfg.Codec, s.baseApp.MsgServiceRouter(), s.accountKeeper)

queryHelper := baseapp.NewQueryServerTestHelper(s.ctx, s.encCfg.InterfaceRegistry)
authz.RegisterQueryServer(queryHelper, s.authzKeeper)
queryClient := authz.NewQueryClient(queryHelper)
s.queryClient = queryClient

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

func (s *TestSuite) TestKeeper() {
Expand Down Expand Up @@ -147,8 +161,6 @@ func (s *TestSuite) TestDispatchAction() {
recipientAddr := addrs[2]
a := banktypes.NewSendAuthorization(coins100, nil)

require.NoError(banktestutil.FundAccount(s.bankKeeper, s.ctx, granterAddr, coins1000))

testCases := []struct {
name string
req authz.MsgExec
Expand Down Expand Up @@ -291,7 +303,6 @@ func (s *TestSuite) TestDispatchedEvents() {
granterAddr := addrs[0]
granteeAddr := addrs[1]
recipientAddr := addrs[2]
require.NoError(banktestutil.FundAccount(s.bankKeeper, s.ctx, granterAddr, coins1000))
expiration := s.ctx.BlockTime().Add(1 * time.Second) // must be in the future

msgs := authz.NewMsgExec(granteeAddr, []sdk.Msg{
Expand Down Expand Up @@ -321,13 +332,11 @@ func (s *TestSuite) TestDispatchedEvents() {
events := s.ctx.EventManager().Events()

// get last 5 events (events that occur *after* the grant)
events = events[len(events)-5:]
events = events[len(events)-2:]

requiredEvents := map[string]bool{
"coin_spent": false,
"coin_received": false,
"transfer": false,
"message": false,
"cosmos.authz.v1beta1.EventGrant": true,
"cosmos.authz.v1beta1.EventRevoke": true,
}
for _, e := range events {
requiredEvents[e.Type] = true
Expand Down
53 changes: 34 additions & 19 deletions x/authz/module/abci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,42 @@ import (
"time"

"github.com/cosmos/cosmos-sdk/baseapp"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/testutil"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/authz"
"github.com/cosmos/cosmos-sdk/x/authz/keeper"
authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module"
"github.com/cosmos/cosmos-sdk/x/authz/testutil"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
authztestutil "github.com/cosmos/cosmos-sdk/x/authz/testutil"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"

"github.com/tendermint/tendermint/proto/tendermint/types"
)

func TestExpiredGrantsQueue(t *testing.T) {
var interfaceRegistry codectypes.InterfaceRegistry
var authzKeeper keeper.Keeper
var bankKeeper bankkeeper.Keeper
var stakingKeeper *stakingkeeper.Keeper

app, err := simtestutil.Setup(
testutil.AppConfig,
&interfaceRegistry,
&authzKeeper,
&bankKeeper,
&stakingKeeper,

key := sdk.NewKVStoreKey(keeper.StoreKey)
testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test"))
encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{})
ctx := testCtx.Ctx.WithBlockHeader(types.Header{})

baseApp := baseapp.NewBaseApp(
"authz",
log.NewNopLogger(),
testCtx.DB,
encCfg.TxConfig.TxDecoder(),
)
require.NoError(t, err)
baseApp.SetCMS(testCtx.CMS)
baseApp.SetInterfaceRegistry(encCfg.InterfaceRegistry)

ctx := app.BaseApp.NewContext(false, types.Header{})
addrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 5, sdk.NewInt(30000000))
banktypes.RegisterInterfaces(encCfg.InterfaceRegistry)

addrs := simtestutil.CreateIncrementalAccounts(5)
granter := addrs[0]
grantee1 := addrs[1]
grantee2 := addrs[2]
Expand All @@ -46,6 +51,16 @@ func TestExpiredGrantsQueue(t *testing.T) {
smallCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 10))
sendAuthz := banktypes.NewSendAuthorization(smallCoins, nil)

ctrl := gomock.NewController(t)
accountKeeper := authztestutil.NewMockAccountKeeper(ctrl)
accountKeeper.EXPECT().GetAccount(gomock.Any(), granter).Return(authtypes.NewBaseAccountWithAddress(granter)).AnyTimes()
accountKeeper.EXPECT().GetAccount(gomock.Any(), grantee1).Return(authtypes.NewBaseAccountWithAddress(grantee1)).AnyTimes()
accountKeeper.EXPECT().GetAccount(gomock.Any(), grantee2).Return(authtypes.NewBaseAccountWithAddress(grantee2)).AnyTimes()
accountKeeper.EXPECT().GetAccount(gomock.Any(), grantee3).Return(authtypes.NewBaseAccountWithAddress(grantee3)).AnyTimes()
accountKeeper.EXPECT().GetAccount(gomock.Any(), grantee4).Return(authtypes.NewBaseAccountWithAddress(grantee4)).AnyTimes()

authzKeeper := keeper.NewKeeper(key, encCfg.Codec, baseApp.MsgServiceRouter(), accountKeeper)

save := func(grantee sdk.AccAddress, exp *time.Time) {
err := authzKeeper.SaveGrant(ctx, grantee, granter, sendAuthz, exp)
require.NoError(t, err, "Grant from %s", grantee.String())
Expand All @@ -55,7 +70,7 @@ func TestExpiredGrantsQueue(t *testing.T) {
save(grantee3, &expiration2)
save(grantee4, nil)

queryHelper := baseapp.NewQueryServerTestHelper(ctx, interfaceRegistry)
queryHelper := baseapp.NewQueryServerTestHelper(ctx, encCfg.InterfaceRegistry)
authz.RegisterQueryServer(queryHelper, authzKeeper)
queryClient := authz.NewQueryClient(queryHelper)

Expand Down
14 changes: 7 additions & 7 deletions x/authz/simulation/decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,28 @@ import (

"github.com/stretchr/testify/require"

"cosmossdk.io/depinject"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
"github.com/cosmos/cosmos-sdk/x/authz"
"github.com/cosmos/cosmos-sdk/x/authz/keeper"
authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module"
"github.com/cosmos/cosmos-sdk/x/authz/simulation"
"github.com/cosmos/cosmos-sdk/x/authz/testutil"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"

moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
)

func TestDecodeStore(t *testing.T) {
var cdc codec.Codec
depinject.Inject(testutil.AppConfig, &cdc)
encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{})
banktypes.RegisterInterfaces(encCfg.InterfaceRegistry)

dec := simulation.NewDecodeStore(cdc)
dec := simulation.NewDecodeStore(encCfg.Codec)

now := time.Now().UTC()
e := now.Add(1)
sendAuthz := banktypes.NewSendAuthorization(sdk.NewCoins(sdk.NewInt64Coin("foo", 123)), nil)
grant, _ := authz.NewGrant(now, sendAuthz, &e)
grantBz, err := cdc.Marshal(&grant)
grantBz, err := encCfg.Codec.Marshal(&grant)
require.NoError(t, err)
kvPairs := kv.Pairs{
Pairs: []kv.Pair{
Expand Down
13 changes: 7 additions & 6 deletions x/authz/simulation/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,27 @@ import (

"github.com/stretchr/testify/require"

"cosmossdk.io/depinject"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/authz"
authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module"
"github.com/cosmos/cosmos-sdk/x/authz/simulation"
"github.com/cosmos/cosmos-sdk/x/authz/testutil"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"

moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
)

func TestRandomizedGenState(t *testing.T) {
var cdc codec.Codec
depinject.Inject(testutil.AppConfig, &cdc)
encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{})
banktypes.RegisterInterfaces(encCfg.InterfaceRegistry)

s := rand.NewSource(1)
r := rand.New(s)

simState := module.SimulationState{
AppParams: make(simtypes.AppParams),
Cdc: cdc,
Cdc: encCfg.Codec,
Rand: r,
NumBonded: 3,
Accounts: simtypes.RandomAccounts(r, 3),
Expand Down
Loading

0 comments on commit f7e46ae

Please sign in to comment.