chore: Replace testify with gotest.tools in staking integration tests (#14504)

This commit is contained in:
Likhita Polavarapu 2023-01-11 18:50:20 +05:30 committed by GitHub
parent d5bcfb3f3e
commit f7ead8cbd8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 1051 additions and 848 deletions

View File

@ -7,25 +7,22 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"cosmossdk.io/math"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"gotest.tools/v3/assert"
"cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/testutil/configurator"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdktestutil "github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/configurator"
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/auth"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
_ "github.com/cosmos/cosmos-sdk/x/auth/tx/config"
_ "github.com/cosmos/cosmos-sdk/x/bank"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
_ "github.com/cosmos/cosmos-sdk/x/consensus"
@ -33,6 +30,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/genutil/types"
_ "github.com/cosmos/cosmos-sdk/x/params"
_ "github.com/cosmos/cosmos-sdk/x/staking"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -299,7 +297,7 @@ func TestDeliverGenTxs(t *testing.T) {
tc.malleate()
if tc.expPass {
require.NotPanics(t, func() {
sdktestutil.AssertNotPanics(t, func() {
genutil.DeliverGenTxs(
f.ctx, genTxs, f.stakingKeeper, f.baseApp.DeliverTx,
f.encodingConfig.TxConfig,

View File

@ -4,10 +4,10 @@ import (
"math/big"
"testing"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"cosmossdk.io/simapp"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"gotest.tools/v3/assert"
"github.com/cosmos/cosmos-sdk/codec"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -48,14 +48,14 @@ func ValEq(t *testing.T, exp, got types.Validator) (*testing.T, bool, string, ty
// generateAddresses generates numAddrs of normal AccAddrs and ValAddrs
func generateAddresses(app *simapp.SimApp, ctx sdk.Context, numAddrs int) ([]sdk.AccAddress, []sdk.ValAddress) {
addrDels := simapp.AddTestAddrsIncremental(app, ctx, numAddrs, sdk.NewInt(10000))
addrDels := simtestutil.AddTestAddrsIncremental(app.BankKeeper, app.StakingKeeper, ctx, numAddrs, sdk.NewInt(10000))
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
return addrDels, addrVals
}
func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress, []types.Validator) {
addrs := simapp.AddTestAddrsIncremental(app, ctx, 5, app.StakingKeeper.TokensFromConsensusPower(ctx, 300))
addrs := simtestutil.AddTestAddrsIncremental(app.BankKeeper, app.StakingKeeper, ctx, 5, app.StakingKeeper.TokensFromConsensusPower(ctx, 300))
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
pks := simtestutil.CreateTestPubKeys(5)
cdc := moduletestutil.MakeTestEncodingConfig().Codec
@ -79,11 +79,11 @@ func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers
app.StakingKeeper.SetNewValidatorByPowerIndex(ctx, val2)
_, err := app.StakingKeeper.Delegate(ctx, addrs[0], app.StakingKeeper.TokensFromConsensusPower(ctx, powers[0]), types.Unbonded, val1, true)
require.NoError(t, err)
assert.NilError(t, err)
_, err = app.StakingKeeper.Delegate(ctx, addrs[1], app.StakingKeeper.TokensFromConsensusPower(ctx, powers[1]), types.Unbonded, val2, true)
require.NoError(t, err)
assert.NilError(t, err)
_, err = app.StakingKeeper.Delegate(ctx, addrs[0], app.StakingKeeper.TokensFromConsensusPower(ctx, powers[2]), types.Unbonded, val2, true)
require.NoError(t, err)
assert.NilError(t, err)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
return addrs, valAddrs, vals

View File

@ -5,9 +5,8 @@ import (
"time"
"cosmossdk.io/math"
"github.com/stretchr/testify/require"
"gotest.tools/v3/assert"
"cosmossdk.io/simapp"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
@ -19,7 +18,7 @@ import (
func TestUnbondingDelegationsMaxEntries(t *testing.T) {
_, app, ctx := createTestInput(t)
addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.NewInt(10000))
addrDels := simtestutil.AddTestAddrsIncremental(app.BankKeeper, app.StakingKeeper, ctx, 1, sdk.NewInt(10000))
addrVals := simtestutil.ConvertAddrsToValAddrs(addrDels)
startTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10)
@ -27,18 +26,18 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) {
bondDenom := app.StakingKeeper.BondDenom(ctx)
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, startTokens))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, startTokens))))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
// create a validator and a delegator to that validator
validator := testutil.NewValidator(t, addrVals[0], PKs[0])
validator, issuedShares := validator.AddTokensFromDel(startTokens)
require.Equal(t, startTokens, issuedShares.RoundInt())
assert.DeepEqual(t, startTokens, issuedShares.RoundInt())
validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true)
require.True(math.IntEq(t, startTokens, validator.BondedTokens()))
require.True(t, validator.IsBonded())
assert.Assert(math.IntEq(t, startTokens, validator.BondedTokens()))
assert.Assert(t, validator.IsBonded())
delegation := types.NewDelegation(addrDels[0], addrVals[0], issuedShares)
app.StakingKeeper.SetDelegation(ctx, delegation)
@ -54,45 +53,45 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) {
var err error
ctx = ctx.WithBlockHeight(i)
completionTime, err = app.StakingKeeper.Undelegate(ctx, addrDels[0], addrVals[0], math.LegacyNewDec(1))
require.NoError(t, err)
assert.NilError(t, err)
}
newBonded := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
newNotBonded := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, newBonded, oldBonded.SubRaw(int64(maxEntries))))
require.True(math.IntEq(t, newNotBonded, oldNotBonded.AddRaw(int64(maxEntries))))
assert.Assert(math.IntEq(t, newBonded, oldBonded.SubRaw(int64(maxEntries))))
assert.Assert(math.IntEq(t, newNotBonded, oldNotBonded.AddRaw(int64(maxEntries))))
oldBonded = app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
oldNotBonded = app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
// an additional unbond should fail due to max entries
_, err := app.StakingKeeper.Undelegate(ctx, addrDels[0], addrVals[0], math.LegacyNewDec(1))
require.Error(t, err)
assert.Error(t, err, "too many unbonding delegation entries for (delegator, validator) tuple")
newBonded = app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
newNotBonded = app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, newBonded, oldBonded))
require.True(math.IntEq(t, newNotBonded, oldNotBonded))
assert.Assert(math.IntEq(t, newBonded, oldBonded))
assert.Assert(math.IntEq(t, newNotBonded, oldNotBonded))
// mature unbonding delegations
ctx = ctx.WithBlockTime(completionTime)
_, err = app.StakingKeeper.CompleteUnbonding(ctx, addrDels[0], addrVals[0])
require.NoError(t, err)
assert.NilError(t, err)
newBonded = app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
newNotBonded = app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, newBonded, oldBonded))
require.True(math.IntEq(t, newNotBonded, oldNotBonded.SubRaw(int64(maxEntries))))
assert.Assert(math.IntEq(t, newBonded, oldBonded))
assert.Assert(math.IntEq(t, newNotBonded, oldNotBonded.SubRaw(int64(maxEntries))))
oldNotBonded = app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
// unbonding should work again
_, err = app.StakingKeeper.Undelegate(ctx, addrDels[0], addrVals[0], math.LegacyNewDec(1))
require.NoError(t, err)
assert.NilError(t, err)
newBonded = app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
newNotBonded = app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, newBonded, oldBonded.SubRaw(1)))
require.True(math.IntEq(t, newNotBonded, oldNotBonded.AddRaw(1)))
assert.Assert(math.IntEq(t, newBonded, oldBonded.SubRaw(1)))
assert.Assert(math.IntEq(t, newNotBonded, oldNotBonded.AddRaw(1)))
}

View File

@ -5,8 +5,9 @@ import (
"time"
"cosmossdk.io/math"
"github.com/stretchr/testify/suite"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"gotest.tools/v3/assert"
"pgregory.net/rapid"
"github.com/cosmos/cosmos-sdk/baseapp"
@ -21,7 +22,6 @@ import (
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtestutil "github.com/cosmos/cosmos-sdk/x/staking/testutil"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
@ -36,9 +36,7 @@ var (
delegatorAddr2 = sdk.MustAccAddressFromBech32(delegator2)
)
type DeterministicTestSuite struct {
suite.Suite
type deterministicFixture struct {
ctx sdk.Context
stakingKeeper *stakingkeeper.Keeper
bankKeeper bankkeeper.BaseKeeper
@ -48,31 +46,30 @@ type DeterministicTestSuite struct {
amt2 math.Int
}
func (s *DeterministicTestSuite) SetupTest() {
func initDeterministicFixture(t *testing.T) *deterministicFixture {
f := &deterministicFixture{}
var interfaceRegistry codectypes.InterfaceRegistry
app, err := simtestutil.Setup(
stakingtestutil.AppConfig,
&s.bankKeeper,
&s.accountKeeper,
&s.stakingKeeper,
&f.bankKeeper,
&f.accountKeeper,
&f.stakingKeeper,
&interfaceRegistry,
)
s.Require().NoError(err)
assert.NilError(t, err)
// s.ctx = app.BaseApp.NewContext(false, tmproto.Header{Height: 1, Time: time.Now()}).WithGasMeter(storetypes.NewInfiniteGasMeter())
s.ctx = app.BaseApp.NewContext(false, tmproto.Header{})
f.ctx = app.BaseApp.NewContext(false, tmproto.Header{})
queryHelper := baseapp.NewQueryServerTestHelper(s.ctx, interfaceRegistry)
stakingtypes.RegisterQueryServer(queryHelper, stakingkeeper.Querier{Keeper: s.stakingKeeper})
s.queryClient = stakingtypes.NewQueryClient(queryHelper)
queryHelper := baseapp.NewQueryServerTestHelper(f.ctx, interfaceRegistry)
stakingtypes.RegisterQueryServer(queryHelper, stakingkeeper.Querier{Keeper: f.stakingKeeper})
f.queryClient = stakingtypes.NewQueryClient(queryHelper)
s.amt1 = s.stakingKeeper.TokensFromConsensusPower(s.ctx, 101)
s.amt2 = s.stakingKeeper.TokensFromConsensusPower(s.ctx, 102)
}
f.amt1 = f.stakingKeeper.TokensFromConsensusPower(f.ctx, 101)
f.amt2 = f.stakingKeeper.TokensFromConsensusPower(f.ctx, 102)
func TestDeterministicTestSuite(t *testing.T) {
suite.Run(t, new(DeterministicTestSuite))
return f
}
func durationGenerator() *rapid.Generator[time.Duration] {
@ -99,69 +96,69 @@ func bondTypeGenerator() *rapid.Generator[stakingtypes.BondStatus] {
}
// createValidator creates a validator with random values.
func (suite *DeterministicTestSuite) createValidator(t *rapid.T) stakingtypes.Validator {
pubkey := pubKeyGenerator().Draw(t, "pubkey")
func createValidator(rt *rapid.T, f *deterministicFixture, t *testing.T) stakingtypes.Validator {
pubkey := pubKeyGenerator().Draw(rt, "pubkey")
pubkeyAny, err := codectypes.NewAnyWithValue(&pubkey)
suite.Require().NoError(err)
assert.NilError(t, err)
return stakingtypes.Validator{
OperatorAddress: sdk.ValAddress(testdata.AddressGenerator(t).Draw(t, "address")).String(),
OperatorAddress: sdk.ValAddress(testdata.AddressGenerator(rt).Draw(rt, "address")).String(),
ConsensusPubkey: pubkeyAny,
Jailed: rapid.Bool().Draw(t, "jailed"),
Status: bondTypeGenerator().Draw(t, "bond-status"),
Tokens: sdk.NewInt(rapid.Int64Min(10000).Draw(t, "tokens")),
DelegatorShares: sdk.NewDecWithPrec(rapid.Int64Range(1, 100).Draw(t, "commission"), 2),
Jailed: rapid.Bool().Draw(rt, "jailed"),
Status: bondTypeGenerator().Draw(rt, "bond-status"),
Tokens: sdk.NewInt(rapid.Int64Min(10000).Draw(rt, "tokens")),
DelegatorShares: sdk.NewDecWithPrec(rapid.Int64Range(1, 100).Draw(rt, "commission"), 2),
Description: stakingtypes.NewDescription(
rapid.StringN(5, 250, 255).Draw(t, "moniker"),
rapid.StringN(5, 250, 255).Draw(t, "identity"),
rapid.StringN(5, 250, 255).Draw(t, "website"),
rapid.StringN(5, 250, 255).Draw(t, "securityContact"),
rapid.StringN(5, 250, 255).Draw(t, "details"),
rapid.StringN(5, 250, 255).Draw(rt, "moniker"),
rapid.StringN(5, 250, 255).Draw(rt, "identity"),
rapid.StringN(5, 250, 255).Draw(rt, "website"),
rapid.StringN(5, 250, 255).Draw(rt, "securityContact"),
rapid.StringN(5, 250, 255).Draw(rt, "details"),
),
UnbondingHeight: rapid.Int64Min(1).Draw(t, "unbonding-height"),
UnbondingTime: time.Now().Add(durationGenerator().Draw(t, "duration")),
UnbondingHeight: rapid.Int64Min(1).Draw(rt, "unbonding-height"),
UnbondingTime: time.Now().Add(durationGenerator().Draw(rt, "duration")),
Commission: stakingtypes.NewCommission(
sdk.NewDecWithPrec(rapid.Int64Range(0, 100).Draw(t, "rate"), 2),
sdk.NewDecWithPrec(rapid.Int64Range(0, 100).Draw(t, "max-rate"), 2),
sdk.NewDecWithPrec(rapid.Int64Range(0, 100).Draw(t, "max-change-rate"), 2),
sdk.NewDecWithPrec(rapid.Int64Range(0, 100).Draw(rt, "rate"), 2),
sdk.NewDecWithPrec(rapid.Int64Range(0, 100).Draw(rt, "max-rate"), 2),
sdk.NewDecWithPrec(rapid.Int64Range(0, 100).Draw(rt, "max-change-rate"), 2),
),
MinSelfDelegation: sdk.NewInt(rapid.Int64Min(1).Draw(t, "tokens")),
MinSelfDelegation: sdk.NewInt(rapid.Int64Min(1).Draw(rt, "tokens")),
}
}
// createAndSetValidatorWithStatus creates a validator with random values but with given status and sets to the state
func (suite *DeterministicTestSuite) createAndSetValidatorWithStatus(t *rapid.T, status stakingtypes.BondStatus) stakingtypes.Validator {
val := suite.createValidator(t)
func createAndSetValidatorWithStatus(rt *rapid.T, f *deterministicFixture, t *testing.T, status stakingtypes.BondStatus) stakingtypes.Validator {
val := createValidator(rt, f, t)
val.Status = status
suite.setValidator(val)
setValidator(f, t, val)
return val
}
// createAndSetValidator creates a validator with random values and sets to the state
func (suite *DeterministicTestSuite) createAndSetValidator(t *rapid.T) stakingtypes.Validator {
val := suite.createValidator(t)
suite.setValidator(val)
func createAndSetValidator(rt *rapid.T, f *deterministicFixture, t *testing.T) stakingtypes.Validator {
val := createValidator(rt, f, t)
setValidator(f, t, val)
return val
}
func (suite *DeterministicTestSuite) setValidator(validator stakingtypes.Validator) {
suite.stakingKeeper.SetValidator(suite.ctx, validator)
suite.stakingKeeper.SetValidatorByPowerIndex(suite.ctx, validator)
suite.stakingKeeper.SetValidatorByConsAddr(suite.ctx, validator)
suite.Require().NoError(suite.stakingKeeper.Hooks().AfterValidatorCreated(suite.ctx, validator.GetOperator()))
func setValidator(f *deterministicFixture, t *testing.T, validator stakingtypes.Validator) {
f.stakingKeeper.SetValidator(f.ctx, validator)
f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validator)
f.stakingKeeper.SetValidatorByConsAddr(f.ctx, validator)
assert.NilError(t, f.stakingKeeper.Hooks().AfterValidatorCreated(f.ctx, validator.GetOperator()))
delegatorAddress := sdk.AccAddress(validator.GetOperator())
coins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, validator.BondedTokens()))
banktestutil.FundAccount(suite.bankKeeper, suite.ctx, delegatorAddress, coins)
banktestutil.FundAccount(f.bankKeeper, f.ctx, delegatorAddress, coins)
_, err := suite.stakingKeeper.Delegate(suite.ctx, delegatorAddress, validator.BondedTokens(), stakingtypes.Unbonded, validator, true)
suite.Require().NoError(err)
_, err := f.stakingKeeper.Delegate(f.ctx, delegatorAddress, validator.BondedTokens(), stakingtypes.Unbonded, validator, true)
assert.NilError(t, err)
}
// getStaticValidator creates a validator with hard-coded values and sets to the state.
func (suite *DeterministicTestSuite) getStaticValidator() stakingtypes.Validator {
func getStaticValidator(f *deterministicFixture, t *testing.T) stakingtypes.Validator {
pubkey := ed25519.PubKey{Key: []byte{24, 179, 242, 2, 151, 3, 34, 6, 1, 11, 0, 194, 202, 201, 77, 1, 167, 40, 249, 115, 32, 97, 18, 1, 1, 127, 255, 103, 13, 1, 34, 1}}
pubkeyAny, err := codectypes.NewAnyWithValue(&pubkey)
suite.Require().NoError(err)
assert.NilError(t, err)
validator := stakingtypes.Validator{
OperatorAddress: validator1,
@ -187,15 +184,15 @@ func (suite *DeterministicTestSuite) getStaticValidator() stakingtypes.Validator
MinSelfDelegation: sdk.NewInt(10),
}
suite.setValidator(validator)
setValidator(f, t, validator)
return validator
}
// getStaticValidator2 creates a validator with hard-coded values and sets to the state.
func (suite *DeterministicTestSuite) getStaticValidator2() stakingtypes.Validator {
func getStaticValidator2(f *deterministicFixture, t *testing.T) stakingtypes.Validator {
pubkey := ed25519.PubKey{Key: []byte{40, 249, 115, 32, 97, 18, 1, 1, 127, 255, 103, 13, 1, 34, 1, 24, 179, 242, 2, 151, 3, 34, 6, 1, 11, 0, 194, 202, 201, 77, 1, 167}}
pubkeyAny, err := codectypes.NewAnyWithValue(&pubkey)
suite.Require().NoError(err)
assert.NilError(t, err)
validator := stakingtypes.Validator{
OperatorAddress: validator2,
@ -220,321 +217,361 @@ func (suite *DeterministicTestSuite) getStaticValidator2() stakingtypes.Validato
),
MinSelfDelegation: sdk.NewInt(1),
}
suite.setValidator(validator)
setValidator(f, t, validator)
return validator
}
// createDelegationAndDelegate funds the delegator account with a random delegation in range 100-1000 and delegates.
func (suite *DeterministicTestSuite) createDelegationAndDelegate(t *rapid.T, delegator sdk.AccAddress, validator stakingtypes.Validator) (newShares math.LegacyDec, err error) {
amt := suite.stakingKeeper.TokensFromConsensusPower(suite.ctx, rapid.Int64Range(100, 1000).Draw(t, "amount"))
return suite.fundAccountAndDelegate(delegator, validator, amt)
func createDelegationAndDelegate(rt *rapid.T, f *deterministicFixture, t *testing.T, delegator sdk.AccAddress, validator stakingtypes.Validator) (newShares math.LegacyDec, err error) {
amt := f.stakingKeeper.TokensFromConsensusPower(f.ctx, rapid.Int64Range(100, 1000).Draw(rt, "amount"))
return fundAccountAndDelegate(f, t, delegator, validator, amt)
}
// fundAccountAndDelegate funds the delegator account with the specified delegation and delegates.
func (suite *DeterministicTestSuite) fundAccountAndDelegate(delegator sdk.AccAddress, validator stakingtypes.Validator, amt math.Int) (newShares math.LegacyDec, err error) {
func fundAccountAndDelegate(f *deterministicFixture, t *testing.T, delegator sdk.AccAddress, validator stakingtypes.Validator, amt math.Int) (newShares math.LegacyDec, err error) {
coins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amt))
suite.Require().NoError(suite.bankKeeper.MintCoins(suite.ctx, minttypes.ModuleName, coins))
banktestutil.FundAccount(suite.bankKeeper, suite.ctx, delegator, coins)
assert.NilError(t, f.bankKeeper.MintCoins(f.ctx, minttypes.ModuleName, coins))
banktestutil.FundAccount(f.bankKeeper, f.ctx, delegator, coins)
shares, err := suite.stakingKeeper.Delegate(suite.ctx, delegator, amt, stakingtypes.Unbonded, validator, true)
shares, err := f.stakingKeeper.Delegate(f.ctx, delegator, amt, stakingtypes.Unbonded, validator, true)
return shares, err
}
func (suite *DeterministicTestSuite) TestGRPCValidator() {
rapid.Check(suite.T(), func(t *rapid.T) {
val := suite.createAndSetValidator(t)
func TestGRPCValidator(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
val := createAndSetValidator(rt, f, t)
req := &stakingtypes.QueryValidatorRequest{
ValidatorAddr: val.OperatorAddress,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.Validator, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.Validator, 0, true)
})
suite.SetupTest() // reset
val := suite.getStaticValidator()
f = initDeterministicFixture(t) // reset
val := getStaticValidator(f, t)
req := &stakingtypes.QueryValidatorRequest{
ValidatorAddr: val.OperatorAddress,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.Validator, 1915, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.Validator, 1915, false)
}
func (suite *DeterministicTestSuite) TestGRPCValidators() {
validatorStatus := []string{stakingtypes.BondStatusBonded, stakingtypes.BondStatusUnbonded, stakingtypes.BondStatusUnbonding, ""}
rapid.Check(suite.T(), func(t *rapid.T) {
valsCount := rapid.IntRange(1, 3).Draw(t, "num-validators")
func TestGRPCValidators(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
validatorStatus := []string{stakingtypes.BondStatusBonded, stakingtypes.BondStatusUnbonded, stakingtypes.BondStatusUnbonding}
rapid.Check(t, func(rt *rapid.T) {
valsCount := rapid.IntRange(1, 3).Draw(rt, "num-validators")
for i := 0; i < valsCount; i++ {
suite.createAndSetValidator(t)
createAndSetValidator(rt, f, t)
}
req := &stakingtypes.QueryValidatorsRequest{
Status: validatorStatus[rapid.IntRange(0, 3).Draw(t, "status")],
Pagination: testdata.PaginationGenerator(t, uint64(valsCount)).Draw(t, "pagination"),
Status: validatorStatus[rapid.IntRange(0, 2).Draw(rt, "status")],
Pagination: testdata.PaginationGenerator(rt, uint64(valsCount)).Draw(rt, "pagination"),
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.Validators, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.Validators, 0, true)
})
suite.SetupTest() // reset
suite.getStaticValidator()
suite.getStaticValidator2()
f = initDeterministicFixture(t) // reset
getStaticValidator(f, t)
getStaticValidator2(f, t)
testdata.DeterministicIterations(suite.ctx, suite.Require(), &stakingtypes.QueryValidatorsRequest{}, suite.queryClient.Validators, 3525, false)
testdata.DeterministicIterations(f.ctx, require.New(t), &stakingtypes.QueryValidatorsRequest{}, f.queryClient.Validators, 3525, false)
}
func (suite *DeterministicTestSuite) TestGRPCValidatorDelegations() {
rapid.Check(suite.T(), func(t *rapid.T) {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
numDels := rapid.IntRange(1, 5).Draw(t, "num-dels")
func TestGRPCValidatorDelegations(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
numDels := rapid.IntRange(1, 5).Draw(rt, "num-dels")
for i := 0; i < numDels; i++ {
delegator := testdata.AddressGenerator(t).Draw(t, "delegator")
_, err := suite.createDelegationAndDelegate(t, delegator, validator)
suite.Require().NoError(err)
delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator")
_, err := createDelegationAndDelegate(rt, f, t, delegator, validator)
assert.NilError(t, err)
}
req := &stakingtypes.QueryValidatorDelegationsRequest{
ValidatorAddr: validator.OperatorAddress,
Pagination: testdata.PaginationGenerator(t, uint64(numDels)).Draw(t, "pagination"),
Pagination: testdata.PaginationGenerator(rt, uint64(numDels)).Draw(rt, "pagination"),
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.ValidatorDelegations, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.ValidatorDelegations, 0, true)
})
suite.SetupTest() // reset
f = initDeterministicFixture(t) // reset
validator := suite.getStaticValidator()
validator := getStaticValidator(f, t)
_, err := suite.fundAccountAndDelegate(delegatorAddr1, validator, suite.amt1)
suite.Require().NoError(err)
_, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1)
assert.NilError(t, err)
_, err = suite.fundAccountAndDelegate(delegatorAddr2, validator, suite.amt2)
suite.Require().NoError(err)
_, err = fundAccountAndDelegate(f, t, delegatorAddr2, validator, f.amt2)
assert.NilError(t, err)
req := &stakingtypes.QueryValidatorDelegationsRequest{
ValidatorAddr: validator.OperatorAddress,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.ValidatorDelegations, 11985, false)
testdata.DeterministicIterations(f.ctx, require.New(t), req, f.queryClient.ValidatorDelegations, 11985, false)
}
func (suite *DeterministicTestSuite) TestGRPCValidatorUnbondingDelegations() {
rapid.Check(suite.T(), func(t *rapid.T) {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
numDels := rapid.IntRange(1, 3).Draw(t, "num-dels")
func TestGRPCValidatorUnbondingDelegations(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
numDels := rapid.IntRange(1, 3).Draw(rt, "num-dels")
for i := 0; i < numDels; i++ {
delegator := testdata.AddressGenerator(t).Draw(t, "delegator")
shares, err := suite.createDelegationAndDelegate(t, delegator, validator)
suite.Require().NoError(err)
delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator")
shares, err := createDelegationAndDelegate(rt, f, t, delegator, validator)
assert.NilError(t, err)
_, err = suite.stakingKeeper.Undelegate(suite.ctx, delegator, validator.GetOperator(), shares)
suite.Require().NoError(err)
_, err = f.stakingKeeper.Undelegate(f.ctx, delegator, validator.GetOperator(), shares)
assert.NilError(t, err)
}
req := &stakingtypes.QueryValidatorUnbondingDelegationsRequest{
ValidatorAddr: validator.OperatorAddress,
Pagination: testdata.PaginationGenerator(t, uint64(numDels)).Draw(t, "pagination"),
Pagination: testdata.PaginationGenerator(rt, uint64(numDels)).Draw(rt, "pagination"),
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.ValidatorUnbondingDelegations, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.ValidatorUnbondingDelegations, 0, true)
})
suite.SetupTest() // reset
f = initDeterministicFixture(t) // reset
validator := suite.getStaticValidator()
shares1, err := suite.fundAccountAndDelegate(delegatorAddr1, validator, suite.amt1)
suite.Require().NoError(err)
validator := getStaticValidator(f, t)
shares1, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1)
assert.NilError(t, err)
_, err = suite.stakingKeeper.Undelegate(suite.ctx, delegatorAddr1, validatorAddr1, shares1)
suite.Require().NoError(err)
_, err = f.stakingKeeper.Undelegate(f.ctx, delegatorAddr1, validatorAddr1, shares1)
assert.NilError(t, err)
shares2, err := suite.fundAccountAndDelegate(delegatorAddr2, validator, suite.amt2)
suite.Require().NoError(err)
shares2, err := fundAccountAndDelegate(f, t, delegatorAddr2, validator, f.amt2)
assert.NilError(t, err)
_, err = suite.stakingKeeper.Undelegate(suite.ctx, delegatorAddr2, validatorAddr1, shares2)
suite.Require().NoError(err)
_, err = f.stakingKeeper.Undelegate(f.ctx, delegatorAddr2, validatorAddr1, shares2)
assert.NilError(t, err)
req := &stakingtypes.QueryValidatorUnbondingDelegationsRequest{
ValidatorAddr: validator.OperatorAddress,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.ValidatorUnbondingDelegations, 3719, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.ValidatorUnbondingDelegations, 3719, false)
}
func (suite *DeterministicTestSuite) TestGRPCDelegation() {
rapid.Check(suite.T(), func(t *rapid.T) {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
delegator := testdata.AddressGenerator(t).Draw(t, "delegator")
_, err := suite.createDelegationAndDelegate(t, delegator, validator)
suite.Require().NoError(err)
func TestGRPCDelegation(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator")
_, err := createDelegationAndDelegate(rt, f, t, delegator, validator)
assert.NilError(t, err)
req := &stakingtypes.QueryDelegationRequest{
ValidatorAddr: validator.OperatorAddress,
DelegatorAddr: delegator.String(),
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.Delegation, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.Delegation, 0, true)
})
suite.SetupTest() // reset
f = initDeterministicFixture(t) // reset
validator := suite.getStaticValidator()
_, err := suite.fundAccountAndDelegate(delegatorAddr1, validator, suite.amt1)
suite.Require().NoError(err)
validator := getStaticValidator(f, t)
_, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1)
assert.NilError(t, err)
req := &stakingtypes.QueryDelegationRequest{
ValidatorAddr: validator.OperatorAddress,
DelegatorAddr: delegator1,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.Delegation, 4635, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.Delegation, 4635, false)
}
func (suite *DeterministicTestSuite) TestGRPCUnbondingDelegation() {
rapid.Check(suite.T(), func(t *rapid.T) {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
delegator := testdata.AddressGenerator(t).Draw(t, "delegator")
shares, err := suite.createDelegationAndDelegate(t, delegator, validator)
suite.Require().NoError(err)
func TestGRPCUnbondingDelegation(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
_, err = suite.stakingKeeper.Undelegate(suite.ctx, delegator, validator.GetOperator(), shares)
suite.Require().NoError(err)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator")
shares, err := createDelegationAndDelegate(rt, f, t, delegator, validator)
assert.NilError(t, err)
_, err = f.stakingKeeper.Undelegate(f.ctx, delegator, validator.GetOperator(), shares)
assert.NilError(t, err)
req := &stakingtypes.QueryUnbondingDelegationRequest{
ValidatorAddr: validator.OperatorAddress,
DelegatorAddr: delegator.String(),
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.UnbondingDelegation, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.UnbondingDelegation, 0, true)
})
suite.SetupTest() // reset
validator := suite.getStaticValidator()
f = initDeterministicFixture(t) // reset
validator := getStaticValidator(f, t)
shares1, err := suite.fundAccountAndDelegate(delegatorAddr1, validator, suite.amt1)
suite.Require().NoError(err)
shares1, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1)
assert.NilError(t, err)
_, err = suite.stakingKeeper.Undelegate(suite.ctx, delegatorAddr1, validatorAddr1, shares1)
suite.Require().NoError(err)
_, err = f.stakingKeeper.Undelegate(f.ctx, delegatorAddr1, validatorAddr1, shares1)
assert.NilError(t, err)
req := &stakingtypes.QueryUnbondingDelegationRequest{
ValidatorAddr: validator.OperatorAddress,
DelegatorAddr: delegator1,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.UnbondingDelegation, 1621, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.UnbondingDelegation, 1621, false)
}
func (suite *DeterministicTestSuite) TestGRPCDelegatorDelegations() {
rapid.Check(suite.T(), func(t *rapid.T) {
numVals := rapid.IntRange(1, 3).Draw(t, "num-dels")
delegator := testdata.AddressGenerator(t).Draw(t, "delegator")
func TestGRPCDelegatorDelegations(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
numVals := rapid.IntRange(1, 3).Draw(rt, "num-dels")
delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator")
for i := 0; i < numVals; i++ {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
_, err := suite.createDelegationAndDelegate(t, delegator, validator)
suite.Require().NoError(err)
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
_, err := createDelegationAndDelegate(rt, f, t, delegator, validator)
assert.NilError(t, err)
}
req := &stakingtypes.QueryDelegatorDelegationsRequest{
DelegatorAddr: delegator.String(),
Pagination: testdata.PaginationGenerator(t, uint64(numVals)).Draw(t, "pagination"),
Pagination: testdata.PaginationGenerator(rt, uint64(numVals)).Draw(rt, "pagination"),
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.DelegatorDelegations, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.DelegatorDelegations, 0, true)
})
suite.SetupTest() // reset
f = initDeterministicFixture(t) // reset
validator := suite.getStaticValidator()
_, err := suite.fundAccountAndDelegate(delegatorAddr1, validator, suite.amt1)
suite.Require().NoError(err)
validator := getStaticValidator(f, t)
_, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1)
assert.NilError(t, err)
req := &stakingtypes.QueryDelegatorDelegationsRequest{
DelegatorAddr: delegator1,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.DelegatorDelegations, 4238, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.DelegatorDelegations, 4238, false)
}
func (suite *DeterministicTestSuite) TestGRPCDelegatorValidator() {
rapid.Check(suite.T(), func(t *rapid.T) {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
func TestGRPCDelegatorValidator(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
delegator := testdata.AddressGenerator(t).Draw(t, "delegator")
_, err := suite.createDelegationAndDelegate(t, delegator, validator)
suite.Require().NoError(err)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator")
_, err := createDelegationAndDelegate(rt, f, t, delegator, validator)
assert.NilError(t, err)
req := &stakingtypes.QueryDelegatorValidatorRequest{
DelegatorAddr: delegator.String(),
ValidatorAddr: validator.OperatorAddress,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.DelegatorValidator, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.DelegatorValidator, 0, true)
})
suite.SetupTest() // reset
f = initDeterministicFixture(t) // reset
validator := suite.getStaticValidator()
_, err := suite.fundAccountAndDelegate(delegatorAddr1, validator, suite.amt1)
validator := getStaticValidator(f, t)
_, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1)
suite.Require().NoError(err)
assert.NilError(t, err)
req := &stakingtypes.QueryDelegatorValidatorRequest{
DelegatorAddr: delegator1,
ValidatorAddr: validator.OperatorAddress,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.DelegatorValidator, 3563, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.DelegatorValidator, 3563, false)
}
func (suite *DeterministicTestSuite) TestGRPCDelegatorUnbondingDelegations() {
rapid.Check(suite.T(), func(t *rapid.T) {
numVals := rapid.IntRange(1, 5).Draw(t, "num-vals")
delegator := testdata.AddressGenerator(t).Draw(t, "delegator")
func TestGRPCDelegatorUnbondingDelegations(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
numVals := rapid.IntRange(1, 5).Draw(rt, "num-vals")
delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator")
for i := 0; i < numVals; i++ {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
shares, err := suite.createDelegationAndDelegate(t, delegator, validator)
suite.Require().NoError(err)
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
shares, err := createDelegationAndDelegate(rt, f, t, delegator, validator)
assert.NilError(t, err)
_, err = suite.stakingKeeper.Undelegate(suite.ctx, delegator, validator.GetOperator(), shares)
suite.Require().NoError(err)
_, err = f.stakingKeeper.Undelegate(f.ctx, delegator, validator.GetOperator(), shares)
assert.NilError(t, err)
}
req := &stakingtypes.QueryDelegatorUnbondingDelegationsRequest{
DelegatorAddr: delegator.String(),
Pagination: testdata.PaginationGenerator(t, uint64(numVals)).Draw(t, "pagination"),
Pagination: testdata.PaginationGenerator(rt, uint64(numVals)).Draw(rt, "pagination"),
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.DelegatorUnbondingDelegations, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.DelegatorUnbondingDelegations, 0, true)
})
suite.SetupTest() // reset
f = initDeterministicFixture(t) // reset
validator := suite.getStaticValidator()
shares1, err := suite.fundAccountAndDelegate(delegatorAddr1, validator, suite.amt1)
suite.Require().NoError(err)
validator := getStaticValidator(f, t)
shares1, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1)
assert.NilError(t, err)
_, err = suite.stakingKeeper.Undelegate(suite.ctx, delegatorAddr1, validatorAddr1, shares1)
suite.Require().NoError(err)
_, err = f.stakingKeeper.Undelegate(f.ctx, delegatorAddr1, validatorAddr1, shares1)
assert.NilError(t, err)
req := &stakingtypes.QueryDelegatorUnbondingDelegationsRequest{
DelegatorAddr: delegator1,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.DelegatorUnbondingDelegations, 1302, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.DelegatorUnbondingDelegations, 1302, false)
}
func (suite *DeterministicTestSuite) TestGRPCHistoricalInfo() {
rapid.Check(suite.T(), func(t *rapid.T) {
numVals := rapid.IntRange(1, 5).Draw(t, "num-vals")
func TestGRPCHistoricalInfo(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
numVals := rapid.IntRange(1, 5).Draw(rt, "num-vals")
vals := make(stakingtypes.Validators, 0, numVals)
for i := 0; i < numVals; i++ {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
vals = append(vals, validator)
}
@ -543,10 +580,10 @@ func (suite *DeterministicTestSuite) TestGRPCHistoricalInfo() {
Valset: vals,
}
height := rapid.Int64Min(0).Draw(t, "height")
height := rapid.Int64Min(0).Draw(rt, "height")
suite.stakingKeeper.SetHistoricalInfo(
suite.ctx,
f.stakingKeeper.SetHistoricalInfo(
f.ctx,
height,
&historicalInfo,
)
@ -555,12 +592,12 @@ func (suite *DeterministicTestSuite) TestGRPCHistoricalInfo() {
Height: height,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.HistoricalInfo, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.HistoricalInfo, 0, true)
})
suite.SetupTest() // reset
f = initDeterministicFixture(t) // reset
validator := suite.getStaticValidator()
validator := getStaticValidator(f, t)
historicalInfo := stakingtypes.HistoricalInfo{
Header: tmproto.Header{},
@ -569,8 +606,8 @@ func (suite *DeterministicTestSuite) TestGRPCHistoricalInfo() {
height := int64(127)
suite.stakingKeeper.SetHistoricalInfo(
suite.ctx,
f.stakingKeeper.SetHistoricalInfo(
f.ctx,
height,
&historicalInfo,
)
@ -579,73 +616,84 @@ func (suite *DeterministicTestSuite) TestGRPCHistoricalInfo() {
Height: height,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.HistoricalInfo, 1930, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.HistoricalInfo, 1930, false)
}
func (suite *DeterministicTestSuite) TestGRPCDelegatorValidators() {
rapid.Check(suite.T(), func(t *rapid.T) {
numVals := rapid.IntRange(1, 3).Draw(t, "num-dels")
delegator := testdata.AddressGenerator(t).Draw(t, "delegator")
func TestGRPCDelegatorValidators(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
numVals := rapid.IntRange(1, 3).Draw(rt, "num-dels")
delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator")
for i := 0; i < numVals; i++ {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
_, err := suite.createDelegationAndDelegate(t, delegator, validator)
suite.Require().NoError(err)
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
_, err := createDelegationAndDelegate(rt, f, t, delegator, validator)
assert.NilError(t, err)
}
req := &stakingtypes.QueryDelegatorValidatorsRequest{
DelegatorAddr: delegator.String(),
Pagination: testdata.PaginationGenerator(t, uint64(numVals)).Draw(t, "pagination"),
Pagination: testdata.PaginationGenerator(rt, uint64(numVals)).Draw(rt, "pagination"),
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.DelegatorValidators, 0, true)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.DelegatorValidators, 0, true)
})
suite.SetupTest() // reset
f = initDeterministicFixture(t) // reset
validator := suite.getStaticValidator()
validator := getStaticValidator(f, t)
_, err := suite.fundAccountAndDelegate(delegatorAddr1, validator, suite.amt1)
suite.Require().NoError(err)
_, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1)
assert.NilError(t, err)
req := &stakingtypes.QueryDelegatorValidatorsRequest{DelegatorAddr: delegator1}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.DelegatorValidators, 3166, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.DelegatorValidators, 3166, false)
}
func (suite *DeterministicTestSuite) TestGRPCPool() {
rapid.Check(suite.T(), func(t *rapid.T) {
suite.createAndSetValidator(t)
func TestGRPCPool(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
testdata.DeterministicIterations(suite.ctx, suite.Require(), &stakingtypes.QueryPoolRequest{}, suite.queryClient.Pool, 0, true)
rapid.Check(t, func(rt *rapid.T) {
createAndSetValidator(rt, f, t)
testdata.DeterministicIterations(f.ctx, require.New(t), &stakingtypes.QueryPoolRequest{}, f.queryClient.Pool, 0, true)
})
suite.SetupTest() // reset
suite.getStaticValidator()
testdata.DeterministicIterations(suite.ctx, suite.Require(), &stakingtypes.QueryPoolRequest{}, suite.queryClient.Pool, 6185, false)
f = initDeterministicFixture(t) // reset
getStaticValidator(f, t)
testdata.DeterministicIterations(f.ctx, require.New(t), &stakingtypes.QueryPoolRequest{}, f.queryClient.Pool, 6185, false)
}
func (suite *DeterministicTestSuite) TestGRPCRedelegations() {
rapid.Check(suite.T(), func(t *rapid.T) {
validator := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
func TestGRPCRedelegations(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
srcValAddr, err := sdk.ValAddressFromBech32(validator.OperatorAddress)
suite.Require().NoError(err)
assert.NilError(t, err)
validator2 := suite.createAndSetValidatorWithStatus(t, stakingtypes.Bonded)
validator2 := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded)
dstValAddr, err := sdk.ValAddressFromBech32(validator2.OperatorAddress)
suite.Require().NoError(err)
assert.NilError(t, err)
numDels := rapid.IntRange(1, 5).Draw(t, "num-dels")
numDels := rapid.IntRange(1, 5).Draw(rt, "num-dels")
delegator := testdata.AddressGenerator(t).Draw(t, "delegator")
shares, err := suite.createDelegationAndDelegate(t, delegator, validator)
suite.Require().NoError(err)
delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator")
shares, err := createDelegationAndDelegate(rt, f, t, delegator, validator)
assert.NilError(t, err)
_, err = suite.stakingKeeper.BeginRedelegation(suite.ctx, delegator, srcValAddr, dstValAddr, shares)
suite.Require().NoError(err)
_, err = f.stakingKeeper.BeginRedelegation(f.ctx, delegator, srcValAddr, dstValAddr, shares)
assert.NilError(t, err)
var req *stakingtypes.QueryRedelegationsRequest
reqType := rapid.IntRange(0, 2).Draw(t, "req-type")
reqType := rapid.IntRange(0, 2).Draw(rt, "req-type")
switch reqType {
case 0: // queries redelegation with delegator, source and destination validators combination.
req = &stakingtypes.QueryRedelegationsRequest{
@ -663,19 +711,19 @@ func (suite *DeterministicTestSuite) TestGRPCRedelegations() {
}
}
req.Pagination = testdata.PaginationGenerator(t, uint64(numDels)).Draw(t, "pagination")
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.Redelegations, 0, true)
req.Pagination = testdata.PaginationGenerator(rt, uint64(numDels)).Draw(rt, "pagination")
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.Redelegations, 0, true)
})
suite.SetupTest() // reset
validator := suite.getStaticValidator()
_ = suite.getStaticValidator2()
f = initDeterministicFixture(t) // reset
validator := getStaticValidator(f, t)
_ = getStaticValidator2(f, t)
shares, err := suite.fundAccountAndDelegate(delegatorAddr1, validator, suite.amt1)
suite.Require().NoError(err)
shares, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1)
assert.NilError(t, err)
_, err = suite.stakingKeeper.BeginRedelegation(suite.ctx, delegatorAddr1, validatorAddr1, validatorAddr2, shares)
suite.Require().NoError(err)
_, err = f.stakingKeeper.BeginRedelegation(f.ctx, delegatorAddr1, validatorAddr1, validatorAddr2, shares)
assert.NilError(t, err)
req := &stakingtypes.QueryRedelegationsRequest{
DelegatorAddr: delegator1,
@ -683,24 +731,28 @@ func (suite *DeterministicTestSuite) TestGRPCRedelegations() {
DstValidatorAddr: validator2,
}
testdata.DeterministicIterations(suite.ctx, suite.Require(), req, suite.queryClient.Redelegations, 3920, false)
testdata.DeterministicIterations(f.ctx, tt, req, f.queryClient.Redelegations, 3920, false)
}
func (suite *DeterministicTestSuite) TestGRPCParams() {
rapid.Check(suite.T(), func(t *rapid.T) {
func TestGRPCParams(t *testing.T) {
t.Parallel()
f := initDeterministicFixture(t)
tt := require.New(t)
rapid.Check(t, func(rt *rapid.T) {
params := stakingtypes.Params{
BondDenom: rapid.StringMatching(sdk.DefaultCoinDenomRegex()).Draw(t, "bond-denom"),
UnbondingTime: durationGenerator().Draw(t, "duration"),
MaxValidators: rapid.Uint32Min(1).Draw(t, "max-validators"),
MaxEntries: rapid.Uint32Min(1).Draw(t, "max-entries"),
HistoricalEntries: rapid.Uint32Min(1).Draw(t, "historical-entries"),
MinCommissionRate: sdk.NewDecWithPrec(rapid.Int64Range(0, 100).Draw(t, "commission"), 2),
BondDenom: rapid.StringMatching(sdk.DefaultCoinDenomRegex()).Draw(rt, "bond-denom"),
UnbondingTime: durationGenerator().Draw(rt, "duration"),
MaxValidators: rapid.Uint32Min(1).Draw(rt, "max-validators"),
MaxEntries: rapid.Uint32Min(1).Draw(rt, "max-entries"),
HistoricalEntries: rapid.Uint32Min(1).Draw(rt, "historical-entries"),
MinCommissionRate: sdk.NewDecWithPrec(rapid.Int64Range(0, 100).Draw(rt, "commission"), 2),
}
err := suite.stakingKeeper.SetParams(suite.ctx, params)
suite.Require().NoError(err)
err := f.stakingKeeper.SetParams(f.ctx, params)
assert.NilError(t, err)
testdata.DeterministicIterations(suite.ctx, suite.Require(), &stakingtypes.QueryParamsRequest{}, suite.queryClient.Params, 0, true)
testdata.DeterministicIterations(f.ctx, tt, &stakingtypes.QueryParamsRequest{}, f.queryClient.Params, 0, true)
})
params := stakingtypes.Params{
@ -712,8 +764,8 @@ func (suite *DeterministicTestSuite) TestGRPCParams() {
MinCommissionRate: sdk.NewDecWithPrec(5, 2),
}
err := suite.stakingKeeper.SetParams(suite.ctx, params)
suite.Require().NoError(err)
err := f.stakingKeeper.SetParams(f.ctx, params)
assert.NilError(t, err)
testdata.DeterministicIterations(suite.ctx, suite.Require(), &stakingtypes.QueryParamsRequest{}, suite.queryClient.Params, 1114, false)
testdata.DeterministicIterations(f.ctx, tt, &stakingtypes.QueryParamsRequest{}, f.queryClient.Params, 1114, false)
}

View File

@ -5,12 +5,13 @@ import (
"testing"
"cosmossdk.io/math"
"github.com/stretchr/testify/require"
"cosmossdk.io/simapp"
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"gotest.tools/v3/assert"
"cosmossdk.io/simapp"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdktestutil "github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/staking"
@ -32,14 +33,14 @@ func TestInitGenesis(t *testing.T) {
params := app.StakingKeeper.GetParams(ctx)
validators := app.StakingKeeper.GetAllValidators(ctx)
require.Len(t, validators, 1)
assert.Assert(t, len(validators) == 1)
var delegations []types.Delegation
pk0, err := codectypes.NewAnyWithValue(PKs[0])
require.NoError(t, err)
assert.NilError(t, err)
pk1, err := codectypes.NewAnyWithValue(PKs[1])
require.NoError(t, err)
assert.NilError(t, err)
// initialize the validators
bondedVal1 := types.Validator{
@ -64,7 +65,7 @@ func TestInitGenesis(t *testing.T) {
// mint coins in the bonded pool representing the validators coins
i2 := len(validators) - 1 // -1 to exclude genesis validator
require.NoError(t,
assert.NilError(t,
testutil.FundModuleAccount(
app.BankKeeper,
ctx,
@ -82,26 +83,26 @@ func TestInitGenesis(t *testing.T) {
vals := app.StakingKeeper.InitGenesis(ctx, genesisState)
actualGenesis := app.StakingKeeper.ExportGenesis(ctx)
require.Equal(t, genesisState.Params, actualGenesis.Params)
require.Equal(t, genesisState.Delegations, actualGenesis.Delegations)
require.EqualValues(t, app.StakingKeeper.GetAllValidators(ctx), actualGenesis.Validators)
assert.DeepEqual(t, genesisState.Params, actualGenesis.Params)
assert.DeepEqual(t, genesisState.Delegations, actualGenesis.Delegations)
assert.DeepEqual(t, app.StakingKeeper.GetAllValidators(ctx), actualGenesis.Validators)
// Ensure validators have addresses.
vals2, err := staking.WriteValidators(ctx, app.StakingKeeper)
require.NoError(t, err)
assert.NilError(t, err)
for _, val := range vals2 {
require.NotEmpty(t, val.Address)
assert.Assert(t, val.Address.String() != "")
}
// now make sure the validators are bonded and intra-tx counters are correct
resVal, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[0]))
require.True(t, found)
require.Equal(t, types.Bonded, resVal.Status)
assert.Assert(t, found)
assert.Equal(t, types.Bonded, resVal.Status)
resVal, found = app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[1]))
require.True(t, found)
require.Equal(t, types.Bonded, resVal.Status)
assert.Assert(t, found)
assert.Equal(t, types.Bonded, resVal.Status)
abcivals := make([]abci.ValidatorUpdate, len(vals))
@ -110,7 +111,7 @@ func TestInitGenesis(t *testing.T) {
abcivals[i] = val.ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx))
}
require.Equal(t, abcivals, vals)
assert.DeepEqual(t, abcivals, vals)
}
func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) {
@ -118,7 +119,7 @@ func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) {
ctx := app.NewContext(false, tmproto.Header{})
consPub, err := codectypes.NewAnyWithValue(PKs[0])
require.NoError(t, err)
assert.NilError(t, err)
validator := types.Validator{
OperatorAddress: sdk.ValAddress("12345678901234567890").String(),
@ -136,7 +137,7 @@ func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) {
BondDenom: "stake",
}
require.Panics(t, func() {
sdktestutil.AssertPanics(t, func() {
// setting validator status to bonded so the balance counts towards bonded pool
validator.Status = types.Bonded
app.StakingKeeper.InitGenesis(ctx, &types.GenesisState{
@ -144,10 +145,10 @@ func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) {
Validators: []types.Validator{validator},
})
},
"should panic because bonded pool balance is different from bonded pool coins",
// "should panic because bonded pool balance is different from bonded pool coins",
)
require.Panics(t, func() {
sdktestutil.AssertPanics(t, func() {
// setting validator status to unbonded so the balance counts towards not bonded pool
validator.Status = types.Unbonded
app.StakingKeeper.InitGenesis(ctx, &types.GenesisState{
@ -155,13 +156,13 @@ func TestInitGenesis_PoolsBalanceMismatch(t *testing.T) {
Validators: []types.Validator{validator},
})
},
"should panic because not bonded pool balance is different from not bonded pool coins",
// "should panic because not bonded pool balance is different from not bonded pool coins",
)
}
func TestInitGenesisLargeValidatorSet(t *testing.T) {
size := 200
require.True(t, size > 100)
assert.Assert(t, size > 100)
app, ctx, addrs := bootstrapGenesisTest(t, 200)
genesisValidators := app.StakingKeeper.GetAllValidators(ctx)
@ -179,7 +180,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) {
PKs[i],
types.NewDescription(fmt.Sprintf("#%d", i), "", "", "", ""),
)
require.NoError(t, err)
assert.NilError(t, err)
validators[i].Status = types.Bonded
tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 1)
@ -198,7 +199,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) {
genesisState := types.NewGenesisState(params, validators, delegations)
// mint coins in the bonded pool representing the validators coins
require.NoError(t,
assert.NilError(t,
testutil.FundModuleAccount(
app.BankKeeper,
ctx,
@ -216,5 +217,5 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) {
// remove genesis validator
vals = vals[:100]
require.Equal(t, abcivals, vals)
assert.DeepEqual(t, abcivals, vals)
}

View File

@ -3,6 +3,9 @@ package keeper_test
import (
gocontext "context"
"fmt"
"testing"
"gotest.tools/v3/assert"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -10,15 +13,19 @@ import (
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
func (suite *IntegrationTestSuite) TestGRPCQueryValidators() {
queryClient, vals := suite.queryClient, suite.vals
func TestGRPCQueryValidators(t *testing.T) {
t.Parallel()
f := initFixture(t)
queryClient, vals := f.queryClient, f.vals
var req *types.QueryValidatorsRequest
testCases := []struct {
msg string
malleate func()
expPass bool
numVals int
hasNext bool
msg string
malleate func()
expPass bool
numVals int
hasNext bool
expErrMsg string
}{
{
"empty request",
@ -26,9 +33,9 @@ func (suite *IntegrationTestSuite) TestGRPCQueryValidators() {
req = &types.QueryValidatorsRequest{}
},
true,
len(vals) + 1, // +1 validator from genesis state
false,
"",
},
{
"empty status returns all the validators",
@ -38,6 +45,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryValidators() {
true,
len(vals) + 1, // +1 validator from genesis state
false,
"",
},
{
"invalid request",
@ -47,6 +55,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryValidators() {
false,
0,
false,
"invalid validator status test",
},
{
"valid request",
@ -59,39 +68,44 @@ func (suite *IntegrationTestSuite) TestGRPCQueryValidators() {
true,
1,
true,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
valsResp, err := queryClient.Validators(gocontext.Background(), req)
if tc.expPass {
suite.NoError(err)
suite.NotNil(valsResp)
suite.Equal(tc.numVals, len(valsResp.Validators))
suite.Equal(uint64(len(vals))+1, valsResp.Pagination.Total) // +1 validator from genesis state
assert.NilError(t, err)
assert.Assert(t, valsResp != nil)
assert.Equal(t, tc.numVals, len(valsResp.Validators))
assert.Equal(t, uint64(len(vals))+1, valsResp.Pagination.Total) // +1 validator from genesis state
if tc.hasNext {
suite.NotNil(valsResp.Pagination.NextKey)
assert.Assert(t, valsResp.Pagination.NextKey != nil)
} else {
suite.Nil(valsResp.Pagination.NextKey)
assert.Assert(t, valsResp.Pagination.NextKey == nil)
}
} else {
suite.Require().Error(err)
assert.ErrorContains(t, err, tc.expErrMsg)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorValidators() {
app, ctx, queryClient, addrs := suite.app, suite.ctx, suite.queryClient, suite.addrs
func TestGRPCQueryDelegatorValidators(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient, addrs := f.app, f.ctx, f.queryClient, f.addrs
params := app.StakingKeeper.GetParams(ctx)
delValidators := app.StakingKeeper.GetDelegatorValidators(ctx, addrs[0], params.MaxValidators)
var req *types.QueryDelegatorValidatorsRequest
testCases := []struct {
msg string
malleate func()
expPass bool
msg string
malleate func()
expPass bool
expErrMsg string
}{
{
"empty request",
@ -99,6 +113,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorValidators() {
req = &types.QueryDelegatorValidatorsRequest{}
},
false,
"delegator address cannot be empty",
},
{
"valid request",
@ -109,35 +124,40 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorValidators() {
}
},
true,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.DelegatorValidators(gocontext.Background(), req)
if tc.expPass {
suite.NoError(err)
suite.Equal(1, len(res.Validators))
suite.NotNil(res.Pagination.NextKey)
suite.Equal(uint64(len(delValidators)), res.Pagination.Total)
assert.NilError(t, err)
assert.Equal(t, 1, len(res.Validators))
assert.Assert(t, res.Pagination.NextKey != nil)
assert.Equal(t, uint64(len(delValidators)), res.Pagination.Total)
} else {
suite.Error(err)
suite.Nil(res)
assert.ErrorContains(t, err, tc.expErrMsg)
assert.Assert(t, res == nil)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorValidator() {
queryClient, addrs, vals := suite.queryClient, suite.addrs, suite.vals
func TestGRPCQueryDelegatorValidator(t *testing.T) {
t.Parallel()
f := initFixture(t)
queryClient, addrs, vals := f.queryClient, f.addrs, f.vals
addr := addrs[1]
addrVal, addrVal1 := vals[0].OperatorAddress, vals[1].OperatorAddress
var req *types.QueryDelegatorValidatorRequest
testCases := []struct {
msg string
malleate func()
expPass bool
msg string
malleate func()
expPass bool
expErrMsg string
}{
{
"empty request",
@ -145,6 +165,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorValidator() {
req = &types.QueryDelegatorValidatorRequest{}
},
false,
"delegator address cannot be empty",
},
{
"invalid delegator, validator pair",
@ -155,6 +176,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorValidator() {
}
},
false,
"no delegation for (address, validator) tuple",
},
{
"valid request",
@ -165,38 +187,43 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorValidator() {
}
},
true,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.DelegatorValidator(gocontext.Background(), req)
if tc.expPass {
suite.NoError(err)
suite.Equal(addrVal1, res.Validator.OperatorAddress)
assert.NilError(t, err)
assert.Equal(t, addrVal1, res.Validator.OperatorAddress)
} else {
suite.Error(err)
suite.Nil(res)
assert.ErrorContains(t, err, tc.expErrMsg)
assert.Assert(t, res == nil)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryDelegation() {
app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals
func TestGRPCQueryDelegation(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient, addrs, vals := f.app, f.ctx, f.queryClient, f.addrs, f.vals
addrAcc, addrAcc1 := addrs[0], addrs[1]
addrVal := vals[0].OperatorAddress
valAddr, err := sdk.ValAddressFromBech32(addrVal)
suite.NoError(err)
assert.NilError(t, err)
delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, valAddr)
suite.True(found)
assert.Assert(t, found)
var req *types.QueryDelegationRequest
testCases := []struct {
msg string
malleate func()
expPass bool
msg string
malleate func()
expPass bool
expErrMsg string
}{
{
"empty request",
@ -204,6 +231,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegation() {
req = &types.QueryDelegationRequest{}
},
false,
"delegator address cannot be empty",
},
{
"invalid validator, delegator pair",
@ -214,6 +242,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegation() {
}
},
false,
fmt.Sprintf("delegation with delegator %s not found for validator %s", addrAcc1.String(), addrVal),
},
{
"valid request",
@ -221,59 +250,66 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegation() {
req = &types.QueryDelegationRequest{DelegatorAddr: addrAcc.String(), ValidatorAddr: addrVal}
},
true,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.Delegation(gocontext.Background(), req)
if tc.expPass {
suite.Equal(delegation.ValidatorAddress, res.DelegationResponse.Delegation.ValidatorAddress)
suite.Equal(delegation.DelegatorAddress, res.DelegationResponse.Delegation.DelegatorAddress)
suite.Equal(sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), res.DelegationResponse.Balance)
assert.Equal(t, delegation.ValidatorAddress, res.DelegationResponse.Delegation.ValidatorAddress)
assert.Equal(t, delegation.DelegatorAddress, res.DelegationResponse.Delegation.DelegatorAddress)
assert.DeepEqual(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), res.DelegationResponse.Balance)
} else {
suite.Error(err)
suite.Nil(res)
assert.ErrorContains(t, err, tc.expErrMsg)
assert.Assert(t, res == nil)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorDelegations() {
app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals
func TestGRPCQueryDelegatorDelegations(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient, addrs, vals := f.app, f.ctx, f.queryClient, f.addrs, f.vals
addrAcc := addrs[0]
addrVal1 := vals[0].OperatorAddress
valAddr, err := sdk.ValAddressFromBech32(addrVal1)
suite.NoError(err)
assert.NilError(t, err)
delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, valAddr)
suite.True(found)
assert.Assert(t, found)
var req *types.QueryDelegatorDelegationsRequest
testCases := []struct {
msg string
malleate func()
onSuccess func(suite *IntegrationTestSuite, response *types.QueryDelegatorDelegationsResponse)
onSuccess func(response *types.QueryDelegatorDelegationsResponse)
expErr bool
expErrMsg string
}{
{
"empty request",
func() {
req = &types.QueryDelegatorDelegationsRequest{}
},
func(suite *IntegrationTestSuite, response *types.QueryDelegatorDelegationsResponse) {},
func(response *types.QueryDelegatorDelegationsResponse) {},
true,
"delegator address cannot be empty",
},
{
"valid request with no delegations",
func() {
req = &types.QueryDelegatorDelegationsRequest{DelegatorAddr: addrs[4].String()}
},
func(suite *IntegrationTestSuite, response *types.QueryDelegatorDelegationsResponse) {
suite.Equal(uint64(0), response.Pagination.Total)
suite.Len(response.DelegationResponses, 0)
func(response *types.QueryDelegatorDelegationsResponse) {
assert.Equal(t, uint64(0), response.Pagination.Total)
assert.Assert(t, len(response.DelegationResponses) == 0)
},
false,
"",
},
{
"valid request",
@ -283,46 +319,51 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorDelegations() {
Pagination: &query.PageRequest{Limit: 1, CountTotal: true},
}
},
func(suite *IntegrationTestSuite, response *types.QueryDelegatorDelegationsResponse) {
suite.Equal(uint64(2), response.Pagination.Total)
suite.Len(response.DelegationResponses, 1)
suite.Equal(sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), response.DelegationResponses[0].Balance)
func(response *types.QueryDelegatorDelegationsResponse) {
assert.Equal(t, uint64(2), response.Pagination.Total)
assert.Assert(t, len(response.DelegationResponses) == 1)
assert.DeepEqual(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), response.DelegationResponses[0].Balance)
},
false,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.DelegatorDelegations(gocontext.Background(), req)
if tc.expErr {
suite.Error(err)
assert.ErrorContains(t, err, tc.expErrMsg)
} else {
suite.NoError(err)
tc.onSuccess(suite, res)
assert.NilError(t, err)
tc.onSuccess(res)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryValidatorDelegations() {
app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals
func TestGRPCQueryValidatorDelegations(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient, addrs, vals := f.app, f.ctx, f.queryClient, f.addrs, f.vals
addrAcc := addrs[0]
addrVal1 := vals[1].OperatorAddress
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
addrVal2 := valAddrs[4]
valAddr, err := sdk.ValAddressFromBech32(addrVal1)
suite.NoError(err)
assert.NilError(t, err)
delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc, valAddr)
suite.True(found)
assert.Assert(t, found)
var req *types.QueryValidatorDelegationsRequest
testCases := []struct {
msg string
malleate func()
expPass bool
expErr bool
msg string
malleate func()
expPass bool
expErr bool
expErrMsg string
}{
{
"empty request",
@ -331,6 +372,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryValidatorDelegations() {
},
false,
true,
"validator address cannot be empty",
},
{
"invalid validator delegator pair",
@ -339,6 +381,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryValidatorDelegations() {
},
false,
false,
"",
},
{
"valid request",
@ -350,49 +393,54 @@ func (suite *IntegrationTestSuite) TestGRPCQueryValidatorDelegations() {
},
true,
false,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.ValidatorDelegations(gocontext.Background(), req)
if tc.expPass && !tc.expErr {
suite.NoError(err)
suite.Len(res.DelegationResponses, 1)
suite.NotNil(res.Pagination.NextKey)
suite.Equal(uint64(2), res.Pagination.Total)
suite.Equal(addrVal1, res.DelegationResponses[0].Delegation.ValidatorAddress)
suite.Equal(sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), res.DelegationResponses[0].Balance)
assert.NilError(t, err)
assert.Assert(t, len(res.DelegationResponses) == 1)
assert.Assert(t, res.Pagination.NextKey != nil)
assert.Equal(t, uint64(2), res.Pagination.Total)
assert.Equal(t, addrVal1, res.DelegationResponses[0].Delegation.ValidatorAddress)
assert.DeepEqual(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), res.DelegationResponses[0].Balance)
} else if !tc.expPass && !tc.expErr {
suite.NoError(err)
suite.Nil(res.DelegationResponses)
assert.NilError(t, err)
assert.Assert(t, res.DelegationResponses == nil)
} else {
suite.Error(err)
suite.Nil(res)
assert.ErrorContains(t, err, tc.expErrMsg)
assert.Assert(t, res == nil)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryUnbondingDelegation() {
app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals
func TestGRPCQueryUnbondingDelegation(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient, addrs, vals := f.app, f.ctx, f.queryClient, f.addrs, f.vals
addrAcc2 := addrs[1]
addrVal2 := vals[1].OperatorAddress
unbondingTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 2)
valAddr, err1 := sdk.ValAddressFromBech32(addrVal2)
suite.NoError(err1)
assert.NilError(t, err1)
_, err := app.StakingKeeper.Undelegate(ctx, addrAcc2, valAddr, sdk.NewDecFromInt(unbondingTokens))
suite.NoError(err)
assert.NilError(t, err)
unbond, found := app.StakingKeeper.GetUnbondingDelegation(ctx, addrAcc2, valAddr)
suite.True(found)
assert.Assert(t, found)
var req *types.QueryUnbondingDelegationRequest
testCases := []struct {
msg string
malleate func()
expPass bool
msg string
malleate func()
expPass bool
expErrMsg string
}{
{
"empty request",
@ -400,6 +448,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryUnbondingDelegation() {
req = &types.QueryUnbondingDelegationRequest{}
},
false,
"delegator address cannot be empty",
},
{
"invalid request",
@ -407,6 +456,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryUnbondingDelegation() {
req = &types.QueryUnbondingDelegationRequest{}
},
false,
"delegator address cannot be empty",
},
{
"valid request",
@ -416,47 +466,52 @@ func (suite *IntegrationTestSuite) TestGRPCQueryUnbondingDelegation() {
}
},
true,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.UnbondingDelegation(gocontext.Background(), req)
if tc.expPass {
suite.NotNil(res)
suite.Equal(unbond, res.Unbond)
assert.Assert(t, res != nil)
assert.DeepEqual(t, unbond, res.Unbond)
} else {
suite.Error(err)
suite.Nil(res)
assert.ErrorContains(t, err, tc.expErrMsg)
assert.Assert(t, res == nil)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorUnbondingDelegations() {
app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals
func TestGRPCQueryDelegatorUnbondingDelegations(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient, addrs, vals := f.app, f.ctx, f.queryClient, f.addrs, f.vals
addrAcc, addrAcc1 := addrs[0], addrs[1]
addrVal, addrVal2 := vals[0].OperatorAddress, vals[1].OperatorAddress
unbondingTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 2)
valAddr1, err1 := sdk.ValAddressFromBech32(addrVal)
suite.NoError(err1)
assert.NilError(t, err1)
_, err := app.StakingKeeper.Undelegate(ctx, addrAcc, valAddr1, sdk.NewDecFromInt(unbondingTokens))
suite.NoError(err)
assert.NilError(t, err)
valAddr2, err1 := sdk.ValAddressFromBech32(addrVal2)
suite.NoError(err1)
assert.NilError(t, err1)
_, err = app.StakingKeeper.Undelegate(ctx, addrAcc, valAddr2, sdk.NewDecFromInt(unbondingTokens))
suite.NoError(err)
assert.NilError(t, err)
unbond, found := app.StakingKeeper.GetUnbondingDelegation(ctx, addrAcc, valAddr1)
suite.True(found)
assert.Assert(t, found)
var req *types.QueryDelegatorUnbondingDelegationsRequest
testCases := []struct {
msg string
malleate func()
expPass bool
expErr bool
msg string
malleate func()
expPass bool
expErr bool
expErrMsg string
}{
{
"empty request",
@ -465,6 +520,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorUnbondingDelegations()
},
false,
true,
"delegator address cannot be empty",
},
{
"invalid request",
@ -473,6 +529,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorUnbondingDelegations()
},
false,
false,
"",
},
{
"valid request",
@ -484,59 +541,67 @@ func (suite *IntegrationTestSuite) TestGRPCQueryDelegatorUnbondingDelegations()
},
true,
false,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.DelegatorUnbondingDelegations(gocontext.Background(), req)
if tc.expPass && !tc.expErr {
suite.NoError(err)
suite.NotNil(res.Pagination.NextKey)
suite.Equal(uint64(2), res.Pagination.Total)
suite.Len(res.UnbondingResponses, 1)
suite.Equal(unbond, res.UnbondingResponses[0])
assert.NilError(t, err)
assert.Assert(t, res.Pagination.NextKey != nil)
assert.Equal(t, uint64(2), res.Pagination.Total)
assert.Assert(t, len(res.UnbondingResponses) == 1)
assert.DeepEqual(t, unbond, res.UnbondingResponses[0])
} else if !tc.expPass && !tc.expErr {
suite.NoError(err)
suite.Nil(res.UnbondingResponses)
assert.NilError(t, err)
assert.Assert(t, res.UnbondingResponses == nil)
} else {
suite.Error(err)
suite.Nil(res)
assert.ErrorContains(t, err, tc.expErrMsg)
assert.Assert(t, res == nil)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryPoolParameters() {
app, ctx, queryClient := suite.app, suite.ctx, suite.queryClient
func TestGRPCQueryPoolParameters(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient := f.app, f.ctx, f.queryClient
bondDenom := sdk.DefaultBondDenom
// Query pool
res, err := queryClient.Pool(gocontext.Background(), &types.QueryPoolRequest{})
suite.NoError(err)
assert.NilError(t, err)
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
suite.Equal(app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount, res.Pool.NotBondedTokens)
suite.Equal(app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount, res.Pool.BondedTokens)
assert.DeepEqual(t, app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount, res.Pool.NotBondedTokens)
assert.DeepEqual(t, app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount, res.Pool.BondedTokens)
// Query Params
resp, err := queryClient.Params(gocontext.Background(), &types.QueryParamsRequest{})
suite.NoError(err)
suite.Equal(app.StakingKeeper.GetParams(ctx), resp.Params)
assert.NilError(t, err)
assert.DeepEqual(t, app.StakingKeeper.GetParams(ctx), resp.Params)
}
func (suite *IntegrationTestSuite) TestGRPCQueryHistoricalInfo() {
app, ctx, queryClient := suite.app, suite.ctx, suite.queryClient
func TestGRPCQueryHistoricalInfo(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient := f.app, f.ctx, f.queryClient
hi, found := app.StakingKeeper.GetHistoricalInfo(ctx, 5)
suite.True(found)
assert.Assert(t, found)
var req *types.QueryHistoricalInfoRequest
testCases := []struct {
msg string
malleate func()
expPass bool
msg string
malleate func()
expPass bool
expErrMsg string
}{
{
"empty request",
@ -544,6 +609,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryHistoricalInfo() {
req = &types.QueryHistoricalInfoRequest{}
},
false,
"historical info for height 0 not found",
},
{
"invalid request with negative height",
@ -551,6 +617,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryHistoricalInfo() {
req = &types.QueryHistoricalInfoRequest{Height: -1}
},
false,
"height cannot be negative",
},
{
"valid request with old height",
@ -558,6 +625,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryHistoricalInfo() {
req = &types.QueryHistoricalInfoRequest{Height: 4}
},
false,
"historical info for height 4 not found",
},
{
"valid request with current height",
@ -565,50 +633,55 @@ func (suite *IntegrationTestSuite) TestGRPCQueryHistoricalInfo() {
req = &types.QueryHistoricalInfoRequest{Height: 5}
},
true,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.HistoricalInfo(gocontext.Background(), req)
if tc.expPass {
suite.NoError(err)
suite.NotNil(res)
suite.True(hi.Equal(res.Hist))
assert.NilError(t, err)
assert.Assert(t, res != nil)
assert.Assert(t, hi.Equal(res.Hist))
} else {
suite.Error(err)
suite.Nil(res)
assert.ErrorContains(t, err, tc.expErrMsg)
assert.Assert(t, res == nil)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryRedelegations() {
app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals
func TestGRPCQueryRedelegations(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient, addrs, vals := f.app, f.ctx, f.queryClient, f.addrs, f.vals
addrAcc, addrAcc1 := addrs[0], addrs[1]
valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs)
val1, val2, val3, val4 := vals[0], vals[1], valAddrs[3], valAddrs[4]
delAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 1)
_, err := app.StakingKeeper.Delegate(ctx, addrAcc1, delAmount, types.Unbonded, val1, true)
suite.NoError(err)
applyValidatorSetUpdates(suite.T(), ctx, app.StakingKeeper, -1)
assert.NilError(t, err)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
rdAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 1)
_, err = app.StakingKeeper.BeginRedelegation(ctx, addrAcc1, val1.GetOperator(), val2.GetOperator(), sdk.NewDecFromInt(rdAmount))
suite.NoError(err)
applyValidatorSetUpdates(suite.T(), ctx, app.StakingKeeper, -1)
assert.NilError(t, err)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
redel, found := app.StakingKeeper.GetRedelegation(ctx, addrAcc1, val1.GetOperator(), val2.GetOperator())
suite.True(found)
assert.Assert(t, found)
var req *types.QueryRedelegationsRequest
testCases := []struct {
msg string
malleate func()
expPass bool
expErr bool
msg string
malleate func()
expPass bool
expErr bool
expErrMsg string
}{
{
"request redelegations for non existent addr",
@ -617,6 +690,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryRedelegations() {
},
false,
false,
fmt.Sprintf("redelegation not found for delegator address %s", addrAcc.String()),
},
{
"request redelegations with non existent pairs",
@ -628,6 +702,8 @@ func (suite *IntegrationTestSuite) TestGRPCQueryRedelegations() {
},
false,
true,
fmt.Sprintf("redelegation not found for delegator address %s from validator address %s",
addrAcc.String(), val3.String()),
},
{
"request redelegations with delegatoraddr, sourceValAddr, destValAddr",
@ -639,6 +715,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryRedelegations() {
},
true,
false,
"",
},
{
"request redelegations with delegatoraddr and sourceValAddr",
@ -650,6 +727,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryRedelegations() {
},
true,
false,
"",
},
{
"query redelegations with sourceValAddr only",
@ -661,47 +739,52 @@ func (suite *IntegrationTestSuite) TestGRPCQueryRedelegations() {
},
true,
false,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.Redelegations(gocontext.Background(), req)
if tc.expPass && !tc.expErr {
suite.NoError(err)
suite.Len(res.RedelegationResponses, len(redel.Entries))
suite.Equal(redel.DelegatorAddress, res.RedelegationResponses[0].Redelegation.DelegatorAddress)
suite.Equal(redel.ValidatorSrcAddress, res.RedelegationResponses[0].Redelegation.ValidatorSrcAddress)
suite.Equal(redel.ValidatorDstAddress, res.RedelegationResponses[0].Redelegation.ValidatorDstAddress)
suite.Len(redel.Entries, len(res.RedelegationResponses[0].Entries))
assert.NilError(t, err)
assert.Assert(t, len(res.RedelegationResponses) == len(redel.Entries))
assert.Equal(t, redel.DelegatorAddress, res.RedelegationResponses[0].Redelegation.DelegatorAddress)
assert.Equal(t, redel.ValidatorSrcAddress, res.RedelegationResponses[0].Redelegation.ValidatorSrcAddress)
assert.Equal(t, redel.ValidatorDstAddress, res.RedelegationResponses[0].Redelegation.ValidatorDstAddress)
assert.Assert(t, len(redel.Entries) == len(res.RedelegationResponses[0].Entries))
} else if !tc.expPass && !tc.expErr {
suite.NoError(err)
suite.Nil(res.RedelegationResponses)
assert.NilError(t, err)
assert.Assert(t, res.RedelegationResponses == nil)
} else {
suite.Error(err)
suite.Nil(res)
assert.ErrorContains(t, err, tc.expErrMsg)
assert.Assert(t, res == nil)
}
})
}
}
func (suite *IntegrationTestSuite) TestGRPCQueryValidatorUnbondingDelegations() {
app, ctx, queryClient, addrs, vals := suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals
func TestGRPCQueryValidatorUnbondingDelegations(t *testing.T) {
t.Parallel()
f := initFixture(t)
app, ctx, queryClient, addrs, vals := f.app, f.ctx, f.queryClient, f.addrs, f.vals
addrAcc1, _ := addrs[0], addrs[1]
val1 := vals[0]
// undelegate
undelAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 2)
_, err := app.StakingKeeper.Undelegate(ctx, addrAcc1, val1.GetOperator(), sdk.NewDecFromInt(undelAmount))
suite.NoError(err)
applyValidatorSetUpdates(suite.T(), ctx, app.StakingKeeper, -1)
assert.NilError(t, err)
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
var req *types.QueryValidatorUnbondingDelegationsRequest
testCases := []struct {
msg string
malleate func()
expPass bool
msg string
malleate func()
expPass bool
expErrMsg string
}{
{
"empty request",
@ -709,6 +792,7 @@ func (suite *IntegrationTestSuite) TestGRPCQueryValidatorUnbondingDelegations()
req = &types.QueryValidatorUnbondingDelegationsRequest{}
},
false,
"validator address cannot be empty",
},
{
"valid request",
@ -719,21 +803,22 @@ func (suite *IntegrationTestSuite) TestGRPCQueryValidatorUnbondingDelegations()
}
},
true,
"",
},
}
for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.msg), func() {
t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) {
tc.malleate()
res, err := queryClient.ValidatorUnbondingDelegations(gocontext.Background(), req)
if tc.expPass {
suite.NoError(err)
suite.Equal(uint64(1), res.Pagination.Total)
suite.Equal(1, len(res.UnbondingResponses))
suite.Equal(res.UnbondingResponses[0].ValidatorAddress, val1.OperatorAddress)
assert.NilError(t, err)
assert.Equal(t, uint64(1), res.Pagination.Total)
assert.Equal(t, 1, len(res.UnbondingResponses))
assert.Equal(t, res.UnbondingResponses[0].ValidatorAddress, val1.OperatorAddress)
} else {
suite.Error(err)
suite.Nil(res)
assert.ErrorContains(t, err, tc.expErrMsg)
assert.Assert(t, res == nil)
}
})
}

View File

@ -3,20 +3,18 @@ package keeper_test
import (
"testing"
"github.com/stretchr/testify/suite"
"cosmossdk.io/simapp"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"cosmossdk.io/simapp"
"github.com/cosmos/cosmos-sdk/baseapp"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
type IntegrationTestSuite struct {
suite.Suite
// fixture uses simapp (and not a depinjected app) because we manually set a
// new app.StakingKeeper in `createValidators`.
type fixture struct {
app *simapp.SimApp
ctx sdk.Context
addrs []sdk.AccAddress
@ -25,8 +23,13 @@ type IntegrationTestSuite struct {
msgServer types.MsgServer
}
func (suite *IntegrationTestSuite) SetupTest() {
app := simapp.Setup(suite.T(), false)
// initFixture uses simapp (and not a depinjected app) because we manually set a
// new app.StakingKeeper in `createValidators` which is used in most of the
// staking keeper tests.
func initFixture(t *testing.T) *fixture {
f := &fixture{}
app := simapp.Setup(t, false)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
querier := keeper.Querier{Keeper: app.StakingKeeper}
@ -35,9 +38,9 @@ func (suite *IntegrationTestSuite) SetupTest() {
types.RegisterQueryServer(queryHelper, querier)
queryClient := types.NewQueryClient(queryHelper)
suite.msgServer = keeper.NewMsgServerImpl(app.StakingKeeper)
f.msgServer = keeper.NewMsgServerImpl(app.StakingKeeper)
addrs, _, validators := createValidators(suite.T(), ctx, app, []int64{9, 8, 7})
addrs, _, validators := createValidators(t, ctx, app, []int64{9, 8, 7})
header := tmproto.Header{
ChainID: "HelloChain",
Height: 5,
@ -50,9 +53,7 @@ func (suite *IntegrationTestSuite) SetupTest() {
hi := types.NewHistoricalInfo(header, sortedVals, app.StakingKeeper.PowerReduction(ctx))
app.StakingKeeper.SetHistoricalInfo(ctx, 5, &hi)
suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals = app, ctx, queryClient, addrs, validators
}
f.app, f.ctx, f.queryClient, f.addrs, f.vals = app, ctx, queryClient, addrs, validators
func TestIntegrationTestSuite(t *testing.T) {
suite.Run(t, new(IntegrationTestSuite))
return f
}

View File

@ -4,43 +4,64 @@ import (
"testing"
"time"
"cosmossdk.io/simapp"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"gotest.tools/v3/assert"
"github.com/cosmos/cosmos-sdk/testutil/configurator"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
func TestCancelUnbondingDelegation(t *testing.T) {
// setup the app
app := simapp.Setup(t, false)
var (
stakingKeeper *keeper.Keeper
bankKeeper bankkeeper.Keeper
accountKeeper authkeeper.AccountKeeper
)
app, err := simtestutil.SetupWithConfiguration(
configurator.NewAppConfig(
configurator.BankModule(),
configurator.TxModule(),
configurator.StakingModule(),
configurator.ParamsModule(),
configurator.ConsensusModule(),
configurator.AuthModule(),
),
simtestutil.DefaultStartUpConfig(),
&stakingKeeper, &bankKeeper, &accountKeeper)
assert.NilError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
msgServer := keeper.NewMsgServerImpl(app.StakingKeeper)
bondDenom := app.StakingKeeper.BondDenom(ctx)
msgServer := keeper.NewMsgServerImpl(stakingKeeper)
bondDenom := stakingKeeper.BondDenom(ctx)
// set the not bonded pool module account
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
startTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 5)
notBondedPool := stakingKeeper.GetNotBondedPool(ctx)
startTokens := stakingKeeper.TokensFromConsensusPower(ctx, 5)
require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), startTokens))))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
assert.NilError(t, testutil.FundModuleAccount(bankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(stakingKeeper.BondDenom(ctx), startTokens))))
accountKeeper.SetModuleAccount(ctx, notBondedPool)
moduleBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), app.StakingKeeper.BondDenom(ctx))
require.Equal(t, sdk.NewInt64Coin(bondDenom, startTokens.Int64()), moduleBalance)
moduleBalance := bankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), stakingKeeper.BondDenom(ctx))
assert.DeepEqual(t, sdk.NewInt64Coin(bondDenom, startTokens.Int64()), moduleBalance)
// accounts
delAddrs := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(10000))
validators := app.StakingKeeper.GetValidators(ctx, 10)
require.Equal(t, len(validators), 1)
delAddrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 2, sdk.NewInt(10000))
validators := stakingKeeper.GetValidators(ctx, 10)
assert.Equal(t, len(validators), 1)
validatorAddr, err := sdk.ValAddressFromBech32(validators[0].OperatorAddress)
require.NoError(t, err)
assert.NilError(t, err)
delegatorAddr := delAddrs[0]
// setting the ubd entry
unbondingAmount := sdk.NewInt64Coin(app.StakingKeeper.BondDenom(ctx), 5)
unbondingAmount := sdk.NewInt64Coin(stakingKeeper.BondDenom(ctx), 5)
ubd := types.NewUnbondingDelegation(
delegatorAddr, validatorAddr, 10,
ctx.BlockTime().Add(time.Minute*10),
@ -49,15 +70,16 @@ func TestCancelUnbondingDelegation(t *testing.T) {
)
// set and retrieve a record
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
resUnbond, found := app.StakingKeeper.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr)
require.True(t, found)
require.Equal(t, ubd, resUnbond)
stakingKeeper.SetUnbondingDelegation(ctx, ubd)
resUnbond, found := stakingKeeper.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr)
assert.Assert(t, found)
assert.DeepEqual(t, ubd, resUnbond)
testCases := []struct {
Name string
ExceptErr bool
req types.MsgCancelUnbondingDelegation
expErrMsg string
}{
{
Name: "invalid height",
@ -65,9 +87,10 @@ func TestCancelUnbondingDelegation(t *testing.T) {
req: types.MsgCancelUnbondingDelegation{
DelegatorAddress: resUnbond.DelegatorAddress,
ValidatorAddress: resUnbond.ValidatorAddress,
Amount: sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), sdk.NewInt(4)),
Amount: sdk.NewCoin(stakingKeeper.BondDenom(ctx), sdk.NewInt(4)),
CreationHeight: 0,
},
expErrMsg: "unbonding delegation entry is not found at block height",
},
{
Name: "invalid coin",
@ -78,6 +101,7 @@ func TestCancelUnbondingDelegation(t *testing.T) {
Amount: sdk.NewCoin("dump_coin", sdk.NewInt(4)),
CreationHeight: 0,
},
expErrMsg: "invalid coin denomination",
},
{
Name: "validator not exists",
@ -88,6 +112,7 @@ func TestCancelUnbondingDelegation(t *testing.T) {
Amount: unbondingAmount,
CreationHeight: 0,
},
expErrMsg: "validator does not exist",
},
{
Name: "invalid delegator address",
@ -98,6 +123,7 @@ func TestCancelUnbondingDelegation(t *testing.T) {
Amount: unbondingAmount,
CreationHeight: 0,
},
expErrMsg: "decoding bech32 failed",
},
{
Name: "invalid amount",
@ -108,6 +134,7 @@ func TestCancelUnbondingDelegation(t *testing.T) {
Amount: unbondingAmount.Add(sdk.NewInt64Coin(bondDenom, 10)),
CreationHeight: 10,
},
expErrMsg: "amount is greater than the unbonding delegation entry balance",
},
{
Name: "success",
@ -135,11 +162,11 @@ func TestCancelUnbondingDelegation(t *testing.T) {
t.Run(testCase.Name, func(t *testing.T) {
_, err := msgServer.CancelUnbondingDelegation(ctx, &testCase.req)
if testCase.ExceptErr {
require.Error(t, err)
assert.ErrorContains(t, err, testCase.expErrMsg)
} else {
require.NoError(t, err)
balanceForNotBondedPool := app.BankKeeper.GetBalance(ctx, sdk.AccAddress(notBondedPool.GetAddress()), bondDenom)
require.Equal(t, balanceForNotBondedPool, moduleBalance.Sub(testCase.req.Amount))
assert.NilError(t, err)
balanceForNotBondedPool := bankKeeper.GetBalance(ctx, sdk.AccAddress(notBondedPool.GetAddress()), bondDenom)
assert.DeepEqual(t, balanceForNotBondedPool, moduleBalance.Sub(testCase.req.Amount))
moduleBalance = moduleBalance.Sub(testCase.req.Amount)
}
})

View File

@ -3,25 +3,40 @@ package keeper
import (
"testing"
"cosmossdk.io/simapp"
"github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"gotest.tools/v3/assert"
"github.com/cosmos/cosmos-sdk/testutil/configurator"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/types"
)
func TestParams(t *testing.T) {
app := simapp.Setup(t, false)
var stakingKeeper *keeper.Keeper
app, err := simtestutil.SetupWithConfiguration(
configurator.NewAppConfig(
configurator.BankModule(),
configurator.TxModule(),
configurator.StakingModule(),
configurator.ParamsModule(),
configurator.ConsensusModule(),
configurator.AuthModule(),
),
simtestutil.DefaultStartUpConfig(),
&stakingKeeper)
assert.NilError(t, err)
ctx := app.BaseApp.NewContext(false, tmproto.Header{})
expParams := types.DefaultParams()
// check that the empty keeper loads the default
resParams := app.StakingKeeper.GetParams(ctx)
require.True(t, expParams.Equal(resParams))
resParams := stakingKeeper.GetParams(ctx)
assert.Assert(t, expParams.Equal(resParams))
// modify a params, save, and retrieve
expParams.MaxValidators = 777
app.StakingKeeper.SetParams(ctx, expParams)
resParams = app.StakingKeeper.GetParams(ctx)
require.True(t, expParams.Equal(resParams))
stakingKeeper.SetParams(ctx, expParams)
resParams = stakingKeeper.GetParams(ctx)
assert.Assert(t, expParams.Equal(resParams))
}

View File

@ -5,11 +5,11 @@ import (
"time"
"cosmossdk.io/math"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"cosmossdk.io/simapp"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"gotest.tools/v3/assert"
sdktestutil "github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
@ -27,7 +27,7 @@ func bootstrapSlashTest(t *testing.T, power int64) (*simapp.SimApp, sdk.Context,
totalSupply := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), amt.MulRaw(int64(len(addrDels)))))
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), totalSupply))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), totalSupply))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
@ -37,7 +37,7 @@ func bootstrapSlashTest(t *testing.T, power int64) (*simapp.SimApp, sdk.Context,
// set bonded pool balance
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), bondedCoins))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), bondedCoins))
for i := int64(0); i < numVals; i++ {
validator := testutil.NewValidator(t, addrVals[i], PKs[i])
@ -64,13 +64,13 @@ func TestSlashUnbondingDelegation(t *testing.T) {
// unbonding started prior to the infraction height, stakw didn't contribute
slashAmount := app.StakingKeeper.SlashUnbondingDelegation(ctx, ubd, 1, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(0)))
assert.Assert(t, slashAmount.Equal(sdk.NewInt(0)))
// after the expiration time, no longer eligible for slashing
ctx = ctx.WithBlockHeader(tmproto.Header{Time: time.Unix(10, 0)})
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
slashAmount = app.StakingKeeper.SlashUnbondingDelegation(ctx, ubd, 0, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(0)))
assert.Assert(t, slashAmount.Equal(sdk.NewInt(0)))
// test valid slash, before expiration timestamp and to which stake contributed
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
@ -78,19 +78,19 @@ func TestSlashUnbondingDelegation(t *testing.T) {
ctx = ctx.WithBlockHeader(tmproto.Header{Time: time.Unix(0, 0)})
app.StakingKeeper.SetUnbondingDelegation(ctx, ubd)
slashAmount = app.StakingKeeper.SlashUnbondingDelegation(ctx, ubd, 0, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(5)))
assert.Assert(t, slashAmount.Equal(sdk.NewInt(5)))
ubd, found := app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(ubd.Entries) == 1)
// initial balance unchanged
require.Equal(t, sdk.NewInt(10), ubd.Entries[0].InitialBalance)
assert.DeepEqual(t, sdk.NewInt(10), ubd.Entries[0].InitialBalance)
// balance decreased
require.Equal(t, sdk.NewInt(5), ubd.Entries[0].Balance)
assert.DeepEqual(t, sdk.NewInt(5), ubd.Entries[0].Balance)
newUnbondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, notBondedPool.GetAddress())
diffTokens := oldUnbondedPoolBalances.Sub(newUnbondedPoolBalances...)
require.True(t, diffTokens.AmountOf(app.StakingKeeper.BondDenom(ctx)).Equal(sdk.NewInt(5)))
assert.Assert(t, diffTokens.AmountOf(app.StakingKeeper.BondDenom(ctx)).Equal(sdk.NewInt(5)))
}
// tests slashRedelegation
@ -101,9 +101,9 @@ func TestSlashRedelegation(t *testing.T) {
// add bonded tokens to pool for (re)delegations
startCoins := sdk.NewCoins(sdk.NewInt64Coin(app.StakingKeeper.BondDenom(ctx), 15))
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
balances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
_ = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), startCoins))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), startCoins))
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
// set a redelegation with an expiration timestamp beyond which the
@ -119,45 +119,45 @@ func TestSlashRedelegation(t *testing.T) {
// started redelegating prior to the current height, stake didn't contribute to infraction
validator, found := app.StakingKeeper.GetValidator(ctx, addrVals[1])
require.True(t, found)
assert.Assert(t, found)
slashAmount := app.StakingKeeper.SlashRedelegation(ctx, validator, rd, 1, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(0)))
assert.Assert(t, slashAmount.Equal(sdk.NewInt(0)))
// after the expiration time, no longer eligible for slashing
ctx = ctx.WithBlockHeader(tmproto.Header{Time: time.Unix(10, 0)})
app.StakingKeeper.SetRedelegation(ctx, rd)
validator, found = app.StakingKeeper.GetValidator(ctx, addrVals[1])
require.True(t, found)
assert.Assert(t, found)
slashAmount = app.StakingKeeper.SlashRedelegation(ctx, validator, rd, 0, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(0)))
assert.Assert(t, slashAmount.Equal(sdk.NewInt(0)))
balances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
balances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
// test valid slash, before expiration timestamp and to which stake contributed
ctx = ctx.WithBlockHeader(tmproto.Header{Time: time.Unix(0, 0)})
app.StakingKeeper.SetRedelegation(ctx, rd)
validator, found = app.StakingKeeper.GetValidator(ctx, addrVals[1])
require.True(t, found)
assert.Assert(t, found)
slashAmount = app.StakingKeeper.SlashRedelegation(ctx, validator, rd, 0, fraction)
require.True(t, slashAmount.Equal(sdk.NewInt(5)))
assert.Assert(t, slashAmount.Equal(sdk.NewInt(5)))
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(rd.Entries) == 1)
// end block
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
// initialbalance unchanged
require.Equal(t, sdk.NewInt(10), rd.Entries[0].InitialBalance)
assert.DeepEqual(t, sdk.NewInt(10), rd.Entries[0].InitialBalance)
// shares decreased
del, found = app.StakingKeeper.GetDelegation(ctx, addrDels[0], addrVals[1])
require.True(t, found)
require.Equal(t, int64(5), del.Shares.RoundInt64())
assert.Assert(t, found)
assert.Equal(t, int64(5), del.Shares.RoundInt64())
// pool bonded tokens should decrease
burnedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), slashAmount))
require.Equal(t, balances.Sub(burnedCoins...), app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()))
assert.DeepEqual(t, balances.Sub(burnedCoins...), app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()))
}
// test slash at a negative height
@ -170,26 +170,26 @@ func TestSlashAtNegativeHeight(t *testing.T) {
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
oldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
_, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
app.StakingKeeper.Slash(ctx, consAddr, -2, 10, fraction)
// read updated state
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
// end block
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found = app.StakingKeeper.GetValidator(ctx, validator.GetOperator())
require.True(t, found)
assert.Assert(t, found)
// power decreased
require.Equal(t, int64(5), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
assert.Equal(t, int64(5), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// pool bonded shares decreased
newBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 5).String(), diffTokens.String())
assert.DeepEqual(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 5).String(), diffTokens.String())
}
// tests Slash at the current height
@ -201,26 +201,26 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) {
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
oldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
_, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
app.StakingKeeper.Slash(ctx, consAddr, ctx.BlockHeight(), 10, fraction)
// read updated state
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
// end block
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validator, found = app.StakingKeeper.GetValidator(ctx, validator.GetOperator())
assert.True(t, found)
assert.Assert(t, found)
// power decreased
require.Equal(t, int64(5), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
assert.Equal(t, int64(5), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// pool bonded shares decreased
newBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 5).String(), diffTokens.String())
assert.DeepEqual(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 5).String(), diffTokens.String())
}
// tests Slash at a previous height with an unbonding delegation
@ -241,8 +241,8 @@ func TestSlashWithUnbondingDelegation(t *testing.T) {
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
oldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
_, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)
// end block
@ -250,49 +250,49 @@ func TestSlashWithUnbondingDelegation(t *testing.T) {
// read updating unbonding delegation
ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(ubd.Entries) == 1)
// balance decreased
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)
assert.DeepEqual(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)
// bonded tokens burned
newBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)
assert.DeepEqual(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
// power decreased by 3 - 6 stake originally bonded at the time of infraction
// was still bonded at the time of discovery and was slashed by half, 4 stake
// bonded at the time of discovery hadn't been bonded at the time of infraction
// and wasn't slashed
require.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
assert.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// slash validator again
ctx = ctx.WithBlockHeight(13)
app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)
ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(ubd.Entries) == 1)
// balance decreased again
require.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)
assert.DeepEqual(t, sdk.NewInt(0), ubd.Entries[0].Balance)
// bonded tokens burned again
newBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)
assert.DeepEqual(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
assert.Assert(t, found)
// power decreased by 3 again
require.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
assert.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// slash validator again
// all originally bonded stake has been slashed, so this will have no effect
@ -302,23 +302,23 @@ func TestSlashWithUnbondingDelegation(t *testing.T) {
app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)
ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(ubd.Entries) == 1)
// balance unchanged
require.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)
assert.DeepEqual(t, sdk.NewInt(0), ubd.Entries[0].Balance)
// bonded tokens burned again
newBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)
assert.DeepEqual(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
assert.Assert(t, found)
// power decreased by 3 again
require.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
assert.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// slash validator again
// all originally bonded stake has been slashed, so this will have no effect
@ -328,16 +328,16 @@ func TestSlashWithUnbondingDelegation(t *testing.T) {
app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)
ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])
require.True(t, found)
require.Len(t, ubd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(ubd.Entries) == 1)
// balance unchanged
require.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)
assert.DeepEqual(t, sdk.NewInt(0), ubd.Entries[0].Balance)
// just 1 bonded token burned again since that's all the validator now has
newBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())
diffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances...).AmountOf(app.StakingKeeper.BondDenom(ctx))
require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)
assert.DeepEqual(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)
// apply TM updates
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
@ -346,7 +346,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) {
// power decreased by 1 again, validator is out of stake
// validator should be in unbonding period
validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.Equal(t, validator.GetStatus(), types.Unbonding)
assert.Equal(t, validator.GetStatus(), types.Unbonding)
}
// tests Slash at a previous height with a redelegation
@ -370,7 +370,7 @@ func TestSlashWithRedelegation(t *testing.T) {
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
rdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
@ -379,10 +379,10 @@ func TestSlashWithRedelegation(t *testing.T) {
// slash validator
ctx = ctx.WithBlockHeight(12)
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
_, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
require.NotPanics(t, func() {
sdktestutil.AssertNotPanics(t, func() {
app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)
})
burnAmount := sdk.NewDecFromInt(app.StakingKeeper.TokensFromConsensusPower(ctx, 10)).Mul(fraction).TruncateInt()
@ -392,30 +392,30 @@ func TestSlashWithRedelegation(t *testing.T) {
// burn bonded tokens from only from delegations
bondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
assert.Assert(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
notBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
oldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
// read updating redelegation
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(rd.Entries) == 1)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
// power decreased by 2 - 4 stake originally bonded at the time of infraction
// was still bonded at the time of discovery and was slashed by half, 4 stake
// bonded at the time of discovery hadn't been bonded at the time of infraction
// and wasn't slashed
require.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
assert.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// slash the validator again
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
_, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
require.NotPanics(t, func() {
sdktestutil.AssertNotPanics(t, func() {
app.StakingKeeper.Slash(ctx, consAddr, 10, 10, math.LegacyOneDec())
})
burnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)
@ -426,32 +426,32 @@ func TestSlashWithRedelegation(t *testing.T) {
// seven bonded tokens burned
bondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
require.True(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
assert.Assert(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
bondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
assert.Assert(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
notBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
oldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
// read updating redelegation
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(rd.Entries) == 1)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
assert.Assert(t, found)
// power decreased by 4
require.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
assert.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
// slash the validator again, by 100%
ctx = ctx.WithBlockHeight(12)
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.True(t, found)
_, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
assert.Assert(t, found)
require.NotPanics(t, func() {
sdktestutil.AssertNotPanics(t, func() {
app.StakingKeeper.Slash(ctx, consAddr, 10, 10, math.LegacyOneDec())
})
@ -463,30 +463,30 @@ func TestSlashWithRedelegation(t *testing.T) {
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
bondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
assert.Assert(math.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))
notBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
oldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
// read updating redelegation
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(rd.Entries) == 1)
// apply TM updates
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
// read updated validator
// validator decreased to zero power, should be in unbonding period
validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.Equal(t, validator.GetStatus(), types.Unbonding)
assert.Equal(t, validator.GetStatus(), types.Unbonding)
// slash the validator again, by 100%
// no stake remains to be slashed
ctx = ctx.WithBlockHeight(12)
// validator still in unbonding period
validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.Equal(t, validator.GetStatus(), types.Unbonding)
assert.Equal(t, validator.GetStatus(), types.Unbonding)
require.NotPanics(t, func() {
sdktestutil.AssertNotPanics(t, func() {
app.StakingKeeper.Slash(ctx, consAddr, 10, 10, math.LegacyOneDec())
})
@ -495,18 +495,18 @@ func TestSlashWithRedelegation(t *testing.T) {
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
bondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldBonded, bondedPoolBalance))
assert.Assert(math.IntEq(t, oldBonded, bondedPoolBalance))
notBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
assert.Assert(math.IntEq(t, oldNotBonded, notBondedPoolBalance))
// read updating redelegation
rd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rd.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(rd.Entries) == 1)
// read updated validator
// power still zero, still in unbonding period
validator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)
require.Equal(t, validator.GetStatus(), types.Unbonding)
assert.Equal(t, validator.GetStatus(), types.Unbonding)
}
// tests Slash at a previous height with both an unbonding delegation and a redelegation
@ -539,8 +539,8 @@ func TestSlashBoth(t *testing.T) {
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), bondedCoins))
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), notBondedCoins))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), bondedCoins))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), notBondedCoins))
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
@ -549,8 +549,8 @@ func TestSlashBoth(t *testing.T) {
oldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
// slash validator
ctx = ctx.WithBlockHeight(12)
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))
require.True(t, found)
_, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))
assert.Assert(t, found)
consAddr0 := sdk.ConsAddress(PKs[0].Address())
app.StakingKeeper.Slash(ctx, consAddr0, 10, 10, fraction)
@ -563,20 +563,20 @@ func TestSlashBoth(t *testing.T) {
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
bondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldBonded.Sub(burnedBondAmount), bondedPoolBalance))
assert.Assert(math.IntEq(t, oldBonded.Sub(burnedBondAmount), bondedPoolBalance))
notBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, oldNotBonded.Sub(burnedNotBondedAmount), notBondedPoolBalance))
assert.Assert(math.IntEq(t, oldNotBonded.Sub(burnedNotBondedAmount), notBondedPoolBalance))
// read updating redelegation
rdA, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.True(t, found)
require.Len(t, rdA.Entries, 1)
assert.Assert(t, found)
assert.Assert(t, len(rdA.Entries) == 1)
// read updated validator
validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))
require.True(t, found)
validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))
assert.Assert(t, found)
// power not decreased, all stake was bonded since
require.Equal(t, int64(10), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
assert.Equal(t, int64(10), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))
}
func TestSlashAmount(t *testing.T) {
@ -584,10 +584,10 @@ func TestSlashAmount(t *testing.T) {
consAddr := sdk.ConsAddress(PKs[0].Address())
fraction := sdk.NewDecWithPrec(5, 1)
burnedCoins := app.StakingKeeper.Slash(ctx, consAddr, ctx.BlockHeight(), 10, fraction)
require.True(t, burnedCoins.GT(math.ZeroInt()))
assert.Assert(t, burnedCoins.GT(math.ZeroInt()))
// test the case where the validator was not found, which should return no coins
_, addrVals := generateAddresses(app, ctx, 100)
noBurned := app.StakingKeeper.Slash(ctx, sdk.ConsAddress(addrVals[0]), ctx.BlockHeight(), 10, fraction)
require.True(t, sdk.NewInt(0).Equal(noBurned))
assert.Assert(t, sdk.NewInt(0).Equal(noBurned))
}

View File

@ -6,14 +6,15 @@ import (
"cosmossdk.io/math"
"cosmossdk.io/simapp"
"github.com/golang/mock/gomock"
"gotest.tools/v3/assert"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/testutil"
"github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
)
// SetupUnbondingTests creates two validators and setup mocked staking hooks for testing unbonding
@ -28,7 +29,7 @@ func SetupUnbondingTests(t *testing.T, app *simapp.SimApp, ctx sdk.Context, hook
*ubdeID = id
// call back to stop unbonding
err := app.StakingKeeper.PutUnbondingOnHold(ctx, id)
require.NoError(t, err)
assert.NilError(t, err)
return nil
}).AnyTimes()
@ -52,18 +53,18 @@ func SetupUnbondingTests(t *testing.T, app *simapp.SimApp, ctx sdk.Context, hook
bondDenom = app.StakingKeeper.BondDenom(ctx)
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, startTokens))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(bondDenom, startTokens))))
app.BankKeeper.SendCoinsFromModuleToModule(ctx, types.BondedPoolName, types.NotBondedPoolName, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, startTokens)))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
// Create a validator
validator1 := testutil.NewValidator(t, addrVals[0], PKs[0])
validator1, issuedShares1 := validator1.AddTokensFromDel(valTokens)
require.Equal(t, valTokens, issuedShares1.RoundInt())
assert.DeepEqual(t, valTokens, issuedShares1.RoundInt())
validator1 = stakingkeeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator1, true)
require.True(math.IntEq(t, valTokens, validator1.BondedTokens()))
require.True(t, validator1.IsBonded())
assert.Assert(math.IntEq(t, valTokens, validator1.BondedTokens()))
assert.Assert(t, validator1.IsBonded())
// Create a delegator
delegation := types.NewDelegation(addrDels[0], addrVals[0], issuedShares1)
@ -72,11 +73,11 @@ func SetupUnbondingTests(t *testing.T, app *simapp.SimApp, ctx sdk.Context, hook
// Create a validator to redelegate to
validator2 := testutil.NewValidator(t, addrVals[1], PKs[1])
validator2, issuedShares2 := validator2.AddTokensFromDel(valTokens)
require.Equal(t, valTokens, issuedShares2.RoundInt())
assert.DeepEqual(t, valTokens, issuedShares2.RoundInt())
validator2 = stakingkeeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator2, true)
require.Equal(t, types.Bonded, validator2.Status)
require.True(t, validator2.IsBonded())
assert.Equal(t, types.Bonded, validator2.Status)
assert.Assert(t, validator2.IsBonded())
return bondDenom, addrDels, addrVals
}
@ -98,22 +99,22 @@ func doUnbondingDelegation(
var err error
completionTime, err = stakingKeeper.Undelegate(ctx, addrDels[0], addrVals[0], sdk.NewDec(1))
require.NoError(t, err)
assert.NilError(t, err)
// check that the unbonding actually happened
bondedAmt2 := bankKeeper.GetBalance(ctx, stakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
notBondedAmt2 := bankKeeper.GetBalance(ctx, stakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
// Bonded amount is less
require.True(math.IntEq(t, bondedAmt1.SubRaw(1), bondedAmt2))
assert.Assert(math.IntEq(t, bondedAmt1.SubRaw(1), bondedAmt2))
// Unbonded amount is more
require.True(math.IntEq(t, notBondedAmt1.AddRaw(1), notBondedAmt2))
assert.Assert(math.IntEq(t, notBondedAmt1.AddRaw(1), notBondedAmt2))
// Check that the unbonding happened- we look up the entry and see that it has the correct number of shares
unbondingDelegations := stakingKeeper.GetUnbondingDelegationsFromValidator(ctx, addrVals[0])
require.Equal(t, math.NewInt(1), unbondingDelegations[0].Entries[0].Balance)
assert.DeepEqual(t, math.NewInt(1), unbondingDelegations[0].Entries[0].Balance)
// check that our hook was called
require.True(t, *hookCalled)
assert.Assert(t, *hookCalled)
return completionTime, bondedAmt2, notBondedAmt2
}
@ -128,15 +129,15 @@ func doRedelegation(
) (completionTime time.Time) {
var err error
completionTime, err = stakingKeeper.BeginRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1], sdk.NewDec(1))
require.NoError(t, err)
assert.NilError(t, err)
// Check that the redelegation happened- we look up the entry and see that it has the correct number of shares
redelegations := stakingKeeper.GetRedelegationsFromSrcValidator(ctx, addrVals[0])
require.Equal(t, 1, len(redelegations))
require.Equal(t, sdk.NewDec(1), redelegations[0].Entries[0].SharesDst)
assert.Equal(t, 1, len(redelegations))
assert.DeepEqual(t, sdk.NewDec(1), redelegations[0].Entries[0].SharesDst)
// check that our hook was called
require.True(t, *hookCalled)
assert.Assert(t, *hookCalled)
return completionTime
}
@ -149,18 +150,18 @@ func doValidatorUnbonding(
hookCalled *bool,
) (validator types.Validator) {
validator, found := stakingKeeper.GetValidator(ctx, addrVal)
require.True(t, found)
assert.Assert(t, found)
// Check that status is bonded
require.Equal(t, types.BondStatus(3), validator.Status)
assert.Equal(t, types.BondStatus(3), validator.Status)
validator, err := stakingKeeper.BeginUnbondingValidator(ctx, validator)
require.NoError(t, err)
assert.NilError(t, err)
// Check that status is unbonding
require.Equal(t, types.BondStatus(2), validator.Status)
assert.Equal(t, types.BondStatus(2), validator.Status)
// check that our hook was called
require.True(t, *hookCalled)
assert.Assert(t, *hookCalled)
return validator
}
@ -182,18 +183,18 @@ func TestValidatorUnbondingOnHold1(t *testing.T) {
// CONSUMER CHAIN'S UNBONDING PERIOD ENDS - STOPPED UNBONDING CAN NOW COMPLETE
err := app.StakingKeeper.UnbondingCanComplete(ctx, ubdeID)
require.NoError(t, err)
assert.NilError(t, err)
// Try to unbond validator
app.StakingKeeper.UnbondAllMatureValidators(ctx)
// Check that validator unbonding is not complete (is not mature yet)
validator, found := app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
require.Equal(t, types.Unbonding, validator.Status)
assert.Assert(t, found)
assert.Equal(t, types.Unbonding, validator.Status)
unbondingVals := app.StakingKeeper.GetUnbondingValidators(ctx, completionTime, completionHeight)
require.Equal(t, 1, len(unbondingVals))
require.Equal(t, validator.OperatorAddress, unbondingVals[0])
assert.Equal(t, 1, len(unbondingVals))
assert.Equal(t, validator.OperatorAddress, unbondingVals[0])
// PROVIDER CHAIN'S UNBONDING PERIOD ENDS - BUT UNBONDING CANNOT COMPLETE
ctx = ctx.WithBlockTime(completionTime.Add(time.Duration(1)))
@ -202,10 +203,10 @@ func TestValidatorUnbondingOnHold1(t *testing.T) {
// Check that validator unbonding is complete
validator, found = app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
require.Equal(t, types.Unbonded, validator.Status)
assert.Assert(t, found)
assert.Equal(t, types.Unbonded, validator.Status)
unbondingVals = app.StakingKeeper.GetUnbondingValidators(ctx, completionTime, completionHeight)
require.Equal(t, 0, len(unbondingVals))
assert.Equal(t, 0, len(unbondingVals))
}
func TestValidatorUnbondingOnHold2(t *testing.T) {
@ -230,10 +231,10 @@ func TestValidatorUnbondingOnHold2(t *testing.T) {
ubdeIDs = append(ubdeIDs, ubdeID)
// Check that there are two unbonding operations
require.Equal(t, 2, len(ubdeIDs))
assert.Equal(t, 2, len(ubdeIDs))
// Check that both validators have same unbonding time
require.Equal(t, validator1.UnbondingTime, validator2.UnbondingTime)
assert.Equal(t, validator1.UnbondingTime, validator2.UnbondingTime)
completionTime := validator1.UnbondingTime
completionHeight := validator1.UnbondingHeight
@ -245,47 +246,47 @@ func TestValidatorUnbondingOnHold2(t *testing.T) {
// Check that unbonding is not complete for both validators
validator1, found := app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
require.Equal(t, types.Unbonding, validator1.Status)
assert.Assert(t, found)
assert.Equal(t, types.Unbonding, validator1.Status)
validator2, found = app.StakingKeeper.GetValidator(ctx, addrVals[1])
require.True(t, found)
require.Equal(t, types.Unbonding, validator2.Status)
assert.Assert(t, found)
assert.Equal(t, types.Unbonding, validator2.Status)
unbondingVals := app.StakingKeeper.GetUnbondingValidators(ctx, completionTime, completionHeight)
require.Equal(t, 2, len(unbondingVals))
require.Equal(t, validator1.OperatorAddress, unbondingVals[0])
require.Equal(t, validator2.OperatorAddress, unbondingVals[1])
assert.Equal(t, 2, len(unbondingVals))
assert.Equal(t, validator1.OperatorAddress, unbondingVals[0])
assert.Equal(t, validator2.OperatorAddress, unbondingVals[1])
// CONSUMER CHAIN'S UNBONDING PERIOD ENDS - STOPPED UNBONDING CAN NOW COMPLETE
err := app.StakingKeeper.UnbondingCanComplete(ctx, ubdeIDs[0])
require.NoError(t, err)
assert.NilError(t, err)
// Try again to unbond validators
app.StakingKeeper.UnbondAllMatureValidators(ctx)
// Check that unbonding is complete for validator1, but not for validator2
validator1, found = app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.True(t, found)
require.Equal(t, types.Unbonded, validator1.Status)
assert.Assert(t, found)
assert.Equal(t, types.Unbonded, validator1.Status)
validator2, found = app.StakingKeeper.GetValidator(ctx, addrVals[1])
require.True(t, found)
require.Equal(t, types.Unbonding, validator2.Status)
assert.Assert(t, found)
assert.Equal(t, types.Unbonding, validator2.Status)
unbondingVals = app.StakingKeeper.GetUnbondingValidators(ctx, completionTime, completionHeight)
require.Equal(t, 1, len(unbondingVals))
require.Equal(t, validator2.OperatorAddress, unbondingVals[0])
assert.Equal(t, 1, len(unbondingVals))
assert.Equal(t, validator2.OperatorAddress, unbondingVals[0])
// Unbonding for validator2 can complete
err = app.StakingKeeper.UnbondingCanComplete(ctx, ubdeIDs[1])
require.NoError(t, err)
assert.NilError(t, err)
// Try again to unbond validators
app.StakingKeeper.UnbondAllMatureValidators(ctx)
// Check that unbonding is complete for validator2
validator2, found = app.StakingKeeper.GetValidator(ctx, addrVals[1])
require.True(t, found)
require.Equal(t, types.Unbonded, validator2.Status)
assert.Assert(t, found)
assert.Equal(t, types.Unbonded, validator2.Status)
unbondingVals = app.StakingKeeper.GetUnbondingValidators(ctx, completionTime, completionHeight)
require.Equal(t, 0, len(unbondingVals))
assert.Equal(t, 0, len(unbondingVals))
}
func TestRedelegationOnHold1(t *testing.T) {
@ -300,20 +301,20 @@ func TestRedelegationOnHold1(t *testing.T) {
// CONSUMER CHAIN'S UNBONDING PERIOD ENDS - BUT UNBONDING CANNOT COMPLETE
err := app.StakingKeeper.UnbondingCanComplete(ctx, ubdeID)
require.NoError(t, err)
assert.NilError(t, err)
// Redelegation is not complete - still exists
redelegations := app.StakingKeeper.GetRedelegationsFromSrcValidator(ctx, addrVals[0])
require.Equal(t, 1, len(redelegations))
assert.Equal(t, 1, len(redelegations))
// PROVIDER CHAIN'S UNBONDING PERIOD ENDS - STOPPED UNBONDING CAN NOW COMPLETE
ctx = ctx.WithBlockTime(completionTime)
_, err = app.StakingKeeper.CompleteRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.NoError(t, err)
assert.NilError(t, err)
// Redelegation is complete and record is gone
redelegations = app.StakingKeeper.GetRedelegationsFromSrcValidator(ctx, addrVals[0])
require.Equal(t, 0, len(redelegations))
assert.Equal(t, 0, len(redelegations))
}
func TestRedelegationOnHold2(t *testing.T) {
@ -329,19 +330,19 @@ func TestRedelegationOnHold2(t *testing.T) {
// PROVIDER CHAIN'S UNBONDING PERIOD ENDS - BUT UNBONDING CANNOT COMPLETE
ctx = ctx.WithBlockTime(completionTime)
_, err := app.StakingKeeper.CompleteRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])
require.NoError(t, err)
assert.NilError(t, err)
// Redelegation is not complete - still exists
redelegations := app.StakingKeeper.GetRedelegationsFromSrcValidator(ctx, addrVals[0])
require.Equal(t, 1, len(redelegations))
assert.Equal(t, 1, len(redelegations))
// CONSUMER CHAIN'S UNBONDING PERIOD ENDS - STOPPED UNBONDING CAN NOW COMPLETE
err = app.StakingKeeper.UnbondingCanComplete(ctx, ubdeID)
require.NoError(t, err)
assert.NilError(t, err)
// Redelegation is complete and record is gone
redelegations = app.StakingKeeper.GetRedelegationsFromSrcValidator(ctx, addrVals[0])
require.Equal(t, 0, len(redelegations))
assert.Equal(t, 0, len(redelegations))
}
func TestUnbondingDelegationOnHold1(t *testing.T) {
@ -356,28 +357,28 @@ func TestUnbondingDelegationOnHold1(t *testing.T) {
// CONSUMER CHAIN'S UNBONDING PERIOD ENDS - BUT UNBONDING CANNOT COMPLETE
err := app.StakingKeeper.UnbondingCanComplete(ctx, ubdeID)
require.NoError(t, err)
assert.NilError(t, err)
bondedAmt3 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
notBondedAmt3 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
// Bonded and unbonded amounts are the same as before because the completionTime has not yet passed and so the
// unbondingDelegation has not completed
require.True(math.IntEq(t, bondedAmt1, bondedAmt3))
require.True(math.IntEq(t, notBondedAmt1, notBondedAmt3))
assert.Assert(math.IntEq(t, bondedAmt1, bondedAmt3))
assert.Assert(math.IntEq(t, notBondedAmt1, notBondedAmt3))
// PROVIDER CHAIN'S UNBONDING PERIOD ENDS - STOPPED UNBONDING CAN NOW COMPLETE
ctx = ctx.WithBlockTime(completionTime)
_, err = app.StakingKeeper.CompleteUnbonding(ctx, addrDels[0], addrVals[0])
require.NoError(t, err)
assert.NilError(t, err)
// Check that the unbonding was finally completed
bondedAmt5 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
notBondedAmt5 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, bondedAmt1, bondedAmt5))
assert.Assert(math.IntEq(t, bondedAmt1, bondedAmt5))
// Not bonded amount back to what it was originaly
require.True(math.IntEq(t, notBondedAmt1.SubRaw(1), notBondedAmt5))
assert.Assert(math.IntEq(t, notBondedAmt1.SubRaw(1), notBondedAmt5))
}
func TestUnbondingDelegationOnHold2(t *testing.T) {
@ -393,25 +394,25 @@ func TestUnbondingDelegationOnHold2(t *testing.T) {
// PROVIDER CHAIN'S UNBONDING PERIOD ENDS - BUT UNBONDING CANNOT COMPLETE
ctx = ctx.WithBlockTime(completionTime)
_, err := app.StakingKeeper.CompleteUnbonding(ctx, addrDels[0], addrVals[0])
require.NoError(t, err)
assert.NilError(t, err)
bondedAmt3 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
notBondedAmt3 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
// Bonded and unbonded amounts are the same as before because the completionTime has not yet passed and so the
// unbondingDelegation has not completed
require.True(math.IntEq(t, bondedAmt1, bondedAmt3))
require.True(math.IntEq(t, notBondedAmt1, notBondedAmt3))
assert.Assert(math.IntEq(t, bondedAmt1, bondedAmt3))
assert.Assert(math.IntEq(t, notBondedAmt1, notBondedAmt3))
// CONSUMER CHAIN'S UNBONDING PERIOD ENDS - STOPPED UNBONDING CAN NOW COMPLETE
err = app.StakingKeeper.UnbondingCanComplete(ctx, ubdeID)
require.NoError(t, err)
assert.NilError(t, err)
// Check that the unbonding was finally completed
bondedAmt5 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount
notBondedAmt5 := app.BankKeeper.GetBalance(ctx, app.StakingKeeper.GetNotBondedPool(ctx).GetAddress(), bondDenom).Amount
require.True(math.IntEq(t, bondedAmt1, bondedAmt5))
assert.Assert(math.IntEq(t, bondedAmt1, bondedAmt5))
// Not bonded amount back to what it was originaly
require.True(math.IntEq(t, notBondedAmt1.SubRaw(1), notBondedAmt5))
assert.Assert(math.IntEq(t, notBondedAmt1.SubRaw(1), notBondedAmt5))
}

View File

@ -5,11 +5,10 @@ import (
"testing"
"cosmossdk.io/math"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"cosmossdk.io/simapp"
abci "github.com/tendermint/tendermint/abci/types"
"gotest.tools/v3/assert"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -22,7 +21,7 @@ import (
func newMonikerValidator(t testing.TB, operator sdk.ValAddress, pubKey cryptotypes.PubKey, moniker string) types.Validator {
v, err := types.NewValidator(operator, pubKey, types.Description{Moniker: moniker})
require.NoError(t, err)
assert.NilError(t, err)
return v
}
@ -38,15 +37,15 @@ func bootstrapValidatorTest(t testing.TB, power int64, numAddrs int) (*simapp.Si
// set bonded pool supply
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), totalSupply))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), totalSupply))
// unbond genesis validator delegations
delegations := app.StakingKeeper.GetAllDelegations(ctx)
require.Len(t, delegations, 1)
assert.Assert(t, len(delegations) == 1)
delegation := delegations[0]
_, err := app.StakingKeeper.Undelegate(ctx, delegation.GetDelegatorAddr(), delegation.GetValidatorAddr(), delegation.Shares)
require.NoError(t, err)
assert.NilError(t, err)
// end block to unbond genesis validator
staking.EndBlocker(ctx, app.StakingKeeper)
@ -83,8 +82,8 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) {
app.StakingKeeper.SetParams(ctx, params)
// create a random pool
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), app.StakingKeeper.TokensFromConsensusPower(ctx, 1234)))))
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), app.StakingKeeper.TokensFromConsensusPower(ctx, 1234)))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), app.StakingKeeper.TokensFromConsensusPower(ctx, 10000)))))
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
@ -118,7 +117,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) {
for valIdx, status := range expectedValStatus {
valAddr := validators[valIdx].OperatorAddress
addr, err := sdk.ValAddressFromBech32(valAddr)
assert.NoError(t, err)
assert.NilError(t, err)
val, _ := app.StakingKeeper.GetValidator(ctx, addr)
assert.Equal(
@ -138,16 +137,16 @@ func TestSlashToZeroPowerRemoved(t *testing.T) {
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), valTokens))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), valTokens))))
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
validator, _ = validator.AddTokensFromDel(valTokens)
require.Equal(t, types.Unbonded, validator.Status)
require.Equal(t, valTokens, validator.Tokens)
assert.Equal(t, types.Unbonded, validator.Status)
assert.DeepEqual(t, valTokens, validator.Tokens)
app.StakingKeeper.SetValidatorByConsAddr(ctx, validator)
validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true)
require.Equal(t, valTokens, validator.Tokens, "\nvalidator %v\npool %v", validator, valTokens)
assert.DeepEqual(t, valTokens, validator.Tokens)
// slash the validator by 100%
app.StakingKeeper.Slash(ctx, sdk.ConsAddress(PKs[0].Address()), 0, 100, math.LegacyOneDec())
@ -155,7 +154,7 @@ func TestSlashToZeroPowerRemoved(t *testing.T) {
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)
// validator should be unbonding
validator, _ = app.StakingKeeper.GetValidator(ctx, addrVals[0])
require.Equal(t, validator.GetStatus(), types.Unbonding)
assert.Equal(t, validator.GetStatus(), types.Unbonding)
}
// test how the validators are sorted, tests GetBondedValidatorsByPower
@ -183,11 +182,11 @@ func TestGetValidatorSortingUnmixed(t *testing.T) {
// first make sure everything made it in to the gotValidator group
resValidators := app.StakingKeeper.GetBondedValidatorsByPower(ctx)
assert.Equal(t, n, len(resValidators))
assert.Equal(t, sdk.NewInt(400).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[0].BondedTokens(), "%v", resValidators)
assert.Equal(t, sdk.NewInt(200).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[1].BondedTokens(), "%v", resValidators)
assert.Equal(t, sdk.NewInt(100).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[2].BondedTokens(), "%v", resValidators)
assert.Equal(t, sdk.NewInt(1).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[3].BondedTokens(), "%v", resValidators)
assert.Equal(t, sdk.NewInt(0), resValidators[4].BondedTokens(), "%v", resValidators)
assert.DeepEqual(t, sdk.NewInt(400).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[0].BondedTokens())
assert.DeepEqual(t, sdk.NewInt(200).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[1].BondedTokens())
assert.DeepEqual(t, sdk.NewInt(100).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[2].BondedTokens())
assert.DeepEqual(t, sdk.NewInt(1).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[3].BondedTokens())
assert.DeepEqual(t, sdk.NewInt(0), resValidators[4].BondedTokens())
assert.Equal(t, validators[3].OperatorAddress, resValidators[0].OperatorAddress, "%v", resValidators)
assert.Equal(t, validators[4].OperatorAddress, resValidators[1].OperatorAddress, "%v", resValidators)
assert.Equal(t, validators[1].OperatorAddress, resValidators[2].OperatorAddress, "%v", resValidators)
@ -198,46 +197,46 @@ func TestGetValidatorSortingUnmixed(t *testing.T) {
validators[3].Tokens = sdk.NewInt(500).Mul(app.StakingKeeper.PowerReduction(ctx))
keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[3], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, len(resValidators), n)
assert.True(ValEq(t, validators[3], resValidators[0]))
assert.Equal(t, len(resValidators), n)
assert.Assert(ValEq(t, validators[3], resValidators[0]))
// test a decrease in voting power
validators[3].Tokens = sdk.NewInt(300).Mul(app.StakingKeeper.PowerReduction(ctx))
keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[3], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, len(resValidators), n)
assert.True(ValEq(t, validators[3], resValidators[0]))
assert.True(ValEq(t, validators[4], resValidators[1]))
assert.Equal(t, len(resValidators), n)
assert.Assert(ValEq(t, validators[3], resValidators[0]))
assert.Assert(ValEq(t, validators[4], resValidators[1]))
// test equal voting power, different age
validators[3].Tokens = sdk.NewInt(200).Mul(app.StakingKeeper.PowerReduction(ctx))
ctx = ctx.WithBlockHeight(10)
keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[3], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, len(resValidators), n)
assert.True(ValEq(t, validators[3], resValidators[0]))
assert.True(ValEq(t, validators[4], resValidators[1]))
assert.Equal(t, len(resValidators), n)
assert.Assert(ValEq(t, validators[3], resValidators[0]))
assert.Assert(ValEq(t, validators[4], resValidators[1]))
// no change in voting power - no change in sort
ctx = ctx.WithBlockHeight(20)
keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[4], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, len(resValidators), n)
assert.True(ValEq(t, validators[3], resValidators[0]))
assert.True(ValEq(t, validators[4], resValidators[1]))
assert.Equal(t, len(resValidators), n)
assert.Assert(ValEq(t, validators[3], resValidators[0]))
assert.Assert(ValEq(t, validators[4], resValidators[1]))
// change in voting power of both validators, both still in v-set, no age change
validators[3].Tokens = sdk.NewInt(300).Mul(app.StakingKeeper.PowerReduction(ctx))
validators[4].Tokens = sdk.NewInt(300).Mul(app.StakingKeeper.PowerReduction(ctx))
keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[3], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, len(resValidators), n)
assert.Equal(t, len(resValidators), n)
ctx = ctx.WithBlockHeight(30)
keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[4], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, len(resValidators), n, "%v", resValidators)
assert.True(ValEq(t, validators[3], resValidators[0]))
assert.True(ValEq(t, validators[4], resValidators[1]))
assert.Equal(t, len(resValidators), n, "%v", resValidators)
assert.Assert(ValEq(t, validators[3], resValidators[0]))
assert.Assert(ValEq(t, validators[4], resValidators[1]))
}
func TestGetValidatorSortingMixed(t *testing.T) {
@ -245,8 +244,8 @@ func TestGetValidatorSortingMixed(t *testing.T) {
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), app.StakingKeeper.TokensFromConsensusPower(ctx, 501)))))
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), app.StakingKeeper.TokensFromConsensusPower(ctx, 0)))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), app.StakingKeeper.TokensFromConsensusPower(ctx, 501)))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), app.StakingKeeper.TokensFromConsensusPower(ctx, 0)))))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
@ -275,27 +274,27 @@ func TestGetValidatorSortingMixed(t *testing.T) {
}
val0, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[0]))
require.True(t, found)
assert.Assert(t, found)
val1, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[1]))
require.True(t, found)
assert.Assert(t, found)
val2, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[2]))
require.True(t, found)
assert.Assert(t, found)
val3, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[3]))
require.True(t, found)
assert.Assert(t, found)
val4, found := app.StakingKeeper.GetValidator(ctx, sdk.ValAddress(addrs[4]))
require.True(t, found)
require.Equal(t, types.Bonded, val0.Status)
require.Equal(t, types.Unbonding, val1.Status)
require.Equal(t, types.Unbonding, val2.Status)
require.Equal(t, types.Bonded, val3.Status)
require.Equal(t, types.Bonded, val4.Status)
assert.Assert(t, found)
assert.Equal(t, types.Bonded, val0.Status)
assert.Equal(t, types.Unbonding, val1.Status)
assert.Equal(t, types.Unbonding, val2.Status)
assert.Equal(t, types.Bonded, val3.Status)
assert.Equal(t, types.Bonded, val4.Status)
// first make sure everything made it in to the gotValidator group
resValidators := app.StakingKeeper.GetBondedValidatorsByPower(ctx)
// The validators returned should match the max validators
assert.Equal(t, 2, len(resValidators))
assert.Equal(t, sdk.NewInt(400).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[0].BondedTokens(), "%v", resValidators)
assert.Equal(t, sdk.NewInt(200).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[1].BondedTokens(), "%v", resValidators)
assert.DeepEqual(t, sdk.NewInt(400).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[0].BondedTokens())
assert.DeepEqual(t, sdk.NewInt(200).Mul(app.StakingKeeper.PowerReduction(ctx)), resValidators[1].BondedTokens())
assert.Equal(t, validators[3].OperatorAddress, resValidators[0].OperatorAddress, "%v", resValidators)
assert.Equal(t, validators[4].OperatorAddress, resValidators[1].OperatorAddress, "%v", resValidators)
}
@ -321,16 +320,16 @@ func TestGetValidatorsEdgeCases(t *testing.T) {
validators[i], _ = validators[i].AddTokensFromDel(tokens)
notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, tokens))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, tokens))))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
validators[i] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[i], true)
}
// ensure that the first two bonded validators are the largest validators
resValidators := app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, nMax, uint32(len(resValidators)))
assert.True(ValEq(t, validators[2], resValidators[0]))
assert.True(ValEq(t, validators[3], resValidators[1]))
assert.Equal(t, nMax, uint32(len(resValidators)))
assert.Assert(ValEq(t, validators[2], resValidators[0]))
assert.Assert(ValEq(t, validators[3], resValidators[1]))
// delegate 500 tokens to validator 0
app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, validators[0])
@ -340,7 +339,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) {
newTokens := sdk.NewCoins()
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), newTokens))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), newTokens))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
// test that the two largest validators are
@ -348,9 +347,9 @@ func TestGetValidatorsEdgeCases(t *testing.T) {
// b) validator 2 with 400 tokens (delegated before validator 3)
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, nMax, uint32(len(resValidators)))
assert.True(ValEq(t, validators[0], resValidators[0]))
assert.True(ValEq(t, validators[2], resValidators[1]))
assert.Equal(t, nMax, uint32(len(resValidators)))
assert.Assert(ValEq(t, validators[0], resValidators[0]))
assert.Assert(ValEq(t, validators[2], resValidators[1]))
// A validator which leaves the bonded validator set due to a decrease in voting power,
// then increases to the original voting power, does not get its spot back in the
@ -366,20 +365,20 @@ func TestGetValidatorsEdgeCases(t *testing.T) {
var found bool
validators[3], found = app.StakingKeeper.GetValidator(ctx, validators[3].GetOperator())
assert.True(t, found)
assert.Assert(t, found)
app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, validators[3])
validators[3], _ = validators[3].AddTokensFromDel(app.StakingKeeper.TokensFromConsensusPower(ctx, 1))
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
newTokens = sdk.NewCoins(sdk.NewCoin(params.BondDenom, app.StakingKeeper.TokensFromConsensusPower(ctx, 1)))
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), newTokens))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), newTokens))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
validators[3] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[3], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, nMax, uint32(len(resValidators)))
assert.True(ValEq(t, validators[0], resValidators[0]))
assert.True(ValEq(t, validators[3], resValidators[1]))
assert.Equal(t, nMax, uint32(len(resValidators)))
assert.Assert(ValEq(t, validators[0], resValidators[0]))
assert.Assert(ValEq(t, validators[3], resValidators[1]))
// validator 3 kicked out temporarily
app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, validators[3])
@ -387,30 +386,30 @@ func TestGetValidatorsEdgeCases(t *testing.T) {
validators[3], _ = validators[3].RemoveDelShares(math.LegacyNewDec(201))
bondedPool := app.StakingKeeper.GetBondedPool(ctx)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, rmTokens))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, rmTokens))))
app.AccountKeeper.SetModuleAccount(ctx, bondedPool)
validators[3] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[3], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, nMax, uint32(len(resValidators)))
assert.True(ValEq(t, validators[0], resValidators[0]))
assert.True(ValEq(t, validators[2], resValidators[1]))
assert.Equal(t, nMax, uint32(len(resValidators)))
assert.Assert(ValEq(t, validators[0], resValidators[0]))
assert.Assert(ValEq(t, validators[2], resValidators[1]))
// validator 3 does not get spot back
app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, validators[3])
validators[3], _ = validators[3].AddTokensFromDel(sdk.NewInt(200))
notBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)
require.NoError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, sdk.NewInt(200)))))
assert.NilError(t, banktestutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), sdk.NewCoins(sdk.NewCoin(params.BondDenom, sdk.NewInt(200)))))
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
validators[3] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[3], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, nMax, uint32(len(resValidators)))
assert.True(ValEq(t, validators[0], resValidators[0]))
assert.True(ValEq(t, validators[2], resValidators[1]))
assert.Equal(t, nMax, uint32(len(resValidators)))
assert.Assert(ValEq(t, validators[0], resValidators[0]))
assert.Assert(ValEq(t, validators[2], resValidators[1]))
_, exists := app.StakingKeeper.GetValidator(ctx, validators[3].GetOperator())
require.True(t, exists)
assert.Assert(t, exists)
}
func TestValidatorBondHeight(t *testing.T) {
@ -443,10 +442,10 @@ func TestValidatorBondHeight(t *testing.T) {
validators[2] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[2], true)
resValidators := app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, uint32(len(resValidators)), params.MaxValidators)
assert.Equal(t, uint32(len(resValidators)), params.MaxValidators)
assert.True(ValEq(t, validators[0], resValidators[0]))
assert.True(ValEq(t, validators[1], resValidators[1]))
assert.Assert(ValEq(t, validators[0], resValidators[0]))
assert.Assert(ValEq(t, validators[1], resValidators[1]))
app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, validators[1])
app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, validators[2])
delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 50)
@ -454,10 +453,10 @@ func TestValidatorBondHeight(t *testing.T) {
validators[2], _ = validators[2].AddTokensFromDel(delTokens)
validators[2] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[2], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
require.Equal(t, params.MaxValidators, uint32(len(resValidators)))
assert.Equal(t, params.MaxValidators, uint32(len(resValidators)))
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], true)
assert.True(ValEq(t, validators[0], resValidators[0]))
assert.True(ValEq(t, validators[2], resValidators[1]))
assert.Assert(ValEq(t, validators[0], resValidators[0]))
assert.Assert(ValEq(t, validators[2], resValidators[1]))
}
func TestFullValidatorSetPowerChange(t *testing.T) {
@ -479,7 +478,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) {
for i := range powers {
var found bool
validators[i], found = app.StakingKeeper.GetValidator(ctx, validators[i].GetOperator())
require.True(t, found)
assert.Assert(t, found)
}
assert.Equal(t, types.Unbonded, validators[0].Status)
assert.Equal(t, types.Unbonding, validators[1].Status)
@ -488,8 +487,8 @@ func TestFullValidatorSetPowerChange(t *testing.T) {
assert.Equal(t, types.Unbonded, validators[4].Status)
resValidators := app.StakingKeeper.GetBondedValidatorsByPower(ctx)
assert.Equal(t, max, len(resValidators))
assert.True(ValEq(t, validators[2], resValidators[0])) // in the order of txs
assert.True(ValEq(t, validators[3], resValidators[1]))
assert.Assert(ValEq(t, validators[2], resValidators[0])) // in the order of txs
assert.Assert(ValEq(t, validators[3], resValidators[1]))
// test a swap in voting power
@ -498,8 +497,8 @@ func TestFullValidatorSetPowerChange(t *testing.T) {
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], true)
resValidators = app.StakingKeeper.GetBondedValidatorsByPower(ctx)
assert.Equal(t, max, len(resValidators))
assert.True(ValEq(t, validators[0], resValidators[0]))
assert.True(ValEq(t, validators[2], resValidators[1]))
assert.Assert(ValEq(t, validators[0], resValidators[0]))
assert.Assert(ValEq(t, validators[2], resValidators[1]))
}
func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) {
@ -527,8 +526,8 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) {
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
validators[0], _ = app.StakingKeeper.GetValidator(ctx, validators[0].GetOperator())
validators[1], _ = app.StakingKeeper.GetValidator(ctx, validators[1].GetOperator())
assert.Equal(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
assert.Equal(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
}
func TestApplyAndReturnValidatorSetUpdatesIdentical(t *testing.T) {
@ -577,7 +576,7 @@ func TestApplyAndReturnValidatorSetUpdatesSingleValueChange(t *testing.T) {
validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], false)
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
require.Equal(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
}
func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) {
@ -599,8 +598,8 @@ func TestApplyAndReturnValidatorSetUpdatesMultipleValueChange(t *testing.T) {
validators[1] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[1], false)
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
require.Equal(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
require.Equal(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
}
func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) {
@ -617,7 +616,7 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) {
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[2])
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validators[2], _ = app.StakingKeeper.GetValidator(ctx, validators[2].GetOperator())
require.Equal(t, validators[2].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[2].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
// test validtor added at the beginning
// tendermintUpdate set: {} -> {c0}
@ -625,7 +624,7 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) {
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[3])
updates = applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validators[3], _ = app.StakingKeeper.GetValidator(ctx, validators[3].GetOperator())
require.Equal(t, validators[3].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[3].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
// test validtor added at the end
// tendermintUpdate set: {} -> {c0}
@ -633,7 +632,7 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) {
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[4])
updates = applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
validators[4], _ = app.StakingKeeper.GetValidator(ctx, validators[4].GetOperator())
require.Equal(t, validators[4].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[4].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
}
func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) {
@ -668,8 +667,8 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) {
app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[2])
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
validators[2], _ = app.StakingKeeper.GetValidator(ctx, validators[2].GetOperator())
require.Equal(t, validators[0].ABCIValidatorUpdateZero(), updates[1])
require.Equal(t, validators[2].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[0].ABCIValidatorUpdateZero(), updates[1])
assert.DeepEqual(t, validators[2].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
}
func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
@ -699,8 +698,8 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, len(validators))
validators[0], _ = app.StakingKeeper.GetValidator(ctx, validators[0].GetOperator())
validators[1], _ = app.StakingKeeper.GetValidator(ctx, validators[1].GetOperator())
require.Equal(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
require.Equal(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
@ -745,9 +744,9 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) {
validator, _ = app.StakingKeeper.GetValidator(ctx, validator.GetOperator())
validators[0], _ = app.StakingKeeper.GetValidator(ctx, validators[0].GetOperator())
validators[1], _ = app.StakingKeeper.GetValidator(ctx, validators[1].GetOperator())
require.Equal(t, validator.ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
require.Equal(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
require.Equal(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[2])
assert.DeepEqual(t, validator.ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[0].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[2])
}
func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
@ -777,8 +776,8 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
updates := applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 2)
validators[2], _ = app.StakingKeeper.GetValidator(ctx, validators[2].GetOperator())
validators[1], _ = app.StakingKeeper.GetValidator(ctx, validators[1].GetOperator())
require.Equal(t, validators[2].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
require.Equal(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
assert.DeepEqual(t, validators[2].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[1])
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
@ -787,7 +786,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
var found bool
validators[0], found = app.StakingKeeper.GetValidator(ctx, validators[0].GetOperator())
require.True(t, found)
assert.Assert(t, found)
app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, validators[0])
tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 1)
@ -803,7 +802,7 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
ctx = ctx.WithBlockHeight(2)
validators[1], found = app.StakingKeeper.GetValidator(ctx, validators[1].GetOperator())
require.True(t, found)
assert.Assert(t, found)
app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, validators[0])
validators[0], _ = validators[0].RemoveDelShares(validators[0].DelegatorShares)
@ -819,16 +818,16 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) {
// verify initial Tendermint updates are correct
updates = applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)
require.Equal(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
assert.DeepEqual(t, validators[1].ABCIValidatorUpdate(app.StakingKeeper.PowerReduction(ctx)), updates[0])
applyValidatorSetUpdates(t, ctx, app.StakingKeeper, 0)
}
func applyValidatorSetUpdates(t *testing.T, ctx sdk.Context, k *keeper.Keeper, expectedUpdatesLen int) []abci.ValidatorUpdate {
updates, err := k.ApplyAndReturnValidatorSetUpdates(ctx)
require.NoError(t, err)
assert.NilError(t, err)
if expectedUpdatesLen >= 0 {
require.Equal(t, expectedUpdatesLen, len(updates), "%v", updates)
assert.Equal(t, expectedUpdatesLen, len(updates), "%v", updates)
}
return updates
}

25
testutil/assertHelpers.go Normal file
View File

@ -0,0 +1,25 @@
package testutil
import "testing"
func AssertPanics(t *testing.T, f func()) {
panicked := false
defer func() {
if r := recover(); r != nil {
panicked = true
}
}()
f()
if !panicked {
t.Errorf("should panic")
}
}
func AssertNotPanics(t *testing.T, f func()) {
defer func() {
if r := recover(); r != nil {
t.Errorf("should not panic: %v", r)
}
}()
f()
}