Skip to content

Commit

Permalink
feat: Migrate keeper tests to ginkgo
Browse files Browse the repository at this point in the history
  • Loading branch information
DaevMithran committed Nov 30, 2022
1 parent 5902c83 commit 4d25027
Show file tree
Hide file tree
Showing 7 changed files with 338 additions and 587 deletions.
15 changes: 11 additions & 4 deletions ante/testutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,11 @@ type AnteTestSuite struct {
}

// returns context and app with params set on account keeper
func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) {
app := simapp.SetupForGinkgo(isCheckTx)
func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context, error) {
app, err := simapp.Setup(isCheckTx)
if err != nil {
return nil, sdk.Context{}, err
}
ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{})
app.AccountKeeper.SetParams(ctx, authtypes.DefaultParams())

Expand All @@ -53,7 +56,7 @@ func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) {
resourceFeeParams := resourcetypes.DefaultGenesis().FeeParams
app.ResourceKeeper.SetParams(ctx, *resourceFeeParams)

return app, ctx
return app, ctx, nil
}

// func TestAnteTestSuite(t *testing.T) {
Expand All @@ -62,7 +65,11 @@ func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) {

// SetupTest setups a new test, with new app, context, and anteHandler.
func (s *AnteTestSuite) SetupTest(isCheckTx bool) error {
s.app, s.ctx = createTestApp(isCheckTx)
var err error
s.app, s.ctx, err = createTestApp(isCheckTx)
if err != nil {
return err
}
s.ctx = s.ctx.WithBlockHeight(1)
// Set up TxConfig.
encodingConfig := cheqdapp.MakeTestEncodingConfig()
Expand Down
244 changes: 149 additions & 95 deletions simapp/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ import (
"encoding/json"
"fmt"
"math/rand"
"reflect"
"strconv"
"testing"
"time"

"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
Expand Down Expand Up @@ -85,12 +84,12 @@ func setup(withGenesis bool, invCheckPeriod uint) (*SimApp, cheqdapp.GenesisStat
}

// NewSimappWithCustomOptions initializes a new SimApp with custom options.
func NewSimappWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptions) *SimApp {
t.Helper()

func NewSimappWithCustomOptions(isCheckTx bool, options SetupOptions) (*SimApp, error) {
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
require.NoError(t, err)
if err != nil {
return nil, err
}
// create validator set with single validator
validator := tmtypes.NewValidator(pubKey, 1)
valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator})
Expand All @@ -105,12 +104,17 @@ func NewSimappWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptio

app := NewSimApp(options.Logger, options.DB, nil, true, options.SkipUpgradeHeights, options.HomePath, options.InvCheckPeriod, options.EncConfig, options.AppOpts)
genesisState := cheqdapp.NewDefaultGenesisState(app.appCodec)
genesisState = genesisStateWithValSet(t, app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance)
genesisState, err = genesisStateWithValSet(app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance)
if err != nil {
return nil, err
}

if !isCheckTx {
// init chain must be called to stop deliverState from being nil
stateBytes, err := tmjson.MarshalIndent(genesisState, "", " ")
require.NoError(t, err)
if err != nil {
return nil, err
}

// Initialize the chain
app.InitChain(
Expand All @@ -122,16 +126,16 @@ func NewSimappWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptio
)
}

return app
return app, nil
}

// Setup initializes a new SimApp. A Nop logger is set in SimApp.
func Setup(t *testing.T, isCheckTx bool) *SimApp {
t.Helper()

func Setup(isCheckTx bool) (*SimApp, error) {
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
require.NoError(t, err)
if err != nil {
return nil, err
}

// create validator set with single validator
validator := tmtypes.NewValidator(pubKey, 1)
Expand All @@ -145,16 +149,46 @@ func Setup(t *testing.T, isCheckTx bool) *SimApp {
Coins: sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100000000000000))),
}

app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance)
app, err := SetupWithGenesisValSet(valSet, []authtypes.GenesisAccount{acc}, balance)
if err != nil {
return nil, err
}

return app
return app, nil
}

func genesisStateWithValSet(t *testing.T,
// Setup initializes a new SimApp. A Nop logger is set in SimApp.
func SetupTest(isCheckTx bool) (*SimApp, error) {
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
if err != nil {
return nil, err
}
// create validator set with single validator
validator := tmtypes.NewValidator(pubKey, 1)
valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator})

// 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(didtypes.BaseMinimalDenom, sdk.NewInt(100000000000000))),
}

app, err := SetupWithGenesisValSet(valSet, []authtypes.GenesisAccount{acc}, balance)
if err != nil {
return nil, err
}

return app, nil
}

func genesisStateWithValSet(
app *SimApp, genesisState cheqdapp.GenesisState,
valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount,
balances ...banktypes.Balance,
) cheqdapp.GenesisState {
) (cheqdapp.GenesisState, error) {
// set genesis accounts
authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs)
genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis)
Expand All @@ -166,9 +200,13 @@ func genesisStateWithValSet(t *testing.T,

for _, val := range valSet.Validators {
pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey)
require.NoError(t, err)
if err != nil {
return nil, err
}
pkAny, err := codectypes.NewAnyWithValue(pk)
require.NoError(t, err)
if err != nil {
return nil, err
}
validator := stakingtypes.Validator{
OperatorAddress: sdk.ValAddress(val.Address).String(),
ConsensusPubkey: pkAny,
Expand Down Expand Up @@ -219,21 +257,24 @@ func genesisStateWithValSet(t *testing.T,
resourceGenesis := resourcetypes.DefaultGenesis()
genesisState[resourcetypes.ModuleName] = app.AppCodec().MustMarshalJSON(resourceGenesis)

return genesisState
return genesisState, nil
}

// SetupWithGenesisValSet initializes a new SimApp with a validator set and genesis accounts
// that also act as delegators. For simplicity, each validator is bonded with a delegation
// of one consensus engine unit in the default token of the simapp from first genesis
// account. A Nop logger is set in SimApp.
func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp {
t.Helper()

func SetupWithGenesisValSet(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) (*SimApp, error) {
app, genesisState := setup(true, 5)
genesisState = genesisStateWithValSet(t, app, genesisState, valSet, genAccs, balances...)
genesisState, err := genesisStateWithValSet(app, genesisState, valSet, genAccs, balances...)
if err != nil {
return nil, err
}

stateBytes, err := json.MarshalIndent(genesisState, "", " ")
require.NoError(t, err)
if err != nil {
return nil, err
}

// init chain will set the validator set and initialize the genesis accounts
app.InitChain(
Expand All @@ -253,33 +294,33 @@ func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs
NextValidatorsHash: valSet.Hash(),
}})

return app
return app, nil
}

// SetupWithGenesisAccounts initializes a new SimApp with the provided genesis
// accounts and possible balances.
func SetupWithGenesisAccounts(t *testing.T, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp {
t.Helper()

func SetupWithGenesisAccounts(genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) (*SimApp, error) {
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
require.NoError(t, err)
if err != nil {
return nil, err
}

// create validator set with single validator
validator := tmtypes.NewValidator(pubKey, 1)
valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator})

return SetupWithGenesisValSet(t, valSet, genAccs, balances...)
return SetupWithGenesisValSet(valSet, genAccs, balances...)
}

// GenesisStateWithSingleValidator initializes GenesisState with a single validator and genesis accounts
// that also act as delegators.
func GenesisStateWithSingleValidator(t *testing.T, app *SimApp) cheqdapp.GenesisState {
t.Helper()

func GenesisStateWithSingleValidator(app *SimApp) (cheqdapp.GenesisState, error) {
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
require.NoError(t, err)
if err != nil {
return nil, err
}

// create validator set with single validator
validator := tmtypes.NewValidator(pubKey, 1)
Expand All @@ -296,9 +337,80 @@ func GenesisStateWithSingleValidator(t *testing.T, app *SimApp) cheqdapp.Genesis
}

genesisState := cheqdapp.NewDefaultGenesisState(app.appCodec)
genesisState = genesisStateWithValSet(t, app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...)
genesisState, err = genesisStateWithValSet(app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...)
if err != nil {
return nil, err
}

return genesisState, nil
}

return genesisState
// CheckBalance checks the balance of an account.
func CheckBalance(app *SimApp, addr sdk.AccAddress, balances sdk.Coins) {
ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{})
if reflect.DeepEqual(balances, app.BankKeeper.GetAllBalances(ctxCheck, addr)) {
panic("Invalid balance of account")
}
}

// 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(
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 := helpers.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
helpers.DefaultGenTxGas,
chainID,
accNums,
accSeqs,
priv...,
)
if err != nil {
return sdk.GasInfo{}, nil, err
}
txBytes, err := txCfg.TxEncoder()(tx)
if err != nil {
return sdk.GasInfo{}, nil, err
}

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

if expSimPass {
if err != nil || res == nil {
return sdk.GasInfo{}, nil, err
}
} else {
if err == nil || res != nil {
return sdk.GasInfo{}, nil, err
}
}

// 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 {
if err != nil || res == nil {
return sdk.GasInfo{}, nil, err
}
} else {
if err == nil || res != nil {
return sdk.GasInfo{}, nil, err
}
}

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

return gInfo, res, err
}

type GenerateAccountStrategy func(int) []sdk.AccAddress
Expand Down Expand Up @@ -413,64 +525,6 @@ func TestAddr(addr string, bech string) (sdk.AccAddress, error) {
return res, nil
}

// CheckBalance checks the balance of an account.
func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.Coins) {
ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{})
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 := helpers.GenSignedMockTx(
rand.New(rand.NewSource(time.Now().UnixNano())),
txCfg,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
helpers.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.
Expand Down
Loading

0 comments on commit 4d25027

Please sign in to comment.