Skip to content

Commit

Permalink
refactor: remove simapp references from x/bank and x/slashing tests (#…
Browse files Browse the repository at this point in the history
…12897)

## Description

There are still some references to simapp in `x/bank` and `x/slashing`.  This patch removes them.  Somewhat related to forming tests also:

- Flags `LegacySubspace exported.Subspace` as ``optional:"true"`` since x/params is moving to deprecation 



---

### 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
kocubinski authored Aug 11, 2022
1 parent 6473e73 commit 15b04c2
Show file tree
Hide file tree
Showing 18 changed files with 395 additions and 258 deletions.
88 changes: 0 additions & 88 deletions simapp/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ package simapp
import (
"context"
"encoding/json"
"math/rand"
"testing"
"time"

"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
Expand All @@ -18,7 +16,6 @@ import (
"cosmossdk.io/depinject"
"cosmossdk.io/math"
bam "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
Expand Down Expand Up @@ -256,91 +253,6 @@ func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.C
require.True(t, balances.IsEqual(app.BankKeeper.GetAllBalances(ctxCheck, addr)))
}

// SignCheckDeliver checks a generated signed transaction and simulates a
// block commitment with the given transaction. A test assertion is made using
// the parameter 'expPass' against the result. A corresponding result is
// returned.
func SignCheckDeliver(
t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg,
chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey,
) (sdk.GasInfo, *sdk.Result, error) {
tx, err := simtestutil.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
simtestutil.DefaultGenTxGas,
chainID,
accNums,
accSeqs,
priv...,
)
require.NoError(t, err)
txBytes, err := txCfg.TxEncoder()(tx)
require.Nil(t, err)

// Must simulate now as CheckTx doesn't run Msgs anymore
_, res, err := app.Simulate(txBytes)

if expSimPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}

// Simulate a sending a transaction and committing a block
app.BeginBlock(abci.RequestBeginBlock{Header: header})
gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx)

if expPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}

app.EndBlock(abci.RequestEndBlock{})
app.Commit()

return gInfo, res, err
}

// GenSequenceOfTxs generates a set of signed transactions of messages, such
// that they differ only by having the sequence numbers incremented between
// every transaction.
func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...cryptotypes.PrivKey) ([]sdk.Tx, error) {
txs := make([]sdk.Tx, numToGenerate)
var err error
for i := 0; i < numToGenerate; i++ {
txs[i], err = simtestutil.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txGen,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
simtestutil.DefaultGenTxGas,
"",
accNums,
initSeqNums,
priv...,
)
if err != nil {
break
}
incrementAllSequenceNumbers(initSeqNums)
}

return txs, err
}

func incrementAllSequenceNumbers(initSeqNums []uint64) {
for i := 0; i < len(initSeqNums); i++ {
initSeqNums[i]++
}
}

// ModuleAccountAddrs provides a list of blocked module accounts from configuration in app.yaml
//
// Ported from SimApp
Expand Down
File renamed without changes.
10 changes: 10 additions & 0 deletions testutil/configurator/configurator.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
genutilmodulev1 "cosmossdk.io/api/cosmos/genutil/module/v1"
govmodulev1 "cosmossdk.io/api/cosmos/gov/module/v1"
paramsmodulev1 "cosmossdk.io/api/cosmos/params/module/v1"
slashingmodulev1 "cosmossdk.io/api/cosmos/slashing/module/v1"
stakingmodulev1 "cosmossdk.io/api/cosmos/staking/module/v1"
txmodulev1 "cosmossdk.io/api/cosmos/tx/module/v1"
vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1"
Expand Down Expand Up @@ -142,6 +143,15 @@ func StakingModule() ModuleOption {
}
}

func SlashingModule() ModuleOption {
return func(config *appConfig) {
config.moduleConfigs["slashing"] = &appv1alpha1.ModuleConfig{
Name: "slashing",
Config: appconfig.WrapAny(&slashingmodulev1.Module{}),
}
}
}

func GenutilModule() ModuleOption {
return func(config *appConfig) {
config.moduleConfigs["genutil"] = &appv1alpha1.ModuleConfig{
Expand Down
68 changes: 45 additions & 23 deletions testutil/sims/app_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,31 +68,52 @@ func CreateRandomValidatorSet() (*tmtypes.ValidatorSet, error) {
return tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}), nil
}

type GenesisAccount struct {
authtypes.GenesisAccount
Coins sdk.Coins
}

// StartupConfig defines the startup configuration new a test application.
//
// ValidatorSet defines a custom validator set to be validating the app.
// BaseAppOption defines the additional operations that must be run on baseapp before app start.
// AtGenesis defines if the app started should already have produced block or not.
type StartupConfig struct {
ValidatorSet func() (*tmtypes.ValidatorSet, error)
BaseAppOption runtime.BaseAppOption
AtGenesis bool
GenesisAccounts []GenesisAccount
}

func DefaultStartUpConfig() StartupConfig {
priv := secp256k1.GenPrivKey()
ba := authtypes.NewBaseAccount(priv.PubKey().Address().Bytes(), priv.PubKey(), 0, 0)
ga := GenesisAccount{ba, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000)))}
return StartupConfig{
ValidatorSet: CreateRandomValidatorSet,
AtGenesis: false,
GenesisAccounts: []GenesisAccount{ga},
}
}

// Setup initializes a new runtime.App and can inject values into extraOutputs.
// It uses SetupWithConfiguration under the hood.
func Setup(appConfig depinject.Config, extraOutputs ...interface{}) (*runtime.App, error) {
return SetupWithConfiguration(appConfig, CreateRandomValidatorSet, nil, false, extraOutputs...)
return SetupWithConfiguration(appConfig, DefaultStartUpConfig(), extraOutputs...)
}

// SetupAtGenesis initializes a new runtime.App at genesis and can inject values into extraOutputs.
// It uses SetupWithConfiguration under the hood.
func SetupAtGenesis(appConfig depinject.Config, extraOutputs ...interface{}) (*runtime.App, error) {
return SetupWithConfiguration(appConfig, CreateRandomValidatorSet, nil, true, extraOutputs...)
}

// SetupWithBaseAppOption initializes a new runtime.App and can inject values into extraOutputs.
// With specific baseApp options. It uses SetupWithConfiguration under the hood.
func SetupWithBaseAppOption(appConfig depinject.Config, baseAppOption runtime.BaseAppOption, extraOutputs ...interface{}) (*runtime.App, error) {
return SetupWithConfiguration(appConfig, CreateRandomValidatorSet, baseAppOption, false, extraOutputs...)
cfg := DefaultStartUpConfig()
cfg.AtGenesis = true
return SetupWithConfiguration(appConfig, cfg, extraOutputs...)
}

// SetupWithConfiguration initializes a new runtime.App. A Nop logger is set in runtime.App.
// appConfig usually load from a `app.yaml` with `appconfig.LoadYAML`, defines the application configuration.
// validatorSet defines a custom validator set to be validating the app.
// baseAppOption defines the additional operations that must be run on baseapp before app start.
// genesis defines if the app started should already have produced block or not.
// extraOutputs defines the extra outputs to be assigned by the dependency injector (depinject).
func SetupWithConfiguration(appConfig depinject.Config, validatorSet func() (*tmtypes.ValidatorSet, error), baseAppOption runtime.BaseAppOption, genesis bool, extraOutputs ...interface{}) (*runtime.App, error) {
func SetupWithConfiguration(appConfig depinject.Config, startupConfig StartupConfig, extraOutputs ...interface{}) (*runtime.App, error) {
// create the app with depinject
var (
app *runtime.App
Expand All @@ -107,8 +128,8 @@ func SetupWithConfiguration(appConfig depinject.Config, validatorSet func() (*tm
return nil, fmt.Errorf("failed to inject dependencies: %w", err)
}

if baseAppOption != nil {
app = appBuilder.Build(log.NewNopLogger(), dbm.NewMemDB(), nil, baseAppOption)
if startupConfig.BaseAppOption != nil {
app = appBuilder.Build(log.NewNopLogger(), dbm.NewMemDB(), nil, startupConfig.BaseAppOption)
} else {
app = appBuilder.Build(log.NewNopLogger(), dbm.NewMemDB(), nil)
}
Expand All @@ -117,20 +138,21 @@ func SetupWithConfiguration(appConfig depinject.Config, validatorSet func() (*tm
}

// create validator set
valSet, err := validatorSet()
valSet, err := startupConfig.ValidatorSet()
if err != nil {
return nil, fmt.Errorf("failed to create validator set")
}

// generate genesis account
senderPrivKey := secp256k1.GenPrivKey()
acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0)
balance := banktypes.Balance{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))),
var (
balances []banktypes.Balance
genAccounts []authtypes.GenesisAccount
)
for _, ga := range startupConfig.GenesisAccounts {
genAccounts = append(genAccounts, ga.GenesisAccount)
balances = append(balances, banktypes.Balance{Address: ga.GenesisAccount.GetAddress().String(), Coins: ga.Coins})
}

genesisState, err := GenesisStateWithValSet(codec, appBuilder.DefaultGenesis(), valSet, []authtypes.GenesisAccount{acc}, balance)
genesisState, err := GenesisStateWithValSet(codec, appBuilder.DefaultGenesis(), valSet, genAccounts, balances...)
if err != nil {
return nil, fmt.Errorf("failed to create genesis state: %w", err)
}
Expand All @@ -151,7 +173,7 @@ func SetupWithConfiguration(appConfig depinject.Config, validatorSet func() (*tm
)

// commit genesis changes
if !genesis {
if !startupConfig.AtGenesis {
app.Commit()
app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{
Height: app.LastBlockHeight() + 1,
Expand Down
59 changes: 59 additions & 0 deletions testutil/sims/tx_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ package sims

import (
"math/rand"
"testing"
"time"

"github.com/stretchr/testify/require"
types2 "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/proto/tendermint/types"

"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -71,3 +78,55 @@ func GenSignedMockTx(r *rand.Rand, txConfig client.TxConfig, msgs []sdk.Msg, fee

return tx.GetTx(), nil
}

// SignCheckDeliver checks a generated signed transaction and simulates a
// block commitment with the given transaction. A test assertion is made using
// the parameter 'expPass' against the result. A corresponding result is
// returned.
func SignCheckDeliver(
t *testing.T, txCfg client.TxConfig, app *baseapp.BaseApp, header types.Header, msgs []sdk.Msg,
chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey,
) (sdk.GasInfo, *sdk.Result, error) {
tx, err := GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
DefaultGenTxGas,
chainID,
accNums,
accSeqs,
priv...,
)
require.NoError(t, err)
txBytes, err := txCfg.TxEncoder()(tx)
require.Nil(t, err)

// Must simulate now as CheckTx doesn't run Msgs anymore
_, res, err := app.Simulate(txBytes)

if expSimPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}

// Simulate a sending a transaction and committing a block
app.BeginBlock(types2.RequestBeginBlock{Header: header})
gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx)

if expPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}

app.EndBlock(types2.RequestEndBlock{})
app.Commit()

return gInfo, res, err
}
9 changes: 5 additions & 4 deletions x/auth/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import (
"encoding/json"
"fmt"

modulev1 "cosmossdk.io/api/cosmos/auth/module/v1"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
abci "github.com/tendermint/tendermint/abci/types"

modulev1 "cosmossdk.io/api/cosmos/auth/module/v1"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
Expand Down Expand Up @@ -199,7 +200,7 @@ type authInputs struct {
Cdc codec.Codec

// LegacySubspace is used solely for migration of x/params managed parameters
LegacySubspace exported.Subspace
LegacySubspace exported.Subspace `optional:"true"`
}

type authOutputs struct {
Expand Down
Loading

0 comments on commit 15b04c2

Please sign in to comment.