cosmos-sdk/x/genutil/gentx_test.go

286 lines
7.5 KiB
Go
Raw Normal View History

package genutil_test
Merge PR #4159: Module/Genesis Generalization * first commit * gaia cleanup * ... * staking multihooks * missing module function return args * bank module name constant * working, module interface for x/ * got this thing compiling * make test compiles and passes * remove expanded simulation invariants * genesis issue * continued * continued * register crisis routes thought mm * begin blocker to mm * end blocker to mm * empty routes not initialized * move gaia initChainer sanity check to baseapp * remove codecs from module manager * reorging genesis stuff * module manager passed by reference/bugfixes from working last commit int int * move invariant checks from gaia to crisis * typo * basic refactors cmd/gaia/init * working * MultiStakingHooks from types to x/staking/types int * default module manager order of operations from input modules * working * typo * add AppModuleBasic * moduleBasicManager / non-test code compiles * working attempting to get tests passing * make test passes * sim random genesis fix * export bug * ... * genutil module * genutil working * refactored - happy with non-testing code in cmd/ * ... * lint fixes * comment improvement * cli test fix * compile housing * working through compile errors * working gettin' compilin' * non-test code compiles * move testnet to its own module * reworking tests int * bez staging PR 1 comments * concise module function-of names * moved all tests from genesis_test.go to other genutil tests * genaccounts package, add genutil and genaccounts to app.go * docs for genutil genaccounts * genaccounts iterate fn * non-test code with genaccounts/ now compiles * working test compiling * debugging tests * resolved all make test compile errors * test debuggin * resolved all unit tests, introduced param module * cli-test compile fixes * staking initialization bug * code comment improvements, changelog entries * BasicGaiaApp -> ModuleBasics * highlevel explanation in types/module.go * @alexanderbez comment revisions * @fedekunze PR comments * @alexanderbez PR comments (x2) * @cwgoes comments (minor updates) * @fedekunze suggestions * panic on init with multiple validator updates from different modules * initchain panic makes validate genesis fail int * AppModuleGenesis seperation int * test * remove init panic logic in validate genesis replaced with TODO * set maxprocs to match system's GOMAXPROCS * Update circleci * Cap maxprocs in CI to 4 * @alexanderbez recent comments addressed * less blocks in twouble sims int * runsim error output flag * -e on import_export as well * error out int * Try to fix failures * runsim
2019-05-16 08:25:32 -07:00
import (
"encoding/json"
"fmt"
"testing"
Merge PR #4159: Module/Genesis Generalization * first commit * gaia cleanup * ... * staking multihooks * missing module function return args * bank module name constant * working, module interface for x/ * got this thing compiling * make test compiles and passes * remove expanded simulation invariants * genesis issue * continued * continued * register crisis routes thought mm * begin blocker to mm * end blocker to mm * empty routes not initialized * move gaia initChainer sanity check to baseapp * remove codecs from module manager * reorging genesis stuff * module manager passed by reference/bugfixes from working last commit int int * move invariant checks from gaia to crisis * typo * basic refactors cmd/gaia/init * working * MultiStakingHooks from types to x/staking/types int * default module manager order of operations from input modules * working * typo * add AppModuleBasic * moduleBasicManager / non-test code compiles * working attempting to get tests passing * make test passes * sim random genesis fix * export bug * ... * genutil module * genutil working * refactored - happy with non-testing code in cmd/ * ... * lint fixes * comment improvement * cli test fix * compile housing * working through compile errors * working gettin' compilin' * non-test code compiles * move testnet to its own module * reworking tests int * bez staging PR 1 comments * concise module function-of names * moved all tests from genesis_test.go to other genutil tests * genaccounts package, add genutil and genaccounts to app.go * docs for genutil genaccounts * genaccounts iterate fn * non-test code with genaccounts/ now compiles * working test compiling * debugging tests * resolved all make test compile errors * test debuggin * resolved all unit tests, introduced param module * cli-test compile fixes * staking initialization bug * code comment improvements, changelog entries * BasicGaiaApp -> ModuleBasics * highlevel explanation in types/module.go * @alexanderbez comment revisions * @fedekunze PR comments * @alexanderbez PR comments (x2) * @cwgoes comments (minor updates) * @fedekunze suggestions * panic on init with multiple validator updates from different modules * initchain panic makes validate genesis fail int * AppModuleGenesis seperation int * test * remove init panic logic in validate genesis replaced with TODO * set maxprocs to match system's GOMAXPROCS * Update circleci * Cap maxprocs in CI to 4 * @alexanderbez recent comments addressed * less blocks in twouble sims int * runsim error output flag * -e on import_export as well * error out int * Try to fix failures * runsim
2019-05-16 08:25:32 -07:00
"github.com/stretchr/testify/suite"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/simapp/helpers"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/cosmos/cosmos-sdk/x/staking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
var (
priv1 = secp256k1.GenPrivKey()
priv2 = secp256k1.GenPrivKey()
pk1 = priv1.PubKey()
pk2 = priv2.PubKey()
addr1 = sdk.AccAddress(pk1.Address())
addr2 = sdk.AccAddress(pk2.Address())
desc = stakingtypes.NewDescription("testname", "", "", "", "")
comm = stakingtypes.CommissionRates{}
)
// GenTxTestSuite is a test suite to be used with gentx tests.
type GenTxTestSuite struct {
suite.Suite
ctx sdk.Context
app *simapp.SimApp
encodingConfig simappparams.EncodingConfig
msg1, msg2 *stakingtypes.MsgCreateValidator
}
func (suite *GenTxTestSuite) SetupTest() {
checkTx := false
refactor(test)!: refactor `simapp.Setup` function (#9938) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description ref: #8961 <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> Following up on [#9697](https://github.com/cosmos/cosmos-sdk/pull/9697#pullrequestreview-727295733), this PR is the first step for the #8961. --- ### 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... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [x] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [x] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [x] 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)
2021-08-16 17:52:06 -07:00
app := simapp.Setup(suite.T(), checkTx)
suite.ctx = app.BaseApp.NewContext(checkTx, tmproto.Header{})
suite.app = app
suite.encodingConfig = simapp.MakeTestEncodingConfig()
var err error
amount := sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)
one := sdk.OneInt()
suite.msg1, err = stakingtypes.NewMsgCreateValidator(
sdk.ValAddress(pk1.Address()), pk1, amount, desc, comm, one)
suite.NoError(err)
suite.msg2, err = stakingtypes.NewMsgCreateValidator(
sdk.ValAddress(pk2.Address()), pk1, amount, desc, comm, one)
suite.NoError(err)
}
func (suite *GenTxTestSuite) setAccountBalance(addr sdk.AccAddress, amount int64) json.RawMessage {
acc := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr)
suite.app.AccountKeeper.SetAccount(suite.ctx, acc)
err := testutil.FundAccount(suite.app.BankKeeper, suite.ctx, addr, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 25)})
suite.Require().NoError(err)
bankGenesisState := suite.app.BankKeeper.ExportGenesis(suite.ctx)
bankGenesis, err := suite.encodingConfig.Amino.MarshalJSON(bankGenesisState) // TODO switch this to use Marshaler
suite.Require().NoError(err)
return bankGenesis
}
func (suite *GenTxTestSuite) TestSetGenTxsInAppGenesisState() {
var (
txBuilder = suite.encodingConfig.TxConfig.NewTxBuilder()
genTxs []sdk.Tx
)
testCases := []struct {
msg string
malleate func()
expPass bool
}{
{
"one genesis transaction",
func() {
err := txBuilder.SetMsgs(suite.msg1)
suite.Require().NoError(err)
tx := txBuilder.GetTx()
genTxs = []sdk.Tx{tx}
},
true,
},
{
"two genesis transactions",
func() {
err := txBuilder.SetMsgs(suite.msg1, suite.msg2)
suite.Require().NoError(err)
tx := txBuilder.GetTx()
genTxs = []sdk.Tx{tx}
},
true,
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
suite.SetupTest()
refactor!: Remove `clientCtx.JSONCodec` and rename `EncodingConfig.Marshaler` to `Codec` (#9521) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description Closes: #9499 <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> --- ### 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... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [x] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [x] provided a link to the relevant issue or specification - [x] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [x] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [x] reviewed "Files changed" and left comments if necessary - [x] 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)
2021-07-01 01:52:38 -07:00
cdc := suite.encodingConfig.Codec
txJSONEncoder := suite.encodingConfig.TxConfig.TxJSONEncoder()
tc.malleate()
appGenesisState, err := genutil.SetGenTxsInAppGenesisState(cdc, txJSONEncoder, make(map[string]json.RawMessage), genTxs)
if tc.expPass {
suite.Require().NoError(err)
suite.Require().NotNil(appGenesisState[types.ModuleName])
var genesisState types.GenesisState
err := cdc.UnmarshalJSON(appGenesisState[types.ModuleName], &genesisState)
suite.Require().NoError(err)
suite.Require().NotNil(genesisState.GenTxs)
} else {
suite.Require().Error(err)
}
})
}
}
func (suite *GenTxTestSuite) TestValidateAccountInGenesis() {
var (
appGenesisState = make(map[string]json.RawMessage)
coins sdk.Coins
)
testCases := []struct {
msg string
malleate func()
expPass bool
}{
{
"no accounts",
func() {
coins = sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}
},
false,
},
{
"account without balance in the genesis state",
func() {
coins = sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}
appGenesisState[banktypes.ModuleName] = suite.setAccountBalance(addr2, 50)
},
false,
},
{
"account without enough funds of default bond denom",
func() {
coins = sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}
appGenesisState[banktypes.ModuleName] = suite.setAccountBalance(addr1, 25)
},
false,
},
{
"account with enough funds of default bond denom",
func() {
coins = sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 10)}
appGenesisState[banktypes.ModuleName] = suite.setAccountBalance(addr1, 25)
},
true,
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
suite.SetupTest()
refactor!: Remove `clientCtx.JSONCodec` and rename `EncodingConfig.Marshaler` to `Codec` (#9521) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description Closes: #9499 <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> --- ### 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... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [x] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [x] provided a link to the relevant issue or specification - [x] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [x] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [x] reviewed "Files changed" and left comments if necessary - [x] 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)
2021-07-01 01:52:38 -07:00
cdc := suite.encodingConfig.Codec
suite.app.StakingKeeper.SetParams(suite.ctx, stakingtypes.DefaultParams())
stakingGenesisState := staking.ExportGenesis(suite.ctx, suite.app.StakingKeeper)
suite.Require().Equal(stakingGenesisState.Params, stakingtypes.DefaultParams())
stakingGenesis, err := cdc.MarshalJSON(stakingGenesisState) // TODO switch this to use Marshaler
suite.Require().NoError(err)
appGenesisState[stakingtypes.ModuleName] = stakingGenesis
tc.malleate()
err = genutil.ValidateAccountInGenesis(
appGenesisState, banktypes.GenesisBalancesIterator{},
addr1, coins, cdc,
)
if tc.expPass {
suite.Require().NoError(err)
} else {
suite.Require().Error(err)
}
})
}
}
func (suite *GenTxTestSuite) TestDeliverGenTxs() {
var (
genTxs []json.RawMessage
txBuilder = suite.encodingConfig.TxConfig.NewTxBuilder()
)
testCases := []struct {
msg string
malleate func()
expPass bool
}{
{
"no signature supplied",
func() {
err := txBuilder.SetMsgs(suite.msg1)
suite.Require().NoError(err)
genTxs = make([]json.RawMessage, 1)
tx, err := suite.encodingConfig.TxConfig.TxJSONEncoder()(txBuilder.GetTx())
suite.Require().NoError(err)
genTxs[0] = tx
},
false,
},
{
"success",
func() {
_ = suite.setAccountBalance(addr1, 50)
_ = suite.setAccountBalance(addr2, 0)
msg := banktypes.NewMsgSend(addr1, addr2, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)})
tx, err := helpers.GenTx(
suite.encodingConfig.TxConfig,
[]sdk.Msg{msg},
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 10)},
helpers.DefaultGenTxGas,
suite.ctx.ChainID(),
[]uint64{0},
[]uint64{0},
priv1,
)
suite.Require().NoError(err)
genTxs = make([]json.RawMessage, 1)
genTx, err := suite.encodingConfig.TxConfig.TxJSONEncoder()(tx)
suite.Require().NoError(err)
genTxs[0] = genTx
},
true,
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
suite.SetupTest()
tc.malleate()
if tc.expPass {
suite.Require().NotPanics(func() {
genutil.DeliverGenTxs(
suite.ctx, genTxs, suite.app.StakingKeeper, suite.app.BaseApp.DeliverTx,
suite.encodingConfig.TxConfig,
)
})
} else {
suite.Require().Panics(func() {
genutil.DeliverGenTxs(
suite.ctx, genTxs, suite.app.StakingKeeper, suite.app.BaseApp.DeliverTx,
suite.encodingConfig.TxConfig,
)
})
}
})
}
}
func TestGenTxTestSuite(t *testing.T) {
suite.Run(t, new(GenTxTestSuite))
Merge PR #4159: Module/Genesis Generalization * first commit * gaia cleanup * ... * staking multihooks * missing module function return args * bank module name constant * working, module interface for x/ * got this thing compiling * make test compiles and passes * remove expanded simulation invariants * genesis issue * continued * continued * register crisis routes thought mm * begin blocker to mm * end blocker to mm * empty routes not initialized * move gaia initChainer sanity check to baseapp * remove codecs from module manager * reorging genesis stuff * module manager passed by reference/bugfixes from working last commit int int * move invariant checks from gaia to crisis * typo * basic refactors cmd/gaia/init * working * MultiStakingHooks from types to x/staking/types int * default module manager order of operations from input modules * working * typo * add AppModuleBasic * moduleBasicManager / non-test code compiles * working attempting to get tests passing * make test passes * sim random genesis fix * export bug * ... * genutil module * genutil working * refactored - happy with non-testing code in cmd/ * ... * lint fixes * comment improvement * cli test fix * compile housing * working through compile errors * working gettin' compilin' * non-test code compiles * move testnet to its own module * reworking tests int * bez staging PR 1 comments * concise module function-of names * moved all tests from genesis_test.go to other genutil tests * genaccounts package, add genutil and genaccounts to app.go * docs for genutil genaccounts * genaccounts iterate fn * non-test code with genaccounts/ now compiles * working test compiling * debugging tests * resolved all make test compile errors * test debuggin * resolved all unit tests, introduced param module * cli-test compile fixes * staking initialization bug * code comment improvements, changelog entries * BasicGaiaApp -> ModuleBasics * highlevel explanation in types/module.go * @alexanderbez comment revisions * @fedekunze PR comments * @alexanderbez PR comments (x2) * @cwgoes comments (minor updates) * @fedekunze suggestions * panic on init with multiple validator updates from different modules * initchain panic makes validate genesis fail int * AppModuleGenesis seperation int * test * remove init panic logic in validate genesis replaced with TODO * set maxprocs to match system's GOMAXPROCS * Update circleci * Cap maxprocs in CI to 4 * @alexanderbez recent comments addressed * less blocks in twouble sims int * runsim error output flag * -e on import_export as well * error out int * Try to fix failures * runsim
2019-05-16 08:25:32 -07:00
}