Best Go-testdeep code snippet using json.getOperator
querier_test.go
Source:querier_test.go
1package keeper_test2import (3 "fmt"4 "testing"5 "github.com/stretchr/testify/require"6 abci "github.com/tendermint/tendermint/abci/types"7 tmproto "github.com/tendermint/tendermint/proto/tendermint/types"8 "github.com/cosmos/cosmos-sdk/codec"9 "github.com/cosmos/cosmos-sdk/simapp"10 sdk "github.com/cosmos/cosmos-sdk/types"11 "github.com/cosmos/cosmos-sdk/x/staking/keeper"12 "github.com/cosmos/cosmos-sdk/x/staking/teststaking"13 "github.com/cosmos/cosmos-sdk/x/staking/types"14)15func TestNewQuerier(t *testing.T) {16 cdc, app, ctx := createTestInput()17 addrs := simapp.AddTestAddrs(app, ctx, 500, sdk.NewInt(10000))18 _, addrAcc2 := addrs[0], addrs[1]19 addrVal1, _ := sdk.ValAddress(addrs[0]), sdk.ValAddress(addrs[1])20 // Create Validators21 amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8)}22 var validators [2]types.Validator23 for i, amt := range amts {24 validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])25 validators[i], _ = validators[i].AddTokensFromDel(amt)26 app.StakingKeeper.SetValidator(ctx, validators[i])27 app.StakingKeeper.SetValidatorByPowerIndex(ctx, validators[i])28 }29 header := tmproto.Header{30 ChainID: "HelloChain",31 Height: 5,32 }33 hi := types.NewHistoricalInfo(header, validators[:])34 app.StakingKeeper.SetHistoricalInfo(ctx, 5, &hi)35 query := abci.RequestQuery{36 Path: "",37 Data: []byte{},38 }39 legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino())40 querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)41 bz, err := querier(ctx, []string{"other"}, query)42 require.Error(t, err)43 require.Nil(t, bz)44 _, err = querier(ctx, []string{"pool"}, query)45 require.NoError(t, err)46 _, err = querier(ctx, []string{"parameters"}, query)47 require.NoError(t, err)48 queryValParams := types.NewQueryValidatorParams(addrVal1, 0, 0)49 bz, errRes := cdc.MarshalJSON(queryValParams)50 require.NoError(t, errRes)51 query.Path = "/custom/staking/validator"52 query.Data = bz53 _, err = querier(ctx, []string{"validator"}, query)54 require.NoError(t, err)55 _, err = querier(ctx, []string{"validatorDelegations"}, query)56 require.NoError(t, err)57 _, err = querier(ctx, []string{"validatorUnbondingDelegations"}, query)58 require.NoError(t, err)59 queryDelParams := types.NewQueryDelegatorParams(addrAcc2)60 bz, errRes = cdc.MarshalJSON(queryDelParams)61 require.NoError(t, errRes)62 query.Path = "/custom/staking/validator"63 query.Data = bz64 _, err = querier(ctx, []string{"delegatorDelegations"}, query)65 require.NoError(t, err)66 _, err = querier(ctx, []string{"delegatorUnbondingDelegations"}, query)67 require.NoError(t, err)68 _, err = querier(ctx, []string{"delegatorValidators"}, query)69 require.NoError(t, err)70 bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(nil, nil, nil))71 require.NoError(t, errRes)72 query.Data = bz73 _, err = querier(ctx, []string{"redelegations"}, query)74 require.NoError(t, err)75 queryHisParams := types.QueryHistoricalInfoRequest{Height: 5}76 bz, errRes = cdc.MarshalJSON(queryHisParams)77 require.NoError(t, errRes)78 query.Path = "/custom/staking/historicalInfo"79 query.Data = bz80 _, err = querier(ctx, []string{"historicalInfo"}, query)81 require.NoError(t, err)82}83func TestQueryParametersPool(t *testing.T) {84 cdc, app, ctx := createTestInput()85 legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino())86 querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)87 bondDenom := sdk.DefaultBondDenom88 res, err := querier(ctx, []string{types.QueryParameters}, abci.RequestQuery{})89 require.NoError(t, err)90 var params types.Params91 errRes := cdc.UnmarshalJSON(res, ¶ms)92 require.NoError(t, errRes)93 require.Equal(t, app.StakingKeeper.GetParams(ctx), params)94 res, err = querier(ctx, []string{types.QueryPool}, abci.RequestQuery{})95 require.NoError(t, err)96 var pool types.Pool97 bondedPool := app.StakingKeeper.GetBondedPool(ctx)98 notBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)99 require.NoError(t, cdc.UnmarshalJSON(res, &pool))100 require.Equal(t, app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount, pool.NotBondedTokens)101 require.Equal(t, app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount, pool.BondedTokens)102}103func TestQueryValidators(t *testing.T) {104 cdc, app, ctx := createTestInput()105 params := app.StakingKeeper.GetParams(ctx)106 legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino())107 querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)108 addrs := simapp.AddTestAddrs(app, ctx, 500, sdk.TokensFromConsensusPower(10000))109 // Create Validators110 amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8), sdk.NewInt(7)}111 status := []types.BondStatus{types.Bonded, types.Unbonded, types.Unbonding}112 var validators [3]types.Validator113 for i, amt := range amts {114 validators[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), PKs[i])115 validators[i], _ = validators[i].AddTokensFromDel(amt)116 validators[i] = validators[i].UpdateStatus(status[i])117 }118 app.StakingKeeper.SetValidator(ctx, validators[0])119 app.StakingKeeper.SetValidator(ctx, validators[1])120 app.StakingKeeper.SetValidator(ctx, validators[2])121 // Query Validators122 queriedValidators := app.StakingKeeper.GetValidators(ctx, params.MaxValidators)123 require.Len(t, queriedValidators, 3)124 for i, s := range status {125 queryValsParams := types.NewQueryValidatorsParams(1, int(params.MaxValidators), s.String())126 bz, err := cdc.MarshalJSON(queryValsParams)127 require.NoError(t, err)128 req := abci.RequestQuery{129 Path: fmt.Sprintf("/custom/%s/%s", types.QuerierRoute, types.QueryValidators),130 Data: bz,131 }132 res, err := querier(ctx, []string{types.QueryValidators}, req)133 require.NoError(t, err)134 var validatorsResp []types.Validator135 err = cdc.UnmarshalJSON(res, &validatorsResp)136 require.NoError(t, err)137 require.Equal(t, 1, len(validatorsResp))138 require.Equal(t, validators[i].OperatorAddress, validatorsResp[0].OperatorAddress)139 }140 // Query each validator141 for _, validator := range validators {142 queryParams := types.NewQueryValidatorParams(validator.GetOperator(), 0, 0)143 bz, err := cdc.MarshalJSON(queryParams)144 require.NoError(t, err)145 query := abci.RequestQuery{146 Path: "/custom/staking/validator",147 Data: bz,148 }149 res, err := querier(ctx, []string{types.QueryValidator}, query)150 require.NoError(t, err)151 var queriedValidator types.Validator152 err = cdc.UnmarshalJSON(res, &queriedValidator)153 require.NoError(t, err)154 require.True(t, validator.Equal(&queriedValidator))155 }156}157func TestQueryDelegation(t *testing.T) {158 cdc, app, ctx := createTestInput()159 params := app.StakingKeeper.GetParams(ctx)160 legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino())161 querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)162 addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000))163 addrAcc1, addrAcc2 := addrs[0], addrs[1]164 addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2)165 pubKeys := simapp.CreateTestPubKeys(2)166 pk1, pk2 := pubKeys[0], pubKeys[1]167 // Create Validators and Delegation168 val1 := teststaking.NewValidator(t, addrVal1, pk1)169 app.StakingKeeper.SetValidator(ctx, val1)170 app.StakingKeeper.SetValidatorByPowerIndex(ctx, val1)171 val2 := teststaking.NewValidator(t, addrVal2, pk2)172 app.StakingKeeper.SetValidator(ctx, val2)173 app.StakingKeeper.SetValidatorByPowerIndex(ctx, val2)174 delTokens := sdk.TokensFromConsensusPower(20)175 _, err := app.StakingKeeper.Delegate(ctx, addrAcc2, delTokens, types.Unbonded, val1, true)176 require.NoError(t, err)177 // apply TM updates178 applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)179 // Query Delegator bonded validators180 queryParams := types.NewQueryDelegatorParams(addrAcc2)181 bz, errRes := cdc.MarshalJSON(queryParams)182 require.NoError(t, errRes)183 query := abci.RequestQuery{184 Path: "/custom/staking/delegatorValidators",185 Data: bz,186 }187 delValidators := app.StakingKeeper.GetDelegatorValidators(ctx, addrAcc2, params.MaxValidators)188 res, err := querier(ctx, []string{types.QueryDelegatorValidators}, query)189 require.NoError(t, err)190 var validatorsResp types.Validators191 errRes = cdc.UnmarshalJSON(res, &validatorsResp)192 require.NoError(t, errRes)193 require.Equal(t, len(delValidators), len(validatorsResp))194 require.ElementsMatch(t, delValidators, validatorsResp)195 // error unknown request196 query.Data = bz[:len(bz)-1]197 _, err = querier(ctx, []string{types.QueryDelegatorValidators}, query)198 require.Error(t, err)199 // Query bonded validator200 queryBondParams := types.QueryDelegatorValidatorRequest{DelegatorAddr: addrAcc2.String(), ValidatorAddr: addrVal1.String()}201 bz, errRes = cdc.MarshalJSON(queryBondParams)202 require.NoError(t, errRes)203 query = abci.RequestQuery{204 Path: "/custom/staking/delegatorValidator",205 Data: bz,206 }207 res, err = querier(ctx, []string{types.QueryDelegatorValidator}, query)208 require.NoError(t, err)209 var validator types.Validator210 errRes = cdc.UnmarshalJSON(res, &validator)211 require.NoError(t, errRes)212 require.True(t, validator.Equal(&delValidators[0]))213 // error unknown request214 query.Data = bz[:len(bz)-1]215 _, err = querier(ctx, []string{types.QueryDelegatorValidator}, query)216 require.Error(t, err)217 // Query delegation218 query = abci.RequestQuery{219 Path: "/custom/staking/delegation",220 Data: bz,221 }222 delegation, found := app.StakingKeeper.GetDelegation(ctx, addrAcc2, addrVal1)223 require.True(t, found)224 res, err = querier(ctx, []string{types.QueryDelegation}, query)225 require.NoError(t, err)226 var delegationRes types.DelegationResponse227 errRes = cdc.UnmarshalJSON(res, &delegationRes)228 require.NoError(t, errRes)229 require.Equal(t, delegation.ValidatorAddress, delegationRes.Delegation.ValidatorAddress)230 require.Equal(t, delegation.DelegatorAddress, delegationRes.Delegation.DelegatorAddress)231 require.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), delegationRes.Balance)232 // Query Delegator Delegations233 query = abci.RequestQuery{234 Path: "/custom/staking/delegatorDelegations",235 Data: bz,236 }237 res, err = querier(ctx, []string{types.QueryDelegatorDelegations}, query)238 require.NoError(t, err)239 var delegatorDelegations types.DelegationResponses240 errRes = cdc.UnmarshalJSON(res, &delegatorDelegations)241 require.NoError(t, errRes)242 require.Len(t, delegatorDelegations, 1)243 require.Equal(t, delegation.ValidatorAddress, delegatorDelegations[0].Delegation.ValidatorAddress)244 require.Equal(t, delegation.DelegatorAddress, delegatorDelegations[0].Delegation.DelegatorAddress)245 require.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), delegatorDelegations[0].Balance)246 // error unknown request247 query.Data = bz[:len(bz)-1]248 _, err = querier(ctx, []string{types.QueryDelegation}, query)249 require.Error(t, err)250 // Query validator delegations251 bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(addrVal1, 1, 100))252 require.NoError(t, errRes)253 query = abci.RequestQuery{254 Path: "custom/staking/validatorDelegations",255 Data: bz,256 }257 res, err = querier(ctx, []string{types.QueryValidatorDelegations}, query)258 require.NoError(t, err)259 var delegationsRes types.DelegationResponses260 errRes = cdc.UnmarshalJSON(res, &delegationsRes)261 require.NoError(t, errRes)262 require.Len(t, delegatorDelegations, 1)263 require.Equal(t, delegation.ValidatorAddress, delegationsRes[0].Delegation.ValidatorAddress)264 require.Equal(t, delegation.DelegatorAddress, delegationsRes[0].Delegation.DelegatorAddress)265 require.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, delegation.Shares.TruncateInt()), delegationsRes[0].Balance)266 // Query unbonding delegation267 unbondingTokens := sdk.TokensFromConsensusPower(10)268 _, err = app.StakingKeeper.Undelegate(ctx, addrAcc2, val1.GetOperator(), unbondingTokens.ToDec())269 require.NoError(t, err)270 queryBondParams = types.QueryDelegatorValidatorRequest{DelegatorAddr: addrAcc2.String(), ValidatorAddr: addrVal1.String()}271 bz, errRes = cdc.MarshalJSON(queryBondParams)272 require.NoError(t, errRes)273 query = abci.RequestQuery{274 Path: "/custom/staking/unbondingDelegation",275 Data: bz,276 }277 unbond, found := app.StakingKeeper.GetUnbondingDelegation(ctx, addrAcc2, addrVal1)278 require.True(t, found)279 res, err = querier(ctx, []string{types.QueryUnbondingDelegation}, query)280 require.NoError(t, err)281 var unbondRes types.UnbondingDelegation282 errRes = cdc.UnmarshalJSON(res, &unbondRes)283 require.NoError(t, errRes)284 require.Equal(t, unbond, unbondRes)285 // error unknown request286 query.Data = bz[:len(bz)-1]287 _, err = querier(ctx, []string{types.QueryUnbondingDelegation}, query)288 require.Error(t, err)289 // Query Delegator Unbonding Delegations290 query = abci.RequestQuery{291 Path: "/custom/staking/delegatorUnbondingDelegations",292 Data: bz,293 }294 res, err = querier(ctx, []string{types.QueryDelegatorUnbondingDelegations}, query)295 require.NoError(t, err)296 var delegatorUbds []types.UnbondingDelegation297 errRes = cdc.UnmarshalJSON(res, &delegatorUbds)298 require.NoError(t, errRes)299 require.Equal(t, unbond, delegatorUbds[0])300 // error unknown request301 query.Data = bz[:len(bz)-1]302 _, err = querier(ctx, []string{types.QueryDelegatorUnbondingDelegations}, query)303 require.Error(t, err)304 // Query redelegation305 redelegationTokens := sdk.TokensFromConsensusPower(10)306 _, err = app.StakingKeeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(),307 val2.GetOperator(), redelegationTokens.ToDec())308 require.NoError(t, err)309 redel, found := app.StakingKeeper.GetRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator())310 require.True(t, found)311 bz, errRes = cdc.MarshalJSON(types.NewQueryRedelegationParams(addrAcc2, val1.GetOperator(), val2.GetOperator()))312 require.NoError(t, errRes)313 query = abci.RequestQuery{314 Path: "/custom/staking/redelegations",315 Data: bz,316 }317 res, err = querier(ctx, []string{types.QueryRedelegations}, query)318 require.NoError(t, err)319 var redelRes types.RedelegationResponses320 errRes = cdc.UnmarshalJSON(res, &redelRes)321 require.NoError(t, errRes)322 require.Len(t, redelRes, 1)323 require.Equal(t, redel.DelegatorAddress, redelRes[0].Redelegation.DelegatorAddress)324 require.Equal(t, redel.ValidatorSrcAddress, redelRes[0].Redelegation.ValidatorSrcAddress)325 require.Equal(t, redel.ValidatorDstAddress, redelRes[0].Redelegation.ValidatorDstAddress)326 require.Len(t, redel.Entries, len(redelRes[0].Entries))327}328func TestQueryValidatorDelegations_Pagination(t *testing.T) {329 cases := []struct {330 page int331 limit int332 expectedResults int333 }{334 {335 page: 1,336 limit: 75,337 expectedResults: 75,338 },339 {340 page: 2,341 limit: 75,342 expectedResults: 25,343 },344 {345 page: 1,346 limit: 100,347 expectedResults: 100,348 },349 }350 cdc, app, ctx := createTestInput()351 legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino())352 querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)353 addrs := simapp.AddTestAddrs(app, ctx, 100, sdk.TokensFromConsensusPower(10000))354 pubKeys := simapp.CreateTestPubKeys(1)355 valAddress := sdk.ValAddress(addrs[0])356 val1 := teststaking.NewValidator(t, valAddress, pubKeys[0])357 app.StakingKeeper.SetValidator(ctx, val1)358 app.StakingKeeper.SetValidatorByPowerIndex(ctx, val1)359 // Create Validators and Delegation360 for _, addr := range addrs {361 validator, found := app.StakingKeeper.GetValidator(ctx, valAddress)362 if !found {363 t.Error("expected validator not found")364 }365 delTokens := sdk.TokensFromConsensusPower(20)366 _, err := app.StakingKeeper.Delegate(ctx, addr, delTokens, types.Unbonded, validator, true)367 require.NoError(t, err)368 }369 // apply TM updates370 applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)371 for _, c := range cases {372 // Query Delegator bonded validators373 queryParams := types.NewQueryDelegatorParams(addrs[0])374 bz, errRes := cdc.MarshalJSON(queryParams)375 require.NoError(t, errRes)376 // Query valAddress delegations377 bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(valAddress, c.page, c.limit))378 require.NoError(t, errRes)379 query := abci.RequestQuery{380 Path: "custom/staking/validatorDelegations",381 Data: bz,382 }383 res, err := querier(ctx, []string{types.QueryValidatorDelegations}, query)384 require.NoError(t, err)385 var delegationsRes types.DelegationResponses386 errRes = cdc.UnmarshalJSON(res, &delegationsRes)387 require.NoError(t, errRes)388 require.Len(t, delegationsRes, c.expectedResults)389 }390 // Undelegate391 for _, addr := range addrs {392 delTokens := sdk.TokensFromConsensusPower(20)393 _, err := app.StakingKeeper.Undelegate(ctx, addr, val1.GetOperator(), delTokens.ToDec())394 require.NoError(t, err)395 }396 // apply TM updates397 applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)398 for _, c := range cases {399 // Query Unbonding delegations with pagination.400 queryParams := types.NewQueryDelegatorParams(addrs[0])401 bz, errRes := cdc.MarshalJSON(queryParams)402 require.NoError(t, errRes)403 bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(valAddress, c.page, c.limit))404 require.NoError(t, errRes)405 query := abci.RequestQuery{406 Data: bz,407 }408 unbondingDelegations := types.UnbondingDelegations{}409 res, err := querier(ctx, []string{types.QueryValidatorUnbondingDelegations}, query)410 require.NoError(t, err)411 errRes = cdc.UnmarshalJSON(res, &unbondingDelegations)412 require.NoError(t, errRes)413 require.Len(t, unbondingDelegations, c.expectedResults)414 }415}416func TestQueryRedelegations(t *testing.T) {417 cdc, app, ctx := createTestInput()418 legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino())419 querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)420 addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000))421 addrAcc1, addrAcc2 := addrs[0], addrs[1]422 addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2)423 // Create Validators and Delegation424 val1 := teststaking.NewValidator(t, addrVal1, PKs[0])425 val2 := teststaking.NewValidator(t, addrVal2, PKs[1])426 app.StakingKeeper.SetValidator(ctx, val1)427 app.StakingKeeper.SetValidator(ctx, val2)428 delAmount := sdk.TokensFromConsensusPower(100)429 _, err := app.StakingKeeper.Delegate(ctx, addrAcc2, delAmount, types.Unbonded, val1, true)430 require.NoError(t, err)431 applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)432 rdAmount := sdk.TokensFromConsensusPower(20)433 _, err = app.StakingKeeper.BeginRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator(), rdAmount.ToDec())434 require.NoError(t, err)435 applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)436 redel, found := app.StakingKeeper.GetRedelegation(ctx, addrAcc2, val1.GetOperator(), val2.GetOperator())437 require.True(t, found)438 // delegator redelegations439 queryDelegatorParams := types.NewQueryDelegatorParams(addrAcc2)440 bz, errRes := cdc.MarshalJSON(queryDelegatorParams)441 require.NoError(t, errRes)442 query := abci.RequestQuery{443 Path: "/custom/staking/redelegations",444 Data: bz,445 }446 res, err := querier(ctx, []string{types.QueryRedelegations}, query)447 require.NoError(t, err)448 var redelRes types.RedelegationResponses449 errRes = cdc.UnmarshalJSON(res, &redelRes)450 require.NoError(t, errRes)451 require.Len(t, redelRes, 1)452 require.Equal(t, redel.DelegatorAddress, redelRes[0].Redelegation.DelegatorAddress)453 require.Equal(t, redel.ValidatorSrcAddress, redelRes[0].Redelegation.ValidatorSrcAddress)454 require.Equal(t, redel.ValidatorDstAddress, redelRes[0].Redelegation.ValidatorDstAddress)455 require.Len(t, redel.Entries, len(redelRes[0].Entries))456 // validator redelegations457 queryValidatorParams := types.NewQueryValidatorParams(val1.GetOperator(), 0, 0)458 bz, errRes = cdc.MarshalJSON(queryValidatorParams)459 require.NoError(t, errRes)460 query = abci.RequestQuery{461 Path: "/custom/staking/redelegations",462 Data: bz,463 }464 res, err = querier(ctx, []string{types.QueryRedelegations}, query)465 require.NoError(t, err)466 errRes = cdc.UnmarshalJSON(res, &redelRes)467 require.NoError(t, errRes)468 require.Len(t, redelRes, 1)469 require.Equal(t, redel.DelegatorAddress, redelRes[0].Redelegation.DelegatorAddress)470 require.Equal(t, redel.ValidatorSrcAddress, redelRes[0].Redelegation.ValidatorSrcAddress)471 require.Equal(t, redel.ValidatorDstAddress, redelRes[0].Redelegation.ValidatorDstAddress)472 require.Len(t, redel.Entries, len(redelRes[0].Entries))473}474func TestQueryUnbondingDelegation(t *testing.T) {475 cdc, app, ctx := createTestInput()476 legacyQuerierCdc := codec.NewAminoCodec(app.LegacyAmino())477 querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)478 addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000))479 addrAcc1, addrAcc2 := addrs[0], addrs[1]480 addrVal1 := sdk.ValAddress(addrAcc1)481 // Create Validators and Delegation482 val1 := teststaking.NewValidator(t, addrVal1, PKs[0])483 app.StakingKeeper.SetValidator(ctx, val1)484 // delegate485 delAmount := sdk.TokensFromConsensusPower(100)486 _, err := app.StakingKeeper.Delegate(ctx, addrAcc1, delAmount, types.Unbonded, val1, true)487 require.NoError(t, err)488 applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)489 // undelegate490 undelAmount := sdk.TokensFromConsensusPower(20)491 _, err = app.StakingKeeper.Undelegate(ctx, addrAcc1, val1.GetOperator(), undelAmount.ToDec())492 require.NoError(t, err)493 applyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)494 _, found := app.StakingKeeper.GetUnbondingDelegation(ctx, addrAcc1, val1.GetOperator())495 require.True(t, found)496 //497 // found: query unbonding delegation by delegator and validator498 //499 queryValidatorParams := types.QueryDelegatorValidatorRequest{DelegatorAddr: addrAcc1.String(), ValidatorAddr: val1.GetOperator().String()}500 bz, errRes := cdc.MarshalJSON(queryValidatorParams)501 require.NoError(t, errRes)502 query := abci.RequestQuery{503 Path: "/custom/staking/unbondingDelegation",504 Data: bz,505 }506 res, err := querier(ctx, []string{types.QueryUnbondingDelegation}, query)507 require.NoError(t, err)508 require.NotNil(t, res)509 var ubDel types.UnbondingDelegation510 require.NoError(t, cdc.UnmarshalJSON(res, &ubDel))511 require.Equal(t, addrAcc1.String(), ubDel.DelegatorAddress)512 require.Equal(t, val1.OperatorAddress, ubDel.ValidatorAddress)513 require.Equal(t, 1, len(ubDel.Entries))514 //515 // not found: query unbonding delegation by delegator and validator516 //517 queryValidatorParams = types.QueryDelegatorValidatorRequest{DelegatorAddr: addrAcc2.String(), ValidatorAddr: val1.GetOperator().String()}518 bz, errRes = cdc.MarshalJSON(queryValidatorParams)519 require.NoError(t, errRes)520 query = abci.RequestQuery{521 Path: "/custom/staking/unbondingDelegation",522 Data: bz,523 }524 _, err = querier(ctx, []string{types.QueryUnbondingDelegation}, query)525 require.Error(t, err)526 //527 // found: query unbonding delegation by delegator and validator528 //529 queryDelegatorParams := types.NewQueryDelegatorParams(addrAcc1)530 bz, errRes = cdc.MarshalJSON(queryDelegatorParams)531 require.NoError(t, errRes)532 query = abci.RequestQuery{533 Path: "/custom/staking/delegatorUnbondingDelegations",534 Data: bz,535 }536 res, err = querier(ctx, []string{types.QueryDelegatorUnbondingDelegations}, query)537 require.NoError(t, err)538 require.NotNil(t, res)539 var ubDels []types.UnbondingDelegation540 require.NoError(t, cdc.UnmarshalJSON(res, &ubDels))541 require.Equal(t, 1, len(ubDels))542 require.Equal(t, addrAcc1.String(), ubDels[0].DelegatorAddress)543 require.Equal(t, val1.OperatorAddress, ubDels[0].ValidatorAddress)544 //545 // not found: query unbonding delegation by delegator and validator546 //547 queryDelegatorParams = types.NewQueryDelegatorParams(addrAcc2)548 bz, errRes = cdc.MarshalJSON(queryDelegatorParams)549 require.NoError(t, errRes)550 query = abci.RequestQuery{551 Path: "/custom/staking/delegatorUnbondingDelegations",552 Data: bz,553 }554 res, err = querier(ctx, []string{types.QueryDelegatorUnbondingDelegations}, query)555 require.NoError(t, err)556 require.NotNil(t, res)557 require.NoError(t, cdc.UnmarshalJSON(res, &ubDels))558 require.Equal(t, 0, len(ubDels))559}560func TestQueryHistoricalInfo(t *testing.T) {561 cdc, app, ctx := createTestInput()562 legacyQuerierCdc := codec.NewAminoCodec(cdc)563 querier := keeper.NewQuerier(app.StakingKeeper, legacyQuerierCdc.LegacyAmino)564 addrs := simapp.AddTestAddrs(app, ctx, 2, sdk.TokensFromConsensusPower(10000))565 addrAcc1, addrAcc2 := addrs[0], addrs[1]566 addrVal1, addrVal2 := sdk.ValAddress(addrAcc1), sdk.ValAddress(addrAcc2)567 // Create Validators and Delegation568 val1 := teststaking.NewValidator(t, addrVal1, PKs[0])569 val2 := teststaking.NewValidator(t, addrVal2, PKs[1])570 vals := []types.Validator{val1, val2}571 app.StakingKeeper.SetValidator(ctx, val1)572 app.StakingKeeper.SetValidator(ctx, val2)573 header := tmproto.Header{574 ChainID: "HelloChain",575 Height: 5,576 }577 hi := types.NewHistoricalInfo(header, vals)578 app.StakingKeeper.SetHistoricalInfo(ctx, 5, &hi)579 queryHistoricalParams := types.QueryHistoricalInfoRequest{Height: 4}580 bz, errRes := cdc.MarshalJSON(queryHistoricalParams)581 require.NoError(t, errRes)582 query := abci.RequestQuery{583 Path: "/custom/staking/historicalInfo",584 Data: bz,585 }586 res, err := querier(ctx, []string{types.QueryHistoricalInfo}, query)587 require.Error(t, err, "Invalid query passed")588 require.Nil(t, res, "Invalid query returned non-nil result")589 queryHistoricalParams = types.QueryHistoricalInfoRequest{Height: 5}590 bz, errRes = cdc.MarshalJSON(queryHistoricalParams)591 require.NoError(t, errRes)592 query.Data = bz593 res, err = querier(ctx, []string{types.QueryHistoricalInfo}, query)594 require.NoError(t, err, "Valid query passed")595 require.NotNil(t, res, "Valid query returned nil result")596 var recv types.HistoricalInfo597 require.NoError(t, cdc.UnmarshalJSON(res, &recv))598 require.Equal(t, hi, recv, "HistoricalInfo query returned wrong result")599}...
bbcondition.go
Source:bbcondition.go
1package decorator2import (3 "fmt"4 "github.com/alkaid/behavior/bcore"5 "github.com/alkaid/behavior/util"6 "github.com/google/go-cmp/cmp"7 "go.uber.org/zap"8)9type IBBConditionProperties interface {10 GetOperator() bcore.Operator11 GetKey() string12 GetValue() any13}14// BBConditionProperties é»æ¿æ¡ä»¶èç¹å±æ§15type BBConditionProperties struct {16 bcore.ObservingProperties17 Operator bcore.Operator `json:"operator"` // è¿ç®ç¬¦18 Key string `json:"key"` // é»æ¿é®19 Value any `json:"value"`20}21func (b *BBConditionProperties) GetOperator() bcore.Operator {22 return b.Operator23}24func (b *BBConditionProperties) GetKey() string {25 return b.Key26}27func (b *BBConditionProperties) GetValue() any {28 return b.Value29}30// BBCondition é»æ¿æ¡ä»¶31//32// èç¹å°æ£æ¥ç»å®ç é»æ¿é®ï¼Blackboard Keyï¼ ä¸æ¯å¦è®¾ç½®äºå¼ã33type BBCondition struct {34 bcore.ObservingDecorator35}36// PropertiesClassProvider37//38// @implement INodeWorker.PropertiesClassProvider39// @receiver n40// @return any41func (c *BBCondition) PropertiesClassProvider() any {42 return &BBConditionProperties{}43}44func (c *BBCondition) BBConditionProperties() IBBConditionProperties {45 return c.Properties().(IBBConditionProperties)46}47// StartObserving48//49// @override bcore.ObservingDecorator .StartObserving50// @receiver o51// @param brain52func (c *BBCondition) StartObserving(brain bcore.IBrain) {53 c.ObservingDecorator.StartObserving(brain)54 brain.Blackboard().(bcore.IBlackboardInternal).AddObserver(c.BBConditionProperties().GetKey(), c.getObserver(brain))55}56// StopObserving57//58// @override bcore.ObservingDecorator .StopObserving59// @receiver o60// @param brain61func (c *BBCondition) StopObserving(brain bcore.IBrain) {62 c.ObservingDecorator.StopObserving(brain)63 brain.Blackboard().(bcore.IBlackboardInternal).RemoveObserver(c.BBConditionProperties().GetKey(), c.getObserver(brain))64 c.Memory(brain).DefaultObserver = nil65}66// ConditionMet67//68// @implement bcore.IObservingWorker .ConditionMet69// @receiver o70// @param brain71// @param args72// @return bool73//74//nolint:gocyclo75func (c *BBCondition) ConditionMet(brain bcore.IBrain, args ...any) bool {76 // è¥å§æåå¨,ä¼å
使ç¨å§æ77 if c.HasDelegatorOrScript() {78 ret := c.Update(brain, bcore.EventTypeOnUpdate, 0)79 return ret == bcore.ResultSucceeded80 }81 v, ok := brain.Blackboard().Get(c.BBConditionProperties().GetKey())82 if !ok {83 return c.BBConditionProperties().GetOperator() == bcore.OperatorIsNotSet84 }85 propValue := c.BBConditionProperties().GetValue()86 // é»æ¿value转float,é
ç½®value转float87 var bbNumber, propNumber float6488 var bbOk, propOk bool89 bbNumber, bbOk = util.Float(v)90 if bbOk {91 propNumber, propOk = util.Float(propValue)92 }93 // 以ä¸ç±»åå¤æè½å¦æå转ænumber,ä¸è½è½¬åæ æ³æ¯è¾94 switch c.BBConditionProperties().GetOperator() {95 case bcore.OperatorIsGt, bcore.OperatorIsGte, bcore.OperatorIsLt, bcore.OperatorIsLte:96 if bbOk && propOk {97 break98 }99 c.Log(brain).Error("value cannot compare", zap.Int("operate", int(c.BBConditionProperties().GetOperator())), zap.Any("blackboardValue", v), zap.Any("configValue", propValue))100 return false101 }102 switch c.BBConditionProperties().GetOperator() {103 case bcore.OperatorIsSet:104 return true105 case bcore.OperatorIsEqual:106 if bbOk && propOk {107 return bbNumber == propNumber108 }109 return cmp.Equal(v, propValue)110 case bcore.OperatorIsNotEqual:111 if bbOk && propOk {112 return bbNumber != propNumber113 }114 return !cmp.Equal(v, propValue)115 case bcore.OperatorIsGte:116 return bbNumber >= propNumber117 case bcore.OperatorIsGt:118 return bbNumber > propNumber119 case bcore.OperatorIsLte:120 return bbNumber <= propNumber121 case bcore.OperatorIsLt:122 return bbNumber < propNumber123 }124 c.Log(brain).Error("not support operator", zap.Int("operator", int(c.BBConditionProperties().GetOperator())))125 return false126}127func (c *BBCondition) OnString(brain bcore.IBrain) string {128 return fmt.Sprintf("%s(%d)%s?%v", c.ObservingDecorator.OnString(brain), c.BBConditionProperties().GetOperator(), c.BBConditionProperties().GetKey(), c.BBConditionProperties().GetValue())129}130func (c *BBCondition) getObserver(brain bcore.IBrain) bcore.Observer {131 ob := c.Memory(brain).DefaultObserver132 if ob == nil {133 ob = func(op bcore.OpType, key string, oldValue any, newValue any) {134 c.ObservingDecorator.Evaluate(brain, op, key, oldValue, newValue)135 }136 c.Memory(brain).DefaultObserver = ob137 }138 return ob139}...
getOperator
Using AI Code Generation
1import (2func main() {3 var jsonBlob = []byte(`[4 {"Name": "Platypus", "Order": "Monotremata"},5 {"Name": "Quoll", "Order": "Dasyuromorphia"}6 type Animal struct {7 }8 err := json.Unmarshal(jsonBlob, &animals)9 if err != nil {10 fmt.Println("error:", err)11 }12 fmt.Printf("%+v", animals)13}14[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]15[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]16import (17func main() {18 var jsonBlob = []byte(`[19 {"Name": "Platypus", "Order": "Monotremata"},20 {"Name": "Quoll", "Order": "Dasyuromorphia"}21 var animals []map[string]interface{}22 err := json.Unmarshal(jsonBlob, &animals)23 if err != nil {24 fmt.Println("error:", err)25 }26 fmt.Println(animals)27}28[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]29[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]30import (31func main() {32 var jsonBlob = []byte(`[33 {"Name": "Platypus", "Order": "Monotremata"},34 {"Name": "Quoll", "Order": "Dasyuromorphia"}35 type Animal struct {
getOperator
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p1 := Person{"James", "Bond", 20}6 bs, _ := json.Marshal(p1)7 fmt.Println(string(bs))8}9import (10type Person struct {11}12func main() {13 p1 := Person{"James", "Bond", 20}14 bs, _ := json.Marshal(p1)15 fmt.Println(string(bs))16}17import (18type Person struct {19}20func main() {21 p1 := Person{"James", "Bond", 20}22 bs, _ := json.Marshal(p1)23 fmt.Println(string(bs))24}25import (26type Person struct {27}28func main() {29 p1 := Person{"James", "Bond", 20}30 bs, _ := json.Marshal(p1)31 fmt.Println(string(bs))32}33import (34type Person struct {35}36func main() {37 p1 := Person{"James", "Bond", 20}38 bs, _ := json.Marshal(p1)39 fmt.Println(string(bs))40}41import (42type Person struct {
getOperator
Using AI Code Generation
1import (2func main() {3 json := json.New()4 fmt.Println(json.GetOperator())5}6import (7func main() {8 fmt.Println(beego.GetOperator())9}10import (11func main() {12 fmt.Println(beego.GetOperator())13}14import (15func main() {16 fmt.Println(beego.GetOperator())17}18import (19func main() {20 fmt.Println(beego.GetOperator())21}22import (23func main() {24 fmt.Println(beego.GetOperator())25}26import (27func main() {28 fmt.Println(beego.GetOperator())29}30import (31func main() {32 fmt.Println(beego.GetOperator())33}34import (35func main() {36 fmt.Println(beego.GetOperator())37}38import (39func main() {40 fmt.Println(beego.Get
getOperator
Using AI Code Generation
1import (2func main() {3 fmt.Printf("4%s", json.GetOperator())5}6func GetOperator() string {7}8import (9func TestGetOperator(t *testing.T) {10 if GetOperator() != "json" {11 t.Errorf("GetOperator() failed. Got %s, expected %s", GetOperator(), "json")12 }13}
getOperator
Using AI Code Generation
1import (2func main() {3 type Person struct {4 }5 type Human struct {6 }7 type Student struct {8 }9 type Teacher struct {10 }11 type Employee struct {12 }13 type Employee1 struct {14 }15 type Employee2 struct {16 }17 type Employee3 struct {18 }19 type Employee4 struct {20 }21 type Employee5 struct {22 }23 type Employee6 struct {24 }25 type Employee7 struct {26 }27 type Employee8 struct {28 }29 type Employee9 struct {30 }31 type Employee10 struct {32 }33 type Employee11 struct {34 }35 type Employee12 struct {36 }37 type Employee13 struct {
getOperator
Using AI Code Generation
1import (2type Operator struct {3}4func main() {5 data := []byte(`{"name":"Operator","operator":"+"}`)6 err := json.Unmarshal(data, &operator)7 if err != nil {8 fmt.Println(err)9 }10 fmt.Println(operator)11}12{Operator +}13import (14type Operator struct {15}16func main() {17 data, err := json.Marshal(operator)18 if err != nil {19 fmt.Println(err)20 }21 fmt.Println(string(data))22}23{"Name":"Operator","Operator":"+"}
getOperator
Using AI Code Generation
1import (2type Operator struct {3}4func main() {5 jsonString := `{"Name":"Sachin","Age":38}`6 op, err := getOperator(jsonString)7 if err != nil {8 fmt.Println(err)9 } else {10 fmt.Println(op)11 }12}13func getOperator(jsonString string) (Operator, error) {14 err := json.Unmarshal([]byte(jsonString), &op)15}16{Sachin 38}17import (18func main() {19 jsonString := `{"Name":"Sachin","Age":38}`20 op, err := getOperator(jsonString)21 if err != nil {22 fmt.Println(err)23 } else {24 fmt.Println(op)25 }26}27func getOperator(jsonString string) (map[string]interface{}, error) {28 var op map[string]interface{}29 err := json.Unmarshal([]byte(jsonString), &op)30}31import (32func main() {33 jsonString := `[{"Name":"Sachin","Age":38},{"Name":"Virat","Age":32}]`34 op, err := getOperator(jsonString)35 if err != nil {36 fmt.Println(err)37 } else {38 fmt.Println(op)
getOperator
Using AI Code Generation
1func main() {2 json := json.New()3 json.GetOperator()4}5func main() {6 json := json.New()7 json.GetOperator()8}9func main() {10 json := json.New()11 json.GetOperator()12}13func main() {14 json := json.New()15 json.GetOperator()16}17func main() {18 json := json.New()19 json.GetOperator()20}21func main() {22 json := json.New()23 json.GetOperator()24}25func main() {26 json := json.New()27 json.GetOperator()28}29func main() {30 json := json.New()31 json.GetOperator()32}33func main() {34 json := json.New()35 json.GetOperator()36}37func main() {
getOperator
Using AI Code Generation
1import (2type Operator struct {3}4func main() {5 json := json.New()6 op := json.GetOperator()7 fmt.Println(op)8}9func (j *JSON) GetOperator() string10func (j *JSON) GetOperator(op string) string11import (12type Operator struct {13}14func main() {15 json := json.New()16 json.SetOperator(".")17 op := json.GetOperator()18 fmt.Println(op)19}20func (j *JSON) SetOperator(op string)21import (22type Operator struct {23}24func main() {25 json := json.New()26 json.SetOperator(".")27 op := json.GetOperator()
getOperator
Using AI Code Generation
1operator = json.getOperator();2switch (operator) {3result = Calculator.add(json.getOperand1(), json.getOperand2());4break;5result = Calculator.subtract(json.getOperand1(), json.getOperand2());6break;7result = Calculator.multiply(json.getOperand1(), json.getOperand2());8break;9result = Calculator.divide(json.getOperand1(), json.getOperand2());10break;11}12json.setResult(result);13json.closeFile();14}15}16public class Calculator {17public static int add(int operand1, int operand2) {18return operand1 + operand2;19}20public static int subtract(int operand1, int operand2) {21return operand1 - operand2;22}23public static int multiply(int operand1, int operand2) {24return operand1 * operand2;25}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!