From 7fd79df4e150979c478c7a1cfc8e36a680941595 Mon Sep 17 00:00:00 2001 From: Alex | Interchain Labs Date: Fri, 21 Mar 2025 18:04:36 -0400 Subject: [PATCH] chore: fix all linting (#24101) --- .golangci.yml | 2 + Makefile | 8 +- UPGRADING.md | 2 +- baseapp/abci_test.go | 23 +-- baseapp/abci_utils.go | 4 +- baseapp/baseapp_test.go | 26 ++- baseapp/grpcrouter_test.go | 1 + baseapp/snapshot_test.go | 1 - baseapp/streaming_test.go | 15 +- baseapp/utils_test.go | 28 +++- client/config/config.go | 8 +- client/debug/main.go | 14 +- client/flags/flags_test.go | 1 - client/grpc/cmtservice/autocli.go | 2 +- client/grpc_query_test.go | 9 +- client/keys/add.go | 2 +- client/keys/add_ledger_test.go | 1 - client/keys/add_test.go | 1 - client/keys/list_test.go | 3 +- client/keys/parse_test.go | 1 - client/keys/show.go | 4 +- client/keys/show_test.go | 2 - client/snapshot/load.go | 3 +- client/tx/aux_builder_test.go | 2 + client/tx/tx_test.go | 11 +- client/utils_test.go | 1 - client/v2/autocli/common_test.go | 2 +- client/v2/autocli/keyring/keyring.go | 5 +- client/v2/internal/strcase/kebab_test.go | 6 +- codec/amino_codec_test.go | 1 - codec/codec_common_test.go | 8 +- codec/types/any.go | 1 - codec/types/any_internal_test.go | 2 +- codec/types/any_test.go | 2 +- codec/types/types_test.go | 2 +- codec/unknownproto/benchmarks_test.go | 2 + codec/unknownproto/unit_helpers_test.go | 1 - codec/unknownproto/unknown_fields_test.go | 4 - crypto/armor.go | 11 +- crypto/armor_test.go | 4 +- crypto/hd/fundraiser_test.go | 2 + crypto/hd/hdpath_test.go | 4 - crypto/keyring/keyring.go | 4 +- crypto/keyring/keyring_test.go | 11 +- crypto/keyring/signing_algorithms_test.go | 1 - crypto/keys/multisig/amino.go | 2 +- crypto/keys/secp256k1/secp256k1.go | 8 +- .../keys/secp256k1/secp256k1_internal_test.go | 1 - crypto/keys/secp256k1/secp256k1_test.go | 1 - crypto/ledger/encode_test.go | 2 + crypto/ledger/ledger_mock.go | 2 +- crypto/ledger/ledger_secp256k1.go | 6 +- crypto/ledger/ledger_test.go | 2 + crypto/types/compact_bit_array_test.go | 3 - depinject/internal/codegen/file.go | 6 +- internal/util.go | 2 +- runtime/app.go | 8 +- scripts/go-lint-changes.bash | 41 ----- server/api/server_test.go | 11 +- server/export_test.go | 2 + .../grpc/gogoreflection/serverreflection.go | 17 +- server/mock/app.go | 2 +- server/mock/app_test.go | 13 +- server/pruning_test.go | 2 - server/start.go | 6 +- server/util_test.go | 22 ++- simapp/app.go | 4 +- simapp/genesis_account_test.go | 1 - simapp/sim_bench_test.go | 2 - store/cache/cache.go | 2 +- store/cachekv/search_test.go | 2 - store/cachekv/store_test.go | 10 +- store/iavl/store_test.go | 1 - store/rootmulti/snapshot_test.go | 2 - store/rootmulti/store.go | 5 +- store/rootmulti/store_test.go | 2 - store/snapshots/chunk.go | 13 +- store/snapshots/helpers_test.go | 6 +- store/types/gas_test.go | 1 - tests/e2e/auth/cli_test.go | 6 +- tests/e2e/auth/suite.go | 9 +- tests/e2e/authz/grpc.go | 4 +- tests/e2e/authz/tx.go | 7 - tests/e2e/bank/cli_test.go | 7 +- tests/e2e/bank/grpc.go | 3 - tests/e2e/bank/suite.go | 4 - .../client/grpc/cmtservice/service_test.go | 11 +- tests/e2e/distribution/grpc_query_suite.go | 9 - tests/e2e/distribution/suite.go | 8 - tests/e2e/gov/cli_test.go | 6 +- tests/e2e/gov/grpc.go | 8 - tests/e2e/gov/tx.go | 6 - tests/e2e/group/cli_test.go | 7 +- tests/e2e/mint/cli_test.go | 1 + tests/e2e/server/export_test.go | 21 ++- tests/e2e/staking/cli_test.go | 6 +- tests/e2e/staking/suite.go | 3 +- tests/e2e/tx/service_test.go | 6 - .../crypto_hd_deriveprivatekeyforpath_test.go | 4 +- .../tests/crypto_hd_newparamsfrompath_test.go | 2 +- tests/fuzz/tests/types_parsecoin_test.go | 2 +- tests/fuzz/tests/types_parsedeccoin_test.go | 2 +- .../tests/types_verifyaddressformat_test.go | 2 +- tests/fuzz/tests/unknownproto_test.go | 4 +- .../integration/auth/client/cli/suite_test.go | 9 +- .../bank/keeper/deterministic_test.go | 7 +- .../distribution/keeper/msg_server_test.go | 28 ++-- .../evidence/keeper/infraction_test.go | 13 +- tests/integration/gov/common_test.go | 2 + tests/integration/gov/genesis_test.go | 2 + tests/integration/gov/keeper/common_test.go | 23 +-- .../integration/gov/keeper/grpc_query_test.go | 8 +- tests/integration/gov/keeper/keeper_test.go | 11 +- tests/integration/gov/keeper/tally_test.go | 47 +++--- tests/integration/rapidgen/rapidgen.go | 8 +- tests/integration/runtime/query_test.go | 2 +- .../slashing/keeper/keeper_test.go | 34 ++-- .../integration/staking/keeper/common_test.go | 12 +- .../staking/keeper/determinstic_test.go | 158 ++++++++++-------- .../staking/keeper/genesis_test.go | 2 + .../staking/keeper/grpc_query_test.go | 2 + .../integration/staking/keeper/slash_test.go | 2 + .../staking/keeper/unbonding_test.go | 8 + .../staking/keeper/validator_bench_test.go | 46 ++--- .../staking/keeper/validator_test.go | 119 ++++++------- .../store/rootmulti/rollback_test.go | 19 ++- .../tx/aminojson/aminojson_test.go | 4 +- testutil/cmdtest/system.go | 6 +- testutil/integration/router.go | 7 +- testutil/sims/simulation_helpers_test.go | 5 +- testutil/sims/tx_helpers.go | 5 +- types/address.go | 18 +- types/address/hash_test.go | 2 + types/address/store_key_test.go | 1 - types/address_test.go | 38 +++-- types/coin.go | 2 - types/coin_benchmark_test.go | 3 + types/context_test.go | 4 +- types/dec_coin.go | 2 +- types/mempool/priority_nonce_test.go | 4 - types/module/module.go | 2 - types/module/module_test.go | 6 +- types/query/collections_pagination_test.go | 1 - types/simulation/account_test.go | 3 - types/simulation/rand_util_test.go | 3 - types/tx/ext.go | 2 +- x/auth/ante/ante_test.go | 4 +- x/auth/ante/basic_test.go | 1 - x/auth/ante/setup_test.go | 2 +- x/auth/ante/sigverify_test.go | 4 +- x/auth/ante/testutil_test.go | 11 +- x/auth/client/cli/tx_multisign.go | 2 +- x/auth/client/cli/tx_sign.go | 15 +- x/auth/client/tx.go | 2 +- x/auth/client/tx_test.go | 1 - x/auth/migrations/v2/store_test.go | 16 +- x/auth/migrations/v3/store.go | 2 +- x/auth/migrations/v4/migrate.go | 3 +- x/auth/testutil/util.go | 2 + x/auth/tx/aux_test.go | 8 +- x/auth/tx/encode_decode_test.go | 3 - x/auth/tx/legacy_amino_json_test.go | 4 +- x/auth/tx/service.go | 2 +- x/auth/types/account_test.go | 5 +- x/auth/types/params_test.go | 1 - x/auth/types/permissions_test.go | 1 - x/auth/vesting/client/cli/tx_test.go | 9 +- x/auth/vesting/types/vesting_account_test.go | 2 - x/authz/client/cli/tx_test.go | 1 - x/authz/keeper/genesis_test.go | 2 +- x/authz/keeper/keeper.go | 7 +- x/authz/keeper/keeper_test.go | 6 +- x/authz/migrations/v2/store_test.go | 18 +- x/authz/module/abci_test.go | 2 +- x/authz/msgs_test.go | 2 +- x/authz/simulation/decoder_test.go | 1 - x/authz/simulation/operations_test.go | 14 +- x/bank/app_test.go | 4 + x/bank/client/cli/tx.go | 11 +- x/bank/client/cli/tx_test.go | 4 +- x/bank/keeper/genesis.go | 2 +- x/bank/keeper/grpc_query_test.go | 1 - x/bank/keeper/keeper_test.go | 32 ++-- x/bank/keeper/msg_server_test.go | 7 +- x/bank/keeper/send.go | 6 +- x/bank/migrations/v3/store_test.go | 4 +- x/bank/migrations/v4/gen_state_test.go | 2 +- x/bank/module.go | 4 - x/bank/simulation/operations_test.go | 15 +- x/bank/types/balance_test.go | 2 +- x/circuit/ante/circuit_test.go | 5 +- x/circuit/keeper/keeper_test.go | 4 +- x/crisis/abci.go | 2 +- x/crisis/keeper/msg_server_test.go | 2 - x/distribution/client/cli/tx_test.go | 8 - x/distribution/client/common/common_test.go | 1 - x/distribution/keeper/delegation.go | 4 +- x/distribution/keeper/grpc_query.go | 1 - x/distribution/keeper/keeper.go | 12 +- x/distribution/keeper/validator.go | 5 +- x/distribution/migrations/v2/store_test.go | 1 - x/distribution/module.go | 4 - x/distribution/simulation/decoder_test.go | 1 - x/distribution/simulation/operations_test.go | 22 +-- x/distribution/types/params_internal_test.go | 1 - x/feegrant/client/cli/tx_test.go | 5 - x/feegrant/keeper/genesis_test.go | 2 + x/feegrant/keeper/keeper.go | 2 +- x/feegrant/keeper/keeper_test.go | 8 +- x/feegrant/keeper/msg_server_test.go | 42 ++--- x/feegrant/migrations/v2/store.go | 9 +- x/feegrant/module/abci_test.go | 20 +-- x/feegrant/simulation/decoder_test.go | 1 - x/feegrant/simulation/operations.go | 6 +- x/feegrant/simulation/operations_test.go | 5 +- x/genutil/client/cli/genaccount_test.go | 2 - x/genutil/client/cli/init_test.go | 11 +- x/genutil/client/cli/validate_genesis_test.go | 1 - x/genutil/client/testutil/helpers.go | 2 +- x/genutil/gentx.go | 6 +- x/genutil/gentx_test.go | 2 +- x/genutil/types/genesis_state.go | 2 +- x/genutil/utils_test.go | 1 - x/gov/abci_test.go | 44 +++-- x/gov/client/cli/prompt_test.go | 5 +- x/gov/client/cli/util_test.go | 22 +-- x/gov/client/utils/query_test.go | 1 - x/gov/common_test.go | 4 + x/gov/keeper/common_test.go | 2 + x/gov/keeper/deposit_test.go | 6 +- x/gov/keeper/grpc_query_test.go | 36 ++-- x/gov/keeper/hooks_test.go | 4 +- x/gov/keeper/msg_server_test.go | 2 +- x/gov/keeper/proposal.go | 2 +- x/gov/keeper/proposal_test.go | 10 +- x/gov/keeper/tally.go | 1 - x/gov/keeper/vote_test.go | 2 +- x/gov/migrations/v2/store_test.go | 3 +- x/gov/migrations/v3/store_test.go | 2 + x/gov/module.go | 4 - x/gov/simulation/operations.go | 2 - x/gov/simulation/operations_test.go | 51 ++++-- x/gov/types/metadata.go | 2 +- x/gov/types/v1/genesis.go | 4 +- x/gov/types/v1/proposal.go | 4 +- x/gov/types/v1/vote.go | 4 +- x/gov/types/v1beta1/proposal.go | 5 +- x/gov/types/v1beta1/vote.go | 4 +- x/group/client/cli/tx.go | 13 +- x/group/client/cli/tx_test.go | 44 ++--- x/group/internal/orm/auto_uint64_test.go | 1 - x/group/internal/orm/index_test.go | 1 - x/group/internal/orm/iterator.go | 2 +- .../internal/orm/iterator_property_test.go | 3 +- x/group/internal/orm/iterator_test.go | 1 - x/group/internal/orm/orm_scenario_test.go | 8 +- x/group/internal/orm/primary_key_test.go | 1 - x/group/internal/orm/table.go | 2 +- x/group/keeper/keeper.go | 3 - x/group/keeper/keeper_test.go | 15 +- x/group/keeper/msg_server_test.go | 27 +-- x/group/keeper/tally_test.go | 1 - x/group/module/abci_test.go | 55 +++--- x/group/module/module.go | 4 - x/group/simulation/decoder_test.go | 1 - x/group/simulation/operations_test.go | 42 +++-- x/nft/internal/conv/doc.go | 2 +- x/nft/internal/conv/string.go | 11 +- x/nft/keeper/msg_server.go | 4 +- x/nft/keeper/nft.go | 10 +- x/nft/keeper/nft_batch_test.go | 10 +- x/nft/simulation/decoder_test.go | 1 - x/nft/simulation/operations_test.go | 5 +- x/params/keeper/keeper_test.go | 7 - x/params/proposal_handler_test.go | 1 - x/params/types/subspace.go | 2 +- x/params/types/subspace_test.go | 1 - x/simulation/mock_cometbft.go | 2 + x/simulation/operation.go | 1 - x/simulation/util.go | 1 + x/slashing/abci_test.go | 3 +- x/slashing/app_test.go | 5 +- x/slashing/keeper/genesis.go | 20 ++- x/slashing/keeper/genesis_test.go | 10 +- x/slashing/keeper/grpc_query_test.go | 14 +- x/slashing/keeper/hooks_test.go | 2 +- x/slashing/keeper/infractions.go | 5 +- x/slashing/keeper/keeper.go | 6 +- x/slashing/keeper/keeper_test.go | 14 +- x/slashing/keeper/msg_server_test.go | 8 +- x/slashing/keeper/signing_info.go | 3 +- x/slashing/keeper/signing_info_test.go | 8 +- x/slashing/keeper/slash_redelegation_test.go | 8 +- x/slashing/migrations/v2/store_test.go | 1 - x/slashing/simulation/decoder_test.go | 1 - x/slashing/simulation/operations_test.go | 14 +- x/staking/bench_test.go | 1 + x/staking/client/cli/tx.go | 2 +- x/staking/client/cli/tx_test.go | 8 - x/staking/genesis_test.go | 2 - x/staking/keeper/delegation.go | 6 +- x/staking/keeper/genesis.go | 2 +- x/staking/keeper/historical_info_test.go | 2 +- x/staking/keeper/query_utils.go | 7 +- x/staking/keeper/val_state_change.go | 4 +- x/staking/migrations/v2/store_test.go | 1 - x/staking/migrations/v4/migrations_test.go | 4 + x/staking/migrations/v5/store.go | 2 +- x/staking/module.go | 6 +- x/staking/simulation/decoder_test.go | 1 - x/staking/simulation/operations_test.go | 6 +- x/staking/testutil/helpers.go | 2 + x/staking/types/historical_info_test.go | 2 + x/staking/types/keys.go | 1 - x/tx/decode/unknown_test.go | 4 - x/tx/signing/aminojson/aminojson_test.go | 1 + x/tx/signing/aminojson/options.go | 6 +- x/upgrade/abci_test.go | 23 ++- x/upgrade/client/cli/parse_test.go | 4 +- x/upgrade/client/cli/tx.go | 4 +- x/upgrade/internal/conv/string.go | 9 +- x/upgrade/keeper/grpc_query_test.go | 10 +- x/upgrade/keeper/keeper_test.go | 29 ++-- x/upgrade/plan/downloader.go | 3 +- x/upgrade/plan/downloader_test.go | 3 + x/upgrade/plan/info.go | 2 +- x/upgrade/plan/info_test.go | 2 + x/upgrade/types/proposal_test.go | 2 - x/upgrade/types/storeloader_test.go | 9 +- 329 files changed, 1282 insertions(+), 1251 deletions(-) delete mode 100755 scripts/go-lint-changes.bash diff --git a/.golangci.yml b/.golangci.yml index 71eafc7787..f237a48ed5 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -37,6 +37,8 @@ linters: issues: exclude-dirs: - testutil/testdata + - x/params + - x/crisis exclude-files: - server/grpc/gogoreflection/fix_registration.go - "fix_registration.go" diff --git a/Makefile b/Makefile index fff5efbf5a..25f8e34604 100644 --- a/Makefile +++ b/Makefile @@ -382,19 +382,13 @@ benchmark: ### Linting ### ############################################################################### -golangci_version=v1.64.7 +golangci_version=v1.64.8 lint-install: @echo "--> Installing golangci-lint $(golangci_version)" @go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(golangci_version) lint: - @echo "--> Running linter on diffed files only." - $(MAKE) lint-install - @./scripts/go-lint-changes.bash --timeout=15m - - -lint-all: @echo "--> Running linter on all files" $(MAKE) lint-install @./scripts/go-lint-all.bash --timeout=15m diff --git a/UPGRADING.md b/UPGRADING.md index 449d18333f..563d7d4685 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -65,7 +65,7 @@ If you are still using the legacy wiring, you must enable unordered transactions if manager := app.SnapshotManager(); manager != nil { err := manager.RegisterExtensions(unorderedtx.NewSnapshotter(app.UnorderedTxManager)) if err != nil { - panic(fmt.Errorf("failed to register snapshot extension: %s", err)) + panic(fmt.Errorf("failed to register snapshot extension: %w", err)) } } ``` diff --git a/baseapp/abci_test.go b/baseapp/abci_test.go index a1f9e8ca25..796fbeefa5 100644 --- a/baseapp/abci_test.go +++ b/baseapp/abci_test.go @@ -716,7 +716,7 @@ func TestABCI_FinalizeBlock_MultiMsg(t *testing.T) { msgs = append(msgs, &baseapptestutil.MsgCounter2{Counter: 0, Signer: addr.String()}) msgs = append(msgs, &baseapptestutil.MsgCounter2{Counter: 1, Signer: addr.String()}) - builder.SetMsgs(msgs...) + require.NoError(t, builder.SetMsgs(msgs...)) builder.SetMemo(tx.GetMemo()) setTxSignature(t, builder, 0) @@ -888,7 +888,7 @@ func TestABCI_InvalidTransaction(t *testing.T) { { txBuilder := suite.txConfig.NewTxBuilder() _, _, addr := testdata.KeyTestPubAddr() - txBuilder.SetMsgs(&baseapptestutil.MsgCounter2{Signer: addr.String()}) + require.NoError(t, txBuilder.SetMsgs(&baseapptestutil.MsgCounter2{Signer: addr.String()})) setTxSignature(t, txBuilder, 0) unknownRouteTx := txBuilder.GetTx() @@ -901,10 +901,10 @@ func TestABCI_InvalidTransaction(t *testing.T) { require.EqualValues(t, sdkerrors.ErrUnknownRequest.ABCICode(), code, err) txBuilder = suite.txConfig.NewTxBuilder() - txBuilder.SetMsgs( + require.NoError(t, txBuilder.SetMsgs( &baseapptestutil.MsgCounter{Signer: addr.String()}, &baseapptestutil.MsgCounter2{Signer: addr.String()}, - ) + )) setTxSignature(t, txBuilder, 0) unknownRouteTx = txBuilder.GetTx() @@ -920,7 +920,7 @@ func TestABCI_InvalidTransaction(t *testing.T) { // Transaction with an unregistered message { txBuilder := suite.txConfig.NewTxBuilder() - txBuilder.SetMsgs(&testdata.MsgCreateDog{}) + require.NoError(t, txBuilder.SetMsgs(&testdata.MsgCreateDog{})) tx := txBuilder.GetTx() _, _, err := suite.baseApp.SimDeliver(suite.txConfig.TxEncoder(), tx) @@ -1543,10 +1543,11 @@ func TestABCI_Proposals_WithVE(t *testing.T) { suite := NewBaseAppSuite(t, setInitChainerOpt, prepareOpt) - suite.baseApp.InitChain(&abci.RequestInitChain{ + _, err := suite.baseApp.InitChain(&abci.RequestInitChain{ InitialHeight: 1, ConsensusParams: &cmtproto.ConsensusParams{}, }) + require.NoError(t, err) reqPrepareProposal := abci.RequestPrepareProposal{ MaxTxBytes: 100000, @@ -1683,11 +1684,12 @@ func TestABCI_PrepareProposal_MaxGas(t *testing.T) { baseapptestutil.RegisterCounterServer(suite.baseApp.MsgServiceRouter(), NoopCounterServerImpl{}) // set max block gas limit to 100 - suite.baseApp.InitChain(&abci.RequestInitChain{ + _, err := suite.baseApp.InitChain(&abci.RequestInitChain{ ConsensusParams: &cmtproto.ConsensusParams{ Block: &cmtproto.BlockParams{MaxGas: 100}, }, }) + require.NoError(t, err) // insert 100 txs, each with a gas limit of 10 _, _, addr := testdata.KeyTestPubAddr() @@ -1696,7 +1698,7 @@ func TestABCI_PrepareProposal_MaxGas(t *testing.T) { msgs := []sdk.Msg{msg} builder := suite.txConfig.NewTxBuilder() - builder.SetMsgs(msgs...) + require.NoError(t, builder.SetMsgs(msgs...)) builder.SetMemo("counter=" + strconv.FormatInt(i, 10) + "&failOnAnte=false") builder.SetGasLimit(10) setTxSignature(t, builder, uint64(i)) @@ -2010,13 +2012,14 @@ func TestABCI_HaltChain(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { suite := NewBaseAppSuite(t, baseapp.SetHaltHeight(tc.haltHeight), baseapp.SetHaltTime(tc.haltTime)) - suite.baseApp.InitChain(&abci.RequestInitChain{ + _, err := suite.baseApp.InitChain(&abci.RequestInitChain{ ConsensusParams: &cmtproto.ConsensusParams{}, InitialHeight: tc.blockHeight, }) + require.NoError(t, err) app := suite.baseApp - _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: tc.blockHeight, Time: time.Unix(tc.blockTime, 0), }) diff --git a/baseapp/abci_utils.go b/baseapp/abci_utils.go index 51b7b94e56..85e9e1e03c 100644 --- a/baseapp/abci_utils.go +++ b/baseapp/abci_utils.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "slices" //nolint: gci // ignore this line for this linter + "slices" "github.com/cockroachdb/errors" abci "github.com/cometbft/cometbft/abci/types" @@ -13,7 +13,7 @@ import ( cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" cmttypes "github.com/cometbft/cometbft/types" protoio "github.com/cosmos/gogoproto/io" - "github.com/cosmos/gogoproto/proto" //nolint: gci // ignore this line for this linter + "github.com/cosmos/gogoproto/proto" "cosmossdk.io/core/comet" diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 629b39be87..f63ca762bf 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -62,6 +62,8 @@ type ( ) func NewBaseAppSuite(t *testing.T, opts ...func(*baseapp.BaseApp)) *BaseAppSuite { + t.Helper() + cdc := codectestutil.CodecOptions{}.NewCodec() baseapptestutil.RegisterInterfaces(cdc.InterfaceRegistry()) @@ -112,6 +114,8 @@ func getQueryBaseapp(t *testing.T) *baseapp.BaseApp { } func NewBaseAppSuiteWithSnapshots(t *testing.T, cfg SnapshotsConfig, opts ...func(*baseapp.BaseApp)) *BaseAppSuite { + t.Helper() + snapshotTimeout := 1 * time.Minute snapshotStore, err := snapshots.NewStore(dbm.NewMemDB(), testutil.GetTempDir(t)) require.NoError(t, err) @@ -140,7 +144,7 @@ func NewBaseAppSuiteWithSnapshots(t *testing.T, cfg SnapshotsConfig, opts ...fun _, _, addr := testdata.KeyTestPubAddr() txs := [][]byte{} for txNum := 0; txNum < cfg.blockTxs; txNum++ { - msgs := []sdk.Msg{} + var msgs []sdk.Msg for msgNum := 0; msgNum < 100; msgNum++ { key := []byte(fmt.Sprintf("%v", keyCounter)) value := make([]byte, 10000) @@ -153,7 +157,7 @@ func NewBaseAppSuiteWithSnapshots(t *testing.T, cfg SnapshotsConfig, opts ...fun } builder := suite.txConfig.NewTxBuilder() - builder.SetMsgs(msgs...) + require.NoError(t, builder.SetMsgs(msgs...)) setTxSignature(t, builder, 0) txBytes, err := suite.txConfig.TxEncoder()(builder.GetTx()) @@ -294,6 +298,8 @@ func TestSetLoader(t *testing.T) { } initStore := func(t *testing.T, db dbm.DB, storeKey string, k, v []byte) { + t.Helper() + rs := rootmulti.NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) rs.SetPruning(pruningtypes.NewPruningOptions(pruningtypes.PruningNothing)) @@ -314,6 +320,8 @@ func TestSetLoader(t *testing.T) { } checkStore := func(t *testing.T, db dbm.DB, ver int64, storeKey string, k, v []byte) { + t.Helper() + rs := rootmulti.NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) rs.SetPruning(pruningtypes.NewPruningOptions(pruningtypes.PruningDefault)) @@ -549,7 +557,8 @@ func TestCustomRunTxPanicHandler(t *testing.T) { require.PanicsWithValue(t, customPanicMsg, func() { bz, err := suite.txConfig.TxEncoder()(tx) require.NoError(t, err) - suite.baseApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: 1, Txs: [][]byte{bz}}) + _, err = suite.baseApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: 1, Txs: [][]byte{bz}}) + require.Error(t, err) }) } } @@ -623,7 +632,8 @@ func TestBaseAppAnteHandler(t *testing.T) { require.Equal(t, int64(2), getIntFromStore(t, store, anteKey)) require.Equal(t, int64(1), getIntFromStore(t, store, deliverKey)) - suite.baseApp.Commit() + _, err = suite.baseApp.Commit() + require.NoError(t, err) } func TestBaseAppPostHandler(t *testing.T) { @@ -869,16 +879,16 @@ func TestGetMaximumBlockGas(t *testing.T) { ctx := suite.baseApp.NewContext(true) - suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: 0}}) + require.NoError(t, suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: 0}})) require.Equal(t, uint64(0), suite.baseApp.GetMaximumBlockGas(ctx)) - suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: -1}}) + require.NoError(t, suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: -1}})) require.Equal(t, uint64(0), suite.baseApp.GetMaximumBlockGas(ctx)) - suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: 5000000}}) + require.NoError(t, suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: 5000000}})) require.Equal(t, uint64(5000000), suite.baseApp.GetMaximumBlockGas(ctx)) - suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: -5000000}}) + require.NoError(t, suite.baseApp.StoreConsensusParams(ctx, cmtproto.ConsensusParams{Block: &cmtproto.BlockParams{MaxGas: -5000000}})) require.Panics(t, func() { suite.baseApp.GetMaximumBlockGas(ctx) }) } diff --git a/baseapp/grpcrouter_test.go b/baseapp/grpcrouter_test.go index d747fbb747..af5c24c4cc 100644 --- a/baseapp/grpcrouter_test.go +++ b/baseapp/grpcrouter_test.go @@ -162,6 +162,7 @@ func TestQueryDataRaces_uniqueConnectionsToSameHandler(t *testing.T) { } func testQueryDataRacesSameHandler(t *testing.T, makeClientConn func(*baseapp.GRPCQueryRouter) *baseapp.QueryServiceTestHelper) { + t.Helper() t.Parallel() qr := baseapp.NewGRPCQueryRouter() diff --git a/baseapp/snapshot_test.go b/baseapp/snapshot_test.go index 3051177e47..6fe1c2e7b4 100644 --- a/baseapp/snapshot_test.go +++ b/baseapp/snapshot_test.go @@ -245,7 +245,6 @@ func TestABCI_OfferSnapshot_Errors(t *testing.T) { }, abci.ResponseOfferSnapshot_REJECT}, } for name, tc := range testCases { - tc := tc t.Run(name, func(t *testing.T) { resp, err := suite.baseApp.OfferSnapshot(&abci.RequestOfferSnapshot{Snapshot: tc.snapshot}) require.NoError(t, err) diff --git a/baseapp/streaming_test.go b/baseapp/streaming_test.go index 68ab1320ef..50011eacea 100644 --- a/baseapp/streaming_test.go +++ b/baseapp/streaming_test.go @@ -51,11 +51,12 @@ func TestABCI_MultiListener_StateChanges(t *testing.T) { addListenerOpt := func(bapp *baseapp.BaseApp) { bapp.CommitMultiStore().AddListeners([]storetypes.StoreKey{distKey1}) } suite := NewBaseAppSuite(t, anteOpt, distOpt, streamingManagerOpt, addListenerOpt) - suite.baseApp.InitChain( + _, err := suite.baseApp.InitChain( &abci.RequestInitChain{ ConsensusParams: &tmproto.ConsensusParams{}, }, ) + require.NoError(t, err) deliverKey := []byte("deliver-key") baseapptestutil.RegisterCounterServer(suite.baseApp.MsgServiceRouter(), CounterServerImpl{t, capKey1, deliverKey}) @@ -103,7 +104,8 @@ func TestABCI_MultiListener_StateChanges(t *testing.T) { // require.Equal(t, sdk.MarkEventsToIndex(counterEvent(sdk.EventTypeMessage, counter).ToABCIEvents(), map[string]struct{}{})[0], events[2], "msg handler update counter event") } - suite.baseApp.Commit() + _, err = suite.baseApp.Commit() + require.NoError(t, err) require.Equal(t, expectedChangeSet, mockListener1.ChangeSet, "should contain the same changeSet") require.Equal(t, expectedChangeSet, mockListener2.ChangeSet, "should contain the same changeSet") @@ -119,9 +121,10 @@ func Test_Ctx_with_StreamingManager(t *testing.T) { addListenerOpt := func(bapp *baseapp.BaseApp) { bapp.CommitMultiStore().AddListeners([]storetypes.StoreKey{distKey1}) } suite := NewBaseAppSuite(t, streamingManagerOpt, addListenerOpt) - suite.baseApp.InitChain(&abci.RequestInitChain{ + _, err := suite.baseApp.InitChain(&abci.RequestInitChain{ ConsensusParams: &tmproto.ConsensusParams{}, }) + require.NoError(t, err) ctx := getFinalizeBlockStateCtx(suite.baseApp) sm := ctx.StreamingManager() @@ -133,7 +136,8 @@ func Test_Ctx_with_StreamingManager(t *testing.T) { for blockN := 0; blockN < nBlocks; blockN++ { - suite.baseApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: int64(blockN) + 1}) + _, err := suite.baseApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: int64(blockN) + 1}) + require.NoError(t, err) ctx := getFinalizeBlockStateCtx(suite.baseApp) sm := ctx.StreamingManager() @@ -141,6 +145,7 @@ func Test_Ctx_with_StreamingManager(t *testing.T) { require.Equal(t, listeners, sm.ABCIListeners, fmt.Sprintf("should contain same listeners: %v", listeners)) require.Equal(t, true, sm.StopNodeOnErr, "should contain StopNodeOnErr = true") - suite.baseApp.Commit() + _, err = suite.baseApp.Commit() + require.NoError(t, err) } } diff --git a/baseapp/utils_test.go b/baseapp/utils_test.go index 1de526953f..6a280a7552 100644 --- a/baseapp/utils_test.go +++ b/baseapp/utils_test.go @@ -168,6 +168,8 @@ func incrementCounter(ctx context.Context, deliverKey []byte, msg sdk.Msg, ) (*baseapptestutil.MsgCreateCounterResponse, error) { + t.Helper() + sdkCtx := sdk.UnwrapSDKContext(ctx) store := sdkCtx.KVStore(capKey) @@ -210,6 +212,8 @@ func counterEvent(evType string, msgCount int64) sdk.Events { } func anteHandlerTxTest(t *testing.T, capKey storetypes.StoreKey, storeKey []byte) sdk.AnteHandler { + t.Helper() + return func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { store := ctx.KVStore(capKey) counter, failOnAnte := parseTxMemo(t, tx) @@ -233,6 +237,8 @@ func anteHandlerTxTest(t *testing.T, capKey storetypes.StoreKey, storeKey []byte } func incrementingCounter(t *testing.T, store storetypes.KVStore, counterKey []byte, counter int64) (*sdk.Result, error) { + t.Helper() + storedCounter := getIntFromStore(t, store, counterKey) require.Equal(t, storedCounter, counter) setIntOnStore(store, counterKey, counter+1) @@ -283,6 +289,8 @@ func (ps paramStore) Get(_ context.Context) (cmtproto.ConsensusParams, error) { } func setTxSignature(t *testing.T, builder client.TxBuilder, nonce uint64) { + t.Helper() + privKey := secp256k1.GenPrivKeyFromSecret([]byte("test")) pubKey := privKey.PubKey() err := builder.SetSignatures( @@ -296,6 +304,8 @@ func setTxSignature(t *testing.T, builder client.TxBuilder, nonce uint64) { } func testLoadVersionHelper(t *testing.T, app *baseapp.BaseApp, expectedHeight int64, expectedID storetypes.CommitID) { + t.Helper() + lastHeight := app.LastBlockHeight() lastID := app.LastCommitID() require.Equal(t, expectedHeight, lastHeight) @@ -317,6 +327,8 @@ func getFinalizeBlockStateCtx(app *baseapp.BaseApp) sdk.Context { } func parseTxMemo(t *testing.T, tx sdk.Tx) (counter int64, failOnAnte bool) { + t.Helper() + txWithMemo, ok := tx.(sdk.TxWithMemo) require.True(t, ok) @@ -332,6 +344,8 @@ func parseTxMemo(t *testing.T, tx sdk.Tx) (counter int64, failOnAnte bool) { } func newTxCounter(t *testing.T, cfg client.TxConfig, counter int64, msgCounters ...int64) signing.Tx { + t.Helper() + _, _, addr := testdata.KeyTestPubAddr() msgs := make([]sdk.Msg, 0, len(msgCounters)) for _, c := range msgCounters { @@ -340,7 +354,7 @@ func newTxCounter(t *testing.T, cfg client.TxConfig, counter int64, msgCounters } builder := cfg.NewTxBuilder() - builder.SetMsgs(msgs...) + require.NoError(t, builder.SetMsgs(msgs...)) builder.SetMemo("counter=" + strconv.FormatInt(counter, 10) + "&failOnAnte=false") setTxSignature(t, builder, uint64(counter)) @@ -348,6 +362,8 @@ func newTxCounter(t *testing.T, cfg client.TxConfig, counter int64, msgCounters } func getIntFromStore(t *testing.T, store storetypes.KVStore, key []byte) int64 { + t.Helper() + bz := store.Get(key) if len(bz) == 0 { return 0 @@ -360,8 +376,10 @@ func getIntFromStore(t *testing.T, store storetypes.KVStore, key []byte) int64 { } func setFailOnAnte(t *testing.T, cfg client.TxConfig, tx signing.Tx, failOnAnte bool) signing.Tx { + t.Helper() + builder := cfg.NewTxBuilder() - builder.SetMsgs(tx.GetMsgs()...) + require.NoError(t, builder.SetMsgs(tx.GetMsgs()...)) memo := tx.GetMemo() vals, err := url.ParseQuery(memo) @@ -387,12 +405,16 @@ func setFailOnHandler(cfg client.TxConfig, tx signing.Tx, fail bool) signing.Tx } } - builder.SetMsgs(msgs...) + if err := builder.SetMsgs(msgs...); err != nil { + panic(err) + } return builder.GetTx() } // wonkyMsg is to be used to run a MsgCounter2 message when the MsgCounter2 handler is not registered. func wonkyMsg(t *testing.T, cfg client.TxConfig, tx signing.Tx) signing.Tx { + t.Helper() + t.Helper() builder := cfg.NewTxBuilder() builder.SetMemo(tx.GetMemo()) diff --git a/client/config/config.go b/client/config/config.go index e3a2a8646d..bc428e45cc 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -75,7 +75,7 @@ func ReadFromClientConfig(ctx client.Context) (client.Context, error) { // when client.toml does not exist create and init with default values if _, err := os.Stat(configFilePath); os.IsNotExist(err) { if err := os.MkdirAll(configPath, os.ModePerm); err != nil { - return ctx, fmt.Errorf("couldn't make client config: %v", err) + return ctx, fmt.Errorf("couldn't make client config: %w", err) } if ctx.ChainID != "" { @@ -83,13 +83,13 @@ func ReadFromClientConfig(ctx client.Context) (client.Context, error) { } if err := writeConfigToFile(configFilePath, conf); err != nil { - return ctx, fmt.Errorf("could not write client config to the file: %v", err) + return ctx, fmt.Errorf("could not write client config to the file: %w", err) } } conf, err := getClientConfig(configPath, ctx.Viper) if err != nil { - return ctx, fmt.Errorf("couldn't get client config: %v", err) + return ctx, fmt.Errorf("couldn't get client config: %w", err) } // we need to update KeyringDir field on Client Context first cause it is used in NewKeyringFromBackend ctx = ctx.WithOutputFormat(conf.Output). @@ -106,7 +106,7 @@ func ReadFromClientConfig(ctx client.Context) (client.Context, error) { // https://github.com/cosmos/cosmos-sdk/issues/8986 client, err := client.NewClientFromNode(conf.Node) if err != nil { - return ctx, fmt.Errorf("couldn't get client from nodeURI: %v", err) + return ctx, fmt.Errorf("couldn't get client from nodeURI: %w", err) } ctx = ctx.WithNodeURI(conf.Node). diff --git a/client/debug/main.go b/client/debug/main.go index 1c02a2257d..70039e5049 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -16,7 +16,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" - legacybech32 "github.com/cosmos/cosmos-sdk/types/bech32/legacybech32" //nolint:staticcheck // we do old keys, they're keys after all. + "github.com/cosmos/cosmos-sdk/types/bech32/legacybech32" //nolint:staticcheck // retain for debug purposes "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/version" ) @@ -157,17 +157,17 @@ func getPubKeyFromRawString(pkstr, keytype string) (cryptotypes.PubKey, error) { } } - pk, err := legacybech32.UnmarshalPubKey(legacybech32.AccPK, pkstr) //nolint:staticcheck // we do old keys, they're keys after all. + pk, err := legacybech32.UnmarshalPubKey(legacybech32.AccPK, pkstr) if err == nil { return pk, nil } - pk, err = legacybech32.UnmarshalPubKey(legacybech32.ValPK, pkstr) //nolint:staticcheck // we do old keys, they're keys after all. + pk, err = legacybech32.UnmarshalPubKey(legacybech32.ValPK, pkstr) if err == nil { return pk, nil } - pk, err = legacybech32.UnmarshalPubKey(legacybech32.ConsPK, pkstr) //nolint:staticcheck // we do old keys, they're keys after all. + pk, err = legacybech32.UnmarshalPubKey(legacybech32.ConsPK, pkstr) if err == nil { return pk, nil } @@ -206,7 +206,7 @@ func PubkeyRawCmd() *cobra.Command { var consensusPub string edPK, ok := pk.(*ed25519.PubKey) if ok && pubkeyType == ed { - consensusPub, err = legacybech32.MarshalPubKey(legacybech32.ConsPK, edPK) //nolint:staticcheck // we do old keys, they're keys after all. + consensusPub, err = legacybech32.MarshalPubKey(legacybech32.ConsPK, edPK) if err != nil { return err } @@ -219,11 +219,11 @@ func PubkeyRawCmd() *cobra.Command { if err != nil { return err } - accPub, err := legacybech32.MarshalPubKey(legacybech32.AccPK, pk) //nolint:staticcheck // we do old keys, they're keys after all. + accPub, err := legacybech32.MarshalPubKey(legacybech32.AccPK, pk) if err != nil { return err } - valPub, err := legacybech32.MarshalPubKey(legacybech32.ValPK, pk) //nolint:staticcheck // we do old keys, they're keys after all. + valPub, err := legacybech32.MarshalPubKey(legacybech32.ValPK, pk) if err != nil { return err } diff --git a/client/flags/flags_test.go b/client/flags/flags_test.go index d9421f1986..657de9c0e6 100644 --- a/client/flags/flags_test.go +++ b/client/flags/flags_test.go @@ -22,7 +22,6 @@ func TestParseGasSetting(t *testing.T) { } for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { gs, err := flags.ParseGasSetting(tc.input) diff --git a/client/grpc/cmtservice/autocli.go b/client/grpc/cmtservice/autocli.go index 8fae4b915b..ea314c6f8c 100644 --- a/client/grpc/cmtservice/autocli.go +++ b/client/grpc/cmtservice/autocli.go @@ -51,7 +51,7 @@ var CometBFTAutoCLIDescriptor = &autocliv1.ServiceCommandDescriptor{ // NewCometBFTCommands is a fake `appmodule.Module` to be considered as a module // and be added in AutoCLI. -func NewCometBFTCommands() *cometModule { //nolint:revive // fake module and limiting import of core +func NewCometBFTCommands() *cometModule { return &cometModule{} } diff --git a/client/grpc_query_test.go b/client/grpc_query_test.go index 284f609302..e1fcd651e6 100644 --- a/client/grpc_query_test.go +++ b/client/grpc_query_test.go @@ -83,18 +83,19 @@ func (s *IntegrationTestSuite) SetupSuite() { s.NoError(err) // init chain will set the validator set and initialize the genesis accounts - app.InitChain(&abci.RequestInitChain{ + _, err = app.InitChain(&abci.RequestInitChain{ Validators: []abci.ValidatorUpdate{}, ConsensusParams: sims.DefaultConsensusParams, AppStateBytes: stateBytes, - }, - ) + }) + s.NoError(err) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, NextValidatorsHash: valSet.Hash(), }) + s.NoError(err) // end of app init diff --git a/client/keys/add.go b/client/keys/add.go index b64db8afdc..9e4744e137 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -375,7 +375,7 @@ func printCreate(cmd *cobra.Command, k *keyring.Record, showMnemonic bool, mnemo // print mnemonic unless requested not to. if showMnemonic { if _, err := fmt.Fprintf(cmd.ErrOrStderr(), "\n**Important** write this mnemonic phrase in a safe place.\nIt is the only way to recover your account if you ever forget your password.\n\n%s\n", mnemonic); err != nil { - return fmt.Errorf("failed to print mnemonic: %v", err) + return fmt.Errorf("failed to print mnemonic: %w", err) } } case flags.OutputFormatJSON: diff --git a/client/keys/add_ledger_test.go b/client/keys/add_ledger_test.go index 797c0452df..1c78bb75b3 100644 --- a/client/keys/add_ledger_test.go +++ b/client/keys/add_ledger_test.go @@ -163,7 +163,6 @@ func Test_runAddCmdLedgerDryRun(t *testing.T) { } for _, tt := range testData { - tt := tt t.Run(tt.name, func(t *testing.T) { cmd := AddKeyCommand() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) diff --git a/client/keys/add_test.go b/client/keys/add_test.go index ea02eb6b53..14c593c569 100644 --- a/client/keys/add_test.go +++ b/client/keys/add_test.go @@ -202,7 +202,6 @@ func Test_runAddCmdDryRun(t *testing.T) { }, } for _, tt := range testData { - tt := tt t.Run(tt.name, func(t *testing.T) { cmd := AddKeyCommand() cmd.Flags().AddFlagSet(Commands().PersistentFlags()) diff --git a/client/keys/list_test.go b/client/keys/list_test.go index 21f00cd0d4..6605c04696 100644 --- a/client/keys/list_test.go +++ b/client/keys/list_test.go @@ -20,6 +20,8 @@ import ( ) func cleanupKeys(t *testing.T, kb keyring.Keyring, keys ...string) func() { + t.Helper() + return func() { for _, k := range keys { if err := kb.Delete(k); err != nil { @@ -59,7 +61,6 @@ func Test_runListCmd(t *testing.T) { {"keybase: w/key", kbHome2, false}, } for _, tt := range testData { - tt := tt t.Run(tt.name, func(t *testing.T) { cmd.SetArgs([]string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, tt.kbDir), diff --git a/client/keys/parse_test.go b/client/keys/parse_test.go index 687922db3c..9f76c8c6a5 100644 --- a/client/keys/parse_test.go +++ b/client/keys/parse_test.go @@ -25,7 +25,6 @@ func TestParseKey(t *testing.T) { {"hex", []string{hexstr}, false}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { require.Equal(t, tt.wantErr, doParseKey(ParseKeyStringCommand(), config, tt.args) != nil) }) diff --git a/client/keys/show.go b/client/keys/show.go index fa1280a717..dc57d30deb 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -66,14 +66,14 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { if len(args) == 1 { k, err = fetchKey(clientCtx.Keyring, args[0]) if err != nil { - return fmt.Errorf("%s is not a valid name or address: %v", args[0], err) + return fmt.Errorf("%s is not a valid name or address: %w", args[0], err) } } else { pks := make([]cryptotypes.PubKey, len(args)) for i, keyref := range args { k, err := fetchKey(clientCtx.Keyring, keyref) if err != nil { - return fmt.Errorf("%s is not a valid name or address: %v", keyref, err) + return fmt.Errorf("%s is not a valid name or address: %w", keyref, err) } key, err := k.GetPubKey() if err != nil { diff --git a/client/keys/show_test.go b/client/keys/show_test.go index e86df5fb6c..286efeadc3 100644 --- a/client/keys/show_test.go +++ b/client/keys/show_test.go @@ -215,7 +215,6 @@ func Test_validateMultisigThreshold(t *testing.T) { {"1-2", args{2, 1}, true}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { if err := validateMultisigThreshold(tt.args.k, tt.args.nKeys); (err != nil) != tt.wantErr { t.Errorf("validateMultisigThreshold() error = %v, wantErr %v", err, tt.wantErr) @@ -241,7 +240,6 @@ func Test_getBechKeyOut(t *testing.T) { {"cons", args{sdk.PrefixConsensus}, MkConsKeyOutput, false}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got, err := getBechKeyOut(tt.args.bechPrefix) if tt.wantErr { diff --git a/client/snapshot/load.go b/client/snapshot/load.go index a1bf4e6382..0339ce4422 100644 --- a/client/snapshot/load.go +++ b/client/snapshot/load.go @@ -4,6 +4,7 @@ import ( "archive/tar" "bytes" "compress/gzip" + "errors" "fmt" "io" "os" @@ -77,7 +78,7 @@ func LoadArchiveCmd() *cobra.Command { for i := uint32(0); i < snapshot.Chunks; i++ { hdr, err = tr.Next() if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { break } return err diff --git a/client/tx/aux_builder_test.go b/client/tx/aux_builder_test.go index eb2d5abdb2..91d7ba913b 100644 --- a/client/tx/aux_builder_test.go +++ b/client/tx/aux_builder_test.go @@ -229,6 +229,8 @@ func TestAuxTxBuilder(t *testing.T) { // checkCorrectData that the auxSignerData's content matches the inputs we gave. func checkCorrectData(t *testing.T, cdc codec.Codec, auxSignerData typestx.AuxSignerData, signMode signing.SignMode) { + t.Helper() + pkAny, err := codectypes.NewAnyWithValue(pub1) require.NoError(t, err) msgAny, err := codectypes.NewAnyWithValue(msg1) diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index c234739293..190fbf4efe 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -74,7 +74,6 @@ func TestCalculateGas(t *testing.T) { } for _, tc := range testCases { - stc := tc txCfg, _ := newTestTxConfig() defaultSignMode, err := signing.APISignModeToInternal(txCfg.SignModeHandler().DefaultMode()) require.NoError(t, err) @@ -83,16 +82,16 @@ func TestCalculateGas(t *testing.T) { WithChainID("test-chain"). WithTxConfig(txCfg).WithSignMode(defaultSignMode) - t.Run(stc.name, func(t *testing.T) { + t.Run(tc.name, func(t *testing.T) { mockClientCtx := mockContext{ gasUsed: tc.args.mockGasUsed, wantErr: tc.args.mockWantErr, } - simRes, gotAdjusted, err := CalculateGas(mockClientCtx, txf.WithGasAdjustment(stc.args.adjustment)) - if stc.expPass { + simRes, gotAdjusted, err := CalculateGas(mockClientCtx, txf.WithGasAdjustment(tc.args.adjustment)) + if tc.expPass { require.NoError(t, err) - require.Equal(t, simRes.GasInfo.GasUsed, stc.wantEstimate) - require.Equal(t, gotAdjusted, stc.wantAdjusted) + require.Equal(t, simRes.GasInfo.GasUsed, tc.wantEstimate) + require.Equal(t, gotAdjusted, tc.wantAdjusted) require.NotNil(t, simRes.Result) } else { require.Error(t, err) diff --git a/client/utils_test.go b/client/utils_test.go index c8cb93a9f5..61bfb429cc 100644 --- a/client/utils_test.go +++ b/client/utils_test.go @@ -67,7 +67,6 @@ func TestPaginate(t *testing.T) { } for i, tc := range testCases { - i, tc := i, tc t.Run(tc.name, func(t *testing.T) { start, end := client.Paginate(tc.numObjs, tc.page, tc.limit, tc.defLimit) require.Equal(t, tc.expectedStart, start, "invalid result; test case #%d", i) diff --git a/client/v2/autocli/common_test.go b/client/v2/autocli/common_test.go index bcd1436042..9726dcb31b 100644 --- a/client/v2/autocli/common_test.go +++ b/client/v2/autocli/common_test.go @@ -48,7 +48,7 @@ func initFixture(t *testing.T) *fixture { } }() - clientConn, err := grpc.Dial(listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials())) + clientConn, err := grpc.NewClient(listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials())) assert.NilError(t, err) encodingConfig := moduletestutil.MakeTestEncodingConfig(bank.AppModuleBasic{}) diff --git a/client/v2/autocli/keyring/keyring.go b/client/v2/autocli/keyring/keyring.go index 601163aac6..b0646fcd5e 100644 --- a/client/v2/autocli/keyring/keyring.go +++ b/client/v2/autocli/keyring/keyring.go @@ -14,13 +14,14 @@ var KeyringContextKey struct{} var _ Keyring = &KeyringImpl{} -type KeyringImpl struct { //nolint:revive // stuttering is fine +type KeyringImpl struct { k Keyring } // NewKeyringInContext returns a new context with the keyring set. func NewKeyringInContext(ctx context.Context, k Keyring) context.Context { - return context.WithValue(ctx, KeyringContextKey, NewKeyringImpl(k)) + // TODO: should this be fixed? + return context.WithValue(ctx, KeyringContextKey, NewKeyringImpl(k)) //nolint:staticcheck // we can ignore this safely until we make a fix for this } func NewKeyringImpl(k Keyring) *KeyringImpl { diff --git a/client/v2/internal/strcase/kebab_test.go b/client/v2/internal/strcase/kebab_test.go index 1c82f3ab3b..c58cc70179 100644 --- a/client/v2/internal/strcase/kebab_test.go +++ b/client/v2/internal/strcase/kebab_test.go @@ -8,7 +8,9 @@ import ( "cosmossdk.io/client/v2/internal/strcase" ) -func toKebab(t testing.TB) { +func toKebab(tb testing.TB) { + tb.Helper() + cases := [][]string{ {"testCase", "test-case"}, {"TestCase", "test-case"}, @@ -28,7 +30,7 @@ func toKebab(t testing.TB) { in := i[0] out := i[1] result := strcase.ToKebab(in) - assert.Equal(t, out, result, "ToKebab(%s) = %s, want %s", in, result, out) + assert.Equal(tb, out, result, "ToKebab(%s) = %s, want %s", in, result, out) } } diff --git a/codec/amino_codec_test.go b/codec/amino_codec_test.go index 2f25b0a045..74116fbfb6 100644 --- a/codec/amino_codec_test.go +++ b/codec/amino_codec_test.go @@ -71,7 +71,6 @@ func TestAminoCodecMarshalJSONIndent(t *testing.T) { } for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { cdc := codec.NewAminoCodec(createTestCodec()) bz, err := cdc.MarshalJSONIndent(tc.input, "", " ") diff --git a/codec/codec_common_test.go b/codec/codec_common_test.go index 33cbe059f1..cb0fba9311 100644 --- a/codec/codec_common_test.go +++ b/codec/codec_common_test.go @@ -92,7 +92,9 @@ func testMarshaling(t *testing.T, cdc interface { codec.JSONCodec }, ) { - any, err := types.NewAnyWithValue(&testdata.Dog{Name: "rufus"}) + t.Helper() + + cdcAny, err := types.NewAnyWithValue(&testdata.Dog{Name: "rufus"}) require.NoError(t, err) testCases := []testCase{ @@ -113,8 +115,8 @@ func testMarshaling(t *testing.T, cdc interface { if _, ok := cdc.(*codec.AminoCodec); ok { testCases = append(testCases, testCase{ "any marshaling", - &testdata.HasAnimal{Animal: any}, - &testdata.HasAnimal{Animal: any}, + &testdata.HasAnimal{Animal: cdcAny}, + &testdata.HasAnimal{Animal: cdcAny}, false, false, }) diff --git a/codec/types/any.go b/codec/types/any.go index bef5441fd1..557cda0687 100644 --- a/codec/types/any.go +++ b/codec/types/any.go @@ -11,7 +11,6 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// nolint:revive // XXX is reqired for proto compatibility type Any struct { // A URL/resource name that uniquely identifies the type of the serialized // protocol buffer message. This string must contain at least diff --git a/codec/types/any_internal_test.go b/codec/types/any_internal_test.go index f413f95528..9adab29466 100644 --- a/codec/types/any_internal_test.go +++ b/codec/types/any_internal_test.go @@ -17,7 +17,7 @@ func (d Dog) Greet() string { return d.Name } func (d *Dog) Reset() { d.Name = "" } func (d *Dog) String() string { return d.Name } func (d *Dog) ProtoMessage() {} -func (d *Dog) XXX_MessageName() string { return "tests/dog" } //nolint:revive // XXX_ prefix is required +func (d *Dog) XXX_MessageName() string { return "tests/dog" } type Animal interface { Greet() string diff --git a/codec/types/any_test.go b/codec/types/any_test.go index 06c0f5b418..5e2b29fcca 100644 --- a/codec/types/any_test.go +++ b/codec/types/any_test.go @@ -19,7 +19,7 @@ var _ proto.Message = (*errOnMarshal)(nil) var errAlways = fmt.Errorf("always erroring") -func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { //nolint:revive // XXX_ prefix is intentional +func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return nil, errAlways } diff --git a/codec/types/types_test.go b/codec/types/types_test.go index 4bb3f7d609..dddacfe18b 100644 --- a/codec/types/types_test.go +++ b/codec/types/types_test.go @@ -44,7 +44,7 @@ var ( func (dog FakeDog) Reset() {} func (dog FakeDog) String() string { return "fakedog" } func (dog FakeDog) ProtoMessage() {} -func (dog FakeDog) XXX_MessageName() string { return proto.MessageName(&testdata.Dog{}) } //nolint:revive // XXX_ prefix is intentional +func (dog FakeDog) XXX_MessageName() string { return proto.MessageName(&testdata.Dog{}) } func (dog FakeDog) Greet() string { return "fakedog" } func TestRegister(t *testing.T) { diff --git a/codec/unknownproto/benchmarks_test.go b/codec/unknownproto/benchmarks_test.go index 0cf44b4e76..114e4e688f 100644 --- a/codec/unknownproto/benchmarks_test.go +++ b/codec/unknownproto/benchmarks_test.go @@ -51,6 +51,7 @@ func BenchmarkRejectUnknownFields_parallel(b *testing.B) { } func benchmarkRejectUnknownFields(b *testing.B, parallel bool) { + b.Helper() b.ReportAllocs() if !parallel { @@ -89,6 +90,7 @@ func BenchmarkProtoUnmarshal_parallel(b *testing.B) { } func benchmarkProtoUnmarshal(b *testing.B, parallel bool) { + b.Helper() b.ReportAllocs() if !parallel { diff --git a/codec/unknownproto/unit_helpers_test.go b/codec/unknownproto/unit_helpers_test.go index 9c408a6d1f..b156422489 100644 --- a/codec/unknownproto/unit_helpers_test.go +++ b/codec/unknownproto/unit_helpers_test.go @@ -22,7 +22,6 @@ func TestWireTypeToString(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(fmt.Sprintf("wireType=%d", tt.typ), func(t *testing.T) { if g, w := wireTypeToString(tt.typ), tt.want; g != w { t.Fatalf("Mismatch:\nGot: %q\nWant: %q\n", g, w) diff --git a/codec/unknownproto/unknown_fields_test.go b/codec/unknownproto/unknown_fields_test.go index 7f2228e584..85338f0595 100644 --- a/codec/unknownproto/unknown_fields_test.go +++ b/codec/unknownproto/unknown_fields_test.go @@ -223,7 +223,6 @@ func TestRejectUnknownFieldsRepeated(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { protoBlob, err := proto.Marshal(tt.in) if err != nil { @@ -280,7 +279,6 @@ func TestRejectUnknownFields_allowUnknownNonCriticals(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { blob, err := proto.Marshal(tt.in) if err != nil { @@ -483,7 +481,6 @@ func TestRejectUnknownFieldsNested(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { protoBlob, err := proto.Marshal(tt.in) if err != nil { @@ -634,7 +631,6 @@ func TestRejectUnknownFieldsFlat(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { blob, err := proto.Marshal(tt.in) if err != nil { diff --git a/crypto/armor.go b/crypto/armor.go index aab662161c..20847e07ac 100644 --- a/crypto/armor.go +++ b/crypto/armor.go @@ -3,6 +3,7 @@ package crypto import ( "bytes" "encoding/hex" + "errors" "fmt" "io" @@ -104,7 +105,7 @@ func UnarmorInfoBytes(armorStr string) ([]byte, error) { func UnarmorPubKeyBytes(armorStr string) (bz []byte, algo string, err error) { bz, header, err := unarmorBytes(armorStr, blockTypePubKey) if err != nil { - return nil, "", fmt.Errorf("couldn't unarmor bytes: %v", err) + return nil, "", fmt.Errorf("couldn't unarmor bytes: %w", err) } switch header[headerVersion] { @@ -240,7 +241,7 @@ func decryptPrivKey(saltBytes, encBytes []byte, passphrase, kdf string) (privKey key = crypto.Sha256(key) // Get 32 bytes privKeyBytes, err = xsalsa20symmetric.DecryptSymmetric(encBytes, key) - if err == xsalsa20symmetric.ErrCiphertextDecrypt { + if errors.Is(err, xsalsa20symmetric.ErrCiphertextDecrypt) { return privKey, sdkerrors.ErrWrongPassword } default: @@ -261,15 +262,15 @@ func EncodeArmor(blockType string, headers map[string]string, data []byte) strin buf := new(bytes.Buffer) w, err := armor.Encode(buf, blockType, headers) if err != nil { - panic(fmt.Errorf("could not encode ascii armor: %s", err)) + panic(fmt.Errorf("could not encode ascii armor: %w", err)) } _, err = w.Write(data) if err != nil { - panic(fmt.Errorf("could not encode ascii armor: %s", err)) + panic(fmt.Errorf("could not encode ascii armor: %w", err)) } err = w.Close() if err != nil { - panic(fmt.Errorf("could not encode ascii armor: %s", err)) + panic(fmt.Errorf("could not encode ascii armor: %w", err)) } return buf.String() } diff --git a/crypto/armor_test.go b/crypto/armor_test.go index f774165ae4..1b98f5add8 100644 --- a/crypto/armor_test.go +++ b/crypto/armor_test.go @@ -43,7 +43,7 @@ func TestArmorUnarmorPrivKey(t *testing.T) { // empty string decrypted, algo, err = crypto.UnarmorDecryptPrivKey("", "passphrase") require.Error(t, err) - require.True(t, errors.Is(io.EOF, err)) + require.True(t, errors.Is(err, io.EOF)) require.Nil(t, decrypted) require.Empty(t, algo) @@ -165,7 +165,7 @@ func TestArmorInfoBytes(t *testing.T) { func TestUnarmorInfoBytesErrors(t *testing.T) { unarmoredBytes, err := crypto.UnarmorInfoBytes("") require.Error(t, err) - require.True(t, errors.Is(io.EOF, err)) + require.True(t, errors.Is(err, io.EOF)) require.Nil(t, unarmoredBytes) header := map[string]string{ diff --git a/crypto/hd/fundraiser_test.go b/crypto/hd/fundraiser_test.go index 654ac56258..37cb1eff16 100644 --- a/crypto/hd/fundraiser_test.go +++ b/crypto/hd/fundraiser_test.go @@ -29,6 +29,8 @@ func TestFullFundraiserPath(t *testing.T) { } func initFundraiserTestVectors(t *testing.T) []addrData { + t.Helper() + // NOTE: atom fundraiser address // var hdPath string = "m/44'/118'/0'/0/0" var hdToAddrTable []addrData diff --git a/crypto/hd/hdpath_test.go b/crypto/hd/hdpath_test.go index 7b9816fd0b..945638b990 100644 --- a/crypto/hd/hdpath_test.go +++ b/crypto/hd/hdpath_test.go @@ -106,9 +106,7 @@ func TestCreateHDPath(t *testing.T) { {"m/44'/114'/1'/1/0", args{114, 1, 1}, hd.BIP44Params{Purpose: 44, CoinType: 114, Account: 1, AddressIndex: 1}}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - tt := tt require.Equal(t, tt.want, *hd.CreateHDPath(tt.args.coinType, tt.args.account, tt.args.index)) }) } @@ -169,7 +167,6 @@ func TestDeriveHDPathRange(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.path, func(t *testing.T) { master, ch := hd.ComputeMastersFromSeed(seed) _, err := hd.DerivePrivateKeyForPath(master, ch, tt.path) @@ -298,7 +295,6 @@ func TestDerivePrivateKeyForPathDoNotCrash(t *testing.T) { } for _, path := range paths { - path := path t.Run(path, func(t *testing.T) { _, _ = hd.DerivePrivateKeyForPath([32]byte{}, [32]byte{}, path) }) diff --git a/crypto/keyring/keyring.go b/crypto/keyring/keyring.go index 4336772547..d8fe412d33 100644 --- a/crypto/keyring/keyring.go +++ b/crypto/keyring/keyring.go @@ -530,7 +530,7 @@ func (ks keystore) KeyByAddress(address sdk.Address) (*Record, error) { } func wrapKeyNotFound(err error, msg string) error { - if err == keyring.ErrKeyNotFound { + if errors.Is(err, keyring.ErrKeyNotFound) { return errorsmod.Wrap(sdkerrors.ErrKeyNotFound, msg) } return err @@ -628,7 +628,7 @@ func SignWithLedger(k *Record, msg []byte, signMode signing.SignMode) (sig []byt priv, err := ledger.NewPrivKeySecp256k1Unsafe(*path) if err != nil { - return + return nil, nil, err } ledgerPubKey := priv.PubKey() pubKey, err := k.GetPubKey() diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 847c830a81..85f0fbf671 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -930,7 +930,8 @@ func TestImportPubKey(t *testing.T) { if tt.expectedErr == nil { require.NoError(t, err) } else { - require.Equal(t, err, tt.expectedErr) + require.Error(t, err) + require.Contains(t, err.Error(), tt.expectedErr.Error()) } }) } @@ -2037,6 +2038,8 @@ func TestChangeBcrypt(t *testing.T) { } func requireEqualRenamedKey(t *testing.T, key, mnemonic *Record, nameMatch bool) { + t.Helper() + if nameMatch { require.Equal(t, key.Name, mnemonic.Name) } @@ -2055,6 +2058,8 @@ func requireEqualRenamedKey(t *testing.T, key, mnemonic *Record, nameMatch bool) } func newKeyring(t *testing.T, name string) Keyring { + t.Helper() + cdc := getCodec() kr, err := New(name, "test", t.TempDir(), nil, cdc) require.NoError(t, err) @@ -2062,12 +2067,16 @@ func newKeyring(t *testing.T, name string) Keyring { } func newKeyRecord(t *testing.T, kr Keyring, name string) *Record { + t.Helper() + k, _, err := kr.NewMnemonic(name, English, sdk.FullFundraiserPath, DefaultBIP39Passphrase, hd.Secp256k1) require.NoError(t, err) return k } func assertKeysExist(t *testing.T, kr Keyring, names ...string) { + t.Helper() + for _, n := range names { _, err := kr.Key(n) require.NoError(t, err) diff --git a/crypto/keyring/signing_algorithms_test.go b/crypto/keyring/signing_algorithms_test.go index 624e491d09..1ac7d9cc35 100644 --- a/crypto/keyring/signing_algorithms_test.go +++ b/crypto/keyring/signing_algorithms_test.go @@ -36,7 +36,6 @@ func TestNewSigningAlgoByString(t *testing.T) { list := SigningAlgoList{hd.Secp256k1} for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { algorithm, err := NewSigningAlgoFromString(tt.algoStr, list) if tt.isSupported { diff --git a/crypto/keys/multisig/amino.go b/crypto/keys/multisig/amino.go index 1973a31a66..459c4fc05d 100644 --- a/crypto/keys/multisig/amino.go +++ b/crypto/keys/multisig/amino.go @@ -66,7 +66,7 @@ func tmToProto(tmPk tmMultisig) (*LegacyAminoPubKey, error) { } // MarshalAminoJSON overrides amino JSON unmarshaling. -func (m LegacyAminoPubKey) MarshalAminoJSON() (tmMultisig, error) { //nolint:golint,revive // we need to override the default amino JSON marshaling +func (m LegacyAminoPubKey) MarshalAminoJSON() (tmMultisig, error) { return protoToTm(&m) } diff --git a/crypto/keys/secp256k1/secp256k1.go b/crypto/keys/secp256k1/secp256k1.go index c9c4864339..f520bde4d6 100644 --- a/crypto/keys/secp256k1/secp256k1.go +++ b/crypto/keys/secp256k1/secp256k1.go @@ -10,7 +10,7 @@ import ( "github.com/cometbft/cometbft/crypto" secp256k1 "github.com/decred/dcrd/dcrec/secp256k1/v4" - "golang.org/x/crypto/ripemd160" //nolint: staticcheck // keep around for backwards compatibility + "golang.org/x/crypto/ripemd160" //nolint // using just for backwards compat errorsmod "cosmossdk.io/errors" @@ -158,9 +158,9 @@ func (pubKey *PubKey) Address() crypto.Address { } sha := sha256.Sum256(pubKey.Key) - hasherRIPEMD160 := ripemd160.New() - hasherRIPEMD160.Write(sha[:]) // does not error - return crypto.Address(hasherRIPEMD160.Sum(nil)) + hasherRIPEMD160 := ripemd160.New() //nolint:gosec // keeping around for backwards compatibility + hasherRIPEMD160.Write(sha[:]) // does not error + return hasherRIPEMD160.Sum(nil) } // Bytes returns the pubkey byte format. diff --git a/crypto/keys/secp256k1/secp256k1_internal_test.go b/crypto/keys/secp256k1/secp256k1_internal_test.go index 539420d00e..b2360d7552 100644 --- a/crypto/keys/secp256k1/secp256k1_internal_test.go +++ b/crypto/keys/secp256k1/secp256k1_internal_test.go @@ -27,7 +27,6 @@ func Test_genPrivKey(t *testing.T) { {"valid because 0 < 1 < N", validOne, false}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { if tt.shouldPanic { require.Panics(t, func() { diff --git a/crypto/keys/secp256k1/secp256k1_test.go b/crypto/keys/secp256k1/secp256k1_test.go index 299bbfcefc..a1cd922547 100644 --- a/crypto/keys/secp256k1/secp256k1_test.go +++ b/crypto/keys/secp256k1/secp256k1_test.go @@ -255,7 +255,6 @@ func TestGenPrivKeyFromSecret(t *testing.T) { {"another seed used in cosmos tests #3", []byte("")}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { gotPrivKey := secp256k1.GenPrivKeyFromSecret(tt.secret) require.NotNil(t, gotPrivKey) diff --git a/crypto/ledger/encode_test.go b/crypto/ledger/encode_test.go index 6f428f8798..a181f1fa5f 100644 --- a/crypto/ledger/encode_test.go +++ b/crypto/ledger/encode_test.go @@ -9,6 +9,8 @@ import ( ) func checkAminoJSON(t *testing.T, src, dst interface{}, isNil bool) { + t.Helper() + // Marshal to JSON bytes. js, err := cdc.MarshalJSON(src) require.Nil(t, err, "%+v", err) diff --git a/crypto/ledger/ledger_mock.go b/crypto/ledger/ledger_mock.go index 1398f6cd67..93b9903e13 100644 --- a/crypto/ledger/ledger_mock.go +++ b/crypto/ledger/ledger_mock.go @@ -74,7 +74,7 @@ func (mock LedgerSECP256K1Mock) GetAddressPubKeySECP256K1(derivationPath []uint3 // re-serialize in the 33-byte compressed format cmp, err := secp.ParsePubKey(pk) if err != nil { - return nil, "", fmt.Errorf("error parsing public key: %v", err) + return nil, "", fmt.Errorf("error parsing public key: %w", err) } compressedPublicKey := make([]byte, csecp256k1.PubKeySize) diff --git a/crypto/ledger/ledger_secp256k1.go b/crypto/ledger/ledger_secp256k1.go index e0f4a4d94a..8c944d669e 100644 --- a/crypto/ledger/ledger_secp256k1.go +++ b/crypto/ledger/ledger_secp256k1.go @@ -316,13 +316,13 @@ func sign(device SECP256K1, pkl PrivKeyLedgerSecp256k1, msg []byte, p2 byte) ([] func getPubKeyUnsafe(device SECP256K1, path hd.BIP44Params) (types.PubKey, error) { publicKey, err := device.GetPublicKeySECP256K1(path.DerivationPath()) if err != nil { - return nil, fmt.Errorf("please open the %v app on the Ledger device - error: %v", options.appName, err) + return nil, fmt.Errorf("please open the %v app on the Ledger device - error: %w", options.appName, err) } // re-serialize in the 33-byte compressed format cmp, err := secp.ParsePubKey(publicKey) if err != nil { - return nil, fmt.Errorf("error parsing public key: %v", err) + return nil, fmt.Errorf("error parsing public key: %w", err) } compressedPublicKey := make([]byte, secp256k1.PubKeySize) @@ -352,7 +352,7 @@ func getPubKeyAddrSafe(device SECP256K1, path hd.BIP44Params, hrp string) (types // re-serialize in the 33-byte compressed format cmp, err := secp.ParsePubKey(publicKey) if err != nil { - return nil, "", fmt.Errorf("error parsing public key: %v", err) + return nil, "", fmt.Errorf("error parsing public key: %w", err) } compressedPublicKey := make([]byte, secp256k1.PubKeySize) diff --git a/crypto/ledger/ledger_test.go b/crypto/ledger/ledger_test.go index 6371ea13ce..3e1805c105 100644 --- a/crypto/ledger/ledger_test.go +++ b/crypto/ledger/ledger_test.go @@ -32,6 +32,8 @@ func TestPublicKeyUnsafe(t *testing.T) { } func checkDefaultPubKey(t *testing.T, priv types.LedgerPrivKey) { + t.Helper() + require.NotNil(t, priv) expectedPkStr := "PubKeySecp256k1{034FEF9CD7C4C63588D3B03FEB5281B9D232CBA34D6F3D71AEE59211FFBFE1FE87}" require.Equal(t, "eb5ae98721034fef9cd7c4c63588d3b03feb5281b9d232cba34d6f3d71aee59211ffbfe1fe87", diff --git a/crypto/types/compact_bit_array_test.go b/crypto/types/compact_bit_array_test.go index 4b148138e2..1f7f276cff 100644 --- a/crypto/types/compact_bit_array_test.go +++ b/crypto/types/compact_bit_array_test.go @@ -206,8 +206,6 @@ func TestCompactBitArrayNumOfTrueBitsBefore(t *testing.T) { {`"______________xx"`, []int{14, 15}, []int{0, 1}}, } for tcIndex, tc := range testCases { - - tcIndex := tcIndex t.Run(tc.marshalledBA, func(t *testing.T) { var bA *CompactBitArray err := json.Unmarshal([]byte(tc.marshalledBA), &bA) @@ -280,7 +278,6 @@ func TestNewCompactBitArrayCrashWithLimits(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(fmt.Sprintf("%d", tt.in), func(t *testing.T) { got := NewCompactBitArray(tt.in) if g := got != nil; g != tt.mustPass { diff --git a/depinject/internal/codegen/file.go b/depinject/internal/codegen/file.go index 09a1a61096..16ed6dde2d 100644 --- a/depinject/internal/codegen/file.go +++ b/depinject/internal/codegen/file.go @@ -39,11 +39,11 @@ func NewFileGen(file *ast.File, codegenPkgPath string) (*FileGen, error) { g.idents[decl.Name.Name] = true case *ast.GenDecl: for _, spec := range decl.Specs { - switch spec := spec.(type) { + switch specType := spec.(type) { case *ast.TypeSpec: - g.idents[spec.Name.Name] = true + g.idents[specType.Name.Name] = true case *ast.ValueSpec: - for _, name := range spec.Names { + for _, name := range specType.Names { g.idents[name.Name] = true } } diff --git a/internal/util.go b/internal/util.go index 97e3b4d165..2601a466c7 100644 --- a/internal/util.go +++ b/internal/util.go @@ -7,7 +7,7 @@ import ( func CombineErrors(ret, also error, desc string) error { if also != nil { if ret != nil { - ret = fmt.Errorf("%w; %v: %v", ret, desc, also) + ret = fmt.Errorf("%w; %v: %w", ret, desc, also) } else { ret = also } diff --git a/runtime/app.go b/runtime/app.go index 890b1a5a87..00e3617f2e 100644 --- a/runtime/app.go +++ b/runtime/app.go @@ -82,8 +82,8 @@ func (a *App) RegisterModules(modules ...module.AppModule) error { if module, ok := appModule.(module.HasServices); ok { module.RegisterServices(a.configurator) - } else if module, ok := appModule.(appmodule.HasServices); ok { - if err := module.RegisterServices(a.configurator); err != nil { + } else if innerMod, ok := appModule.(appmodule.HasServices); ok { + if err := innerMod.RegisterServices(a.configurator); err != nil { return err } } @@ -178,12 +178,12 @@ func (a *App) EndBlocker(ctx sdk.Context) (sdk.EndBlock, error) { // Precommiter application updates every commit func (a *App) Precommiter(ctx sdk.Context) { - a.ModuleManager.Precommit(ctx) + _ = a.ModuleManager.Precommit(ctx) } // PrepareCheckStater application updates every commit func (a *App) PrepareCheckStater(ctx sdk.Context) { - a.ModuleManager.PrepareCheckState(ctx) + _ = a.ModuleManager.PrepareCheckState(ctx) } // InitChainer initializes the chain. diff --git a/scripts/go-lint-changes.bash b/scripts/go-lint-changes.bash deleted file mode 100755 index 4e8a8ecb82..0000000000 --- a/scripts/go-lint-changes.bash +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash - -set -e -o pipefail - - -LINT_TAGS="e2e,ledger,test_ledger_mock,system_test,sims" -export LINT_TAGS - -REPO_ROOT="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )/.." &> /dev/null && pwd )" -export REPO_ROOT - -lint_module() { - local root="$1" - shift - cd "$(dirname "$root")" && - echo "linting $(grep "^module" go.mod) [$(date -Iseconds -u)]" && - golangci-lint run ./... -c "${REPO_ROOT}/.golangci.yml" "$@" --new --build-tags=${LINT_TAGS} -} -export -f lint_module - -# if LINT_DIFF env is set, only lint the files in the current commit otherwise lint all files -if [[ -z "${LINT_DIFF:-}" ]]; then - find "${REPO_ROOT}" -type f -name go.mod -print0 | - xargs -0 -I{} bash -c 'lint_module "$@"' _ {} "$@" -else - if [[ -z $GIT_DIFF ]]; then - GIT_DIFF=$(git diff --name-only --diff-filter=d | grep \.go$ | grep -v \.pb\.go$) || true - fi - - if [[ -z "$GIT_DIFF" ]]; then - echo "no files to lint" - exit 0 - fi - - for f in $(dirname $(echo "$GIT_DIFF" | tr -d "'") | uniq); do - echo "linting $f [$(date -Iseconds -u)]" && - cd $f && - golangci-lint run ./... -c "${REPO_ROOT}/.golangci.yml" "$@" --new --build-tags=${LINT_TAGS} && - cd $REPO_ROOT - done -fi \ No newline at end of file diff --git a/server/api/server_test.go b/server/api/server_test.go index 34b51bf489..85e46ccfc2 100644 --- a/server/api/server_test.go +++ b/server/api/server_test.go @@ -5,6 +5,7 @@ import ( "bytes" "encoding/base64" "encoding/binary" + "errors" "fmt" "io" "net/http" @@ -221,18 +222,18 @@ func (s *GRPCWebTestSuite) makeGrpcRequest( for { grpcPreamble := []byte{0, 0, 0, 0, 0} readCount, err := reader.Read(grpcPreamble) - if err == io.EOF { + if errors.Is(err, io.EOF) { break } if readCount != 5 || err != nil { - return nil, Trailer{}, nil, fmt.Errorf("Unexpected end of body in preamble: %v", err) + return nil, Trailer{}, nil, fmt.Errorf("unexpected end of body in preamble: %w", err) } payloadLength := binary.BigEndian.Uint32(grpcPreamble[1:]) payloadBytes := make([]byte, payloadLength) readCount, err = reader.Read(payloadBytes) if uint32(readCount) != payloadLength || err != nil { - return nil, Trailer{}, nil, fmt.Errorf("Unexpected end of msg: %v", err) + return nil, Trailer{}, nil, fmt.Errorf("unexpected end of msg: %w", err) } if grpcPreamble[0]&(1<<7) == (1 << 7) { // MSB signifies the trailer parser trailers = readTrailersFromBytes(s.T(), payloadBytes) @@ -244,6 +245,8 @@ func (s *GRPCWebTestSuite) makeGrpcRequest( } func readTrailersFromBytes(t *testing.T, dataBytes []byte) Trailer { + t.Helper() + bufferReader := bytes.NewBuffer(dataBytes) tp := textproto.NewReader(bufio.NewReader(bufferReader)) @@ -262,7 +265,7 @@ func readTrailersFromBytes(t *testing.T, dataBytes []byte) Trailer { // Second, replace header names because gRPC Web trailer names must be lower-case. for { line, err := tp.ReadLine() - if err == io.EOF { + if errors.Is(err, io.EOF) { break } require.NoError(t, err, "failed to read header line") diff --git a/server/export_test.go b/server/export_test.go index d1dad66aaa..f86e7a5ca7 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -93,6 +93,8 @@ func (s *ExportSystem) Run(args ...string) cmdtest.RunResult { // MustRun wraps (*cmdtest.System).MustRunC, providing e's context. func (s *ExportSystem) MustRun(t *testing.T, args ...string) cmdtest.RunResult { + t.Helper() + return s.sys.MustRunC(t, s.Ctx, args...) } diff --git a/server/grpc/gogoreflection/serverreflection.go b/server/grpc/gogoreflection/serverreflection.go index fd48aa416b..963cf0cd79 100644 --- a/server/grpc/gogoreflection/serverreflection.go +++ b/server/grpc/gogoreflection/serverreflection.go @@ -39,6 +39,7 @@ package gogoreflection // import "google.golang.org/grpc/reflection" import ( "bytes" "compress/gzip" + "errors" "fmt" "io" "log" @@ -188,7 +189,7 @@ func fqn(prefix, name string) string { // fileDescForType gets the file descriptor for the given type. // The given type should be a proto message. func (s *serverReflectionServer) fileDescForType(st reflect.Type) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(protoMessage) + m, ok := reflect.Zero(reflect.PointerTo(st)).Interface().(protoMessage) if !ok { return nil, fmt.Errorf("failed to create message from type: %v", st) } @@ -202,12 +203,12 @@ func (s *serverReflectionServer) fileDescForType(st reflect.Type) (*dpb.FileDesc func decodeFileDesc(enc []byte) (*dpb.FileDescriptorProto, error) { raw, err := decompress(enc) if err != nil { - return nil, fmt.Errorf("failed to decompress enc: %v", err) + return nil, fmt.Errorf("failed to decompress enc: %w", err) } fd := new(dpb.FileDescriptorProto) if err := proto.Unmarshal(raw, fd); err != nil { - return nil, fmt.Errorf("bad descriptor: %v", err) + return nil, fmt.Errorf("bad descriptor: %w", err) } return fd, nil } @@ -216,11 +217,11 @@ func decodeFileDesc(enc []byte) (*dpb.FileDescriptorProto, error) { func decompress(b []byte) ([]byte, error) { r, err := gzip.NewReader(bytes.NewReader(b)) if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) + return nil, fmt.Errorf("bad gzipped descriptor: %w", err) } out, err := io.ReadAll(r) if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) + return nil, fmt.Errorf("bad gzipped descriptor: %w", err) } return out, nil } @@ -236,7 +237,7 @@ func typeForName(name string) (reflect.Type, error) { } func fileDescContainingExtension(st reflect.Type, ext int32) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) + m, ok := reflect.Zero(reflect.PointerTo(st)).Interface().(proto.Message) if !ok { return nil, fmt.Errorf("failed to create message from type: %v", st) } @@ -251,7 +252,7 @@ func fileDescContainingExtension(st reflect.Type, ext int32) (*dpb.FileDescripto } func (s *serverReflectionServer) allExtensionNumbersForType(st reflect.Type) ([]int32, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) + m, ok := reflect.Zero(reflect.PointerTo(st)).Interface().(proto.Message) if !ok { return nil, fmt.Errorf("failed to create message from type: %v", st) } @@ -380,7 +381,7 @@ func (s *serverReflectionServer) ServerReflectionInfo(stream rpb.ServerReflectio sentFileDescriptors := make(map[string]bool) for { in, err := stream.Recv() - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } if err != nil { diff --git a/server/mock/app.go b/server/mock/app.go index 3b42051660..f090f8c6df 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -153,7 +153,7 @@ type MsgServerImpl struct { capKeyMainStore *storetypes.KVStoreKey } -func MsgTestHandler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // nolint: revive // refactor this in a followup pr +func MsgTestHandler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(KVStoreTx) if err := dec(in); err != nil { return nil, err diff --git a/server/mock/app_test.go b/server/mock/app_test.go index bb5bd906cc..a200761ea4 100644 --- a/server/mock/app_test.go +++ b/server/mock/app_test.go @@ -37,16 +37,19 @@ func TestInitApp(t *testing.T) { appState, err := AppGenState(nil, genutiltypes.AppGenesis{}, nil) require.NoError(t, err) - req := abci.RequestInitChain{ + res, err := app.InitChain(&abci.RequestInitChain{ AppStateBytes: appState, - } - res, err := app.InitChain(&req) + }) require.NoError(t, err) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Hash: res.AppHash, Height: 1, }) - app.Commit() + require.NoError(t, err) + + _, err = app.Commit() + require.NoError(t, err) // make sure we can query these values query := abci.RequestQuery{ diff --git a/server/pruning_test.go b/server/pruning_test.go index 0c162fad61..08e1a6d077 100644 --- a/server/pruning_test.go +++ b/server/pruning_test.go @@ -49,8 +49,6 @@ func TestGetPruningOptionsFromFlags(t *testing.T) { } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(j *testing.T) { viper.Reset() viper.SetDefault(FlagPruning, pruningtypes.PruningOptionDefault) diff --git a/server/start.go b/server/start.go index d0fbcac2b1..602262d985 100644 --- a/server/start.go +++ b/server/start.go @@ -242,7 +242,7 @@ func startStandAlone(svrCtx *Context, svrCfg serverconfig.Config, clientCtx clie cmtApp := NewCometABCIWrapper(app) svr, err := server.NewServer(addr, transport, cmtApp) if err != nil { - return fmt.Errorf("error creating listener: %v", err) + return fmt.Errorf("error creating listener: %w", err) } svr.SetLogger(servercmtlog.CometLoggerWrapper{Logger: svrCtx.Logger.With("module", "abci-server")}) @@ -803,11 +803,11 @@ func testnetify(ctx *Context, testnetAppCreator types.AppCreator, db dbm.DB, tra _, _, _, _, proxyMetrics, _, _ := metrics(genDoc.ChainID) proxyApp := proxy.NewAppConns(clientCreator, proxyMetrics) if err := proxyApp.Start(); err != nil { - return nil, fmt.Errorf("error starting proxy app connections: %v", err) + return nil, fmt.Errorf("error starting proxy app connections: %w", err) } res, err := proxyApp.Query().Info(context, proxy.RequestInfo) if err != nil { - return nil, fmt.Errorf("error calling Info: %v", err) + return nil, fmt.Errorf("error calling Info: %w", err) } err = proxyApp.Stop() if err != nil { diff --git a/server/util_test.go b/server/util_test.go index a9d17f0e05..50f3e9a67a 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -59,7 +59,7 @@ func TestInterceptConfigsPreRunHandlerCreatesConfigFilesWhenMissing(t *testing.T serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -136,7 +136,7 @@ func TestInterceptConfigsPreRunHandlerReadsConfigToml(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -173,7 +173,7 @@ func TestInterceptConfigsPreRunHandlerReadsAppToml(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -201,7 +201,7 @@ func TestInterceptConfigsPreRunHandlerReadsFlags(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -236,7 +236,7 @@ func TestInterceptConfigsPreRunHandlerReadsEnvVars(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -265,6 +265,8 @@ type precedenceCommon struct { } func newPrecedenceCommon(t *testing.T) precedenceCommon { + t.Helper() + retval := precedenceCommon{} // Determine the env. var. name based off the executable name @@ -306,6 +308,8 @@ func newPrecedenceCommon(t *testing.T) precedenceCommon { } func (v precedenceCommon) setAll(t *testing.T, setFlag, setEnvVar, setConfigFile *string) { + t.Helper() + if setFlag != nil { if err := v.cmd.Flags().Set(v.flagName, *setFlag); err != nil { t.Fatalf("Failed setting flag %q", v.flagName) @@ -340,7 +344,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceFlag(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -356,7 +360,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceEnvVar(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -372,7 +376,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceConfigFile(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -388,7 +392,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceConfigDefault(t *testing.T) { serverCtx := &server.Context{} ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != errCanceledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCanceledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } diff --git a/simapp/app.go b/simapp/app.go index c1c85616ff..ae88239e74 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -457,7 +457,7 @@ func NewSimApp( app.GovKeeper = *govKeeper.SetHooks( govtypes.NewMultiGovHooks( - // register the governance hooks + // register the governance hooks ), ) @@ -487,7 +487,7 @@ func NewSimApp( app.EpochsKeeper.SetHooks( epochstypes.NewMultiEpochHooks( - // insert epoch hooks receivers here + // insert epoch hooks receivers here ), ) diff --git a/simapp/genesis_account_test.go b/simapp/genesis_account_test.go index d813e9ec7e..eccb8cc66c 100644 --- a/simapp/genesis_account_test.go +++ b/simapp/genesis_account_test.go @@ -81,7 +81,6 @@ func TestSimGenesisAccountValidate(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.wantErr, tc.sga.Validate() != nil) }) diff --git a/simapp/sim_bench_test.go b/simapp/sim_bench_test.go index d568b52b4e..4053f7db8e 100644 --- a/simapp/sim_bench_test.go +++ b/simapp/sim_bench_test.go @@ -13,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/server" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "github.com/cosmos/cosmos-sdk/testutils/sims" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" @@ -45,7 +44,6 @@ func BenchmarkFullAppSimulation(b *testing.B) { appOptions := viper.New() appOptions.SetDefault(flags.FlagHome, DefaultNodeHome) - appOptions.SetDefault(server.FlagInvCheckPeriod, simcli.FlagPeriodValue) app := NewSimApp(logger, db, nil, true, appOptions, interBlockCacheOpt(), baseapp.SetChainID(sims.SimAppChainID)) diff --git a/store/cache/cache.go b/store/cache/cache.go index 98d17d0341..748eae8c42 100644 --- a/store/cache/cache.go +++ b/store/cache/cache.go @@ -43,7 +43,7 @@ type ( func NewCommitKVStoreCache(store types.CommitKVStore, size uint) *CommitKVStoreCache { cache, err := lru.NewARC(int(size)) if err != nil { - panic(fmt.Errorf("failed to create KVStore cache: %s", err)) + panic(fmt.Errorf("failed to create KVStore cache: %w", err)) } return &CommitKVStoreCache{ diff --git a/store/cachekv/search_test.go b/store/cachekv/search_test.go index 41321c076e..aedc066903 100644 --- a/store/cachekv/search_test.go +++ b/store/cachekv/search_test.go @@ -60,7 +60,6 @@ func TestFindStartIndex(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { body := tt.sortedL got := findStartIndex(body, tt.query) @@ -129,7 +128,6 @@ func TestFindEndIndex(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { body := tt.sortedL got := findEndIndex(body, tt.query) diff --git a/store/cachekv/store_test.go b/store/cachekv/store_test.go index 3c56223554..980fe19467 100644 --- a/store/cachekv/store_test.go +++ b/store/cachekv/store_test.go @@ -464,7 +464,7 @@ func randInt(n int) int { return unsafe.NewRand().Int() % n } -// useful for replaying a error case if we find one +// useful for replaying an error case if we find one func doOp(t *testing.T, st types.CacheKVStore, truth dbm.DB, op int, args ...int) { t.Helper() switch op { @@ -474,8 +474,9 @@ func doOp(t *testing.T, st types.CacheKVStore, truth dbm.DB, op int, args ...int err := truth.Set(keyFmt(k), valFmt(k)) require.NoError(t, err) case opSetRange: + require.True(t, len(args) > 1) start := args[0] - end := args[1] + end := args[1] //nolint:gosec // this is not out of range setRange(t, st, truth, start, end) case opDel: k := args[0] @@ -483,8 +484,9 @@ func doOp(t *testing.T, st types.CacheKVStore, truth dbm.DB, op int, args ...int err := truth.Delete(keyFmt(k)) require.NoError(t, err) case opDelRange: + require.True(t, len(args) > 1) start := args[0] - end := args[1] + end := args[1] //nolint:gosec // this is not out of range deleteRange(t, st, truth, start, end) case opWrite: st.Write() @@ -543,7 +545,6 @@ func assertIterateDomainCheck(t *testing.T, st types.KVStore, mem dbm.DB, r []ke require.NoError(t, err) krc := newKeyRangeCounter(r) - i := 0 for ; krc.valid(); krc.next() { require.True(t, itr.Valid()) @@ -560,7 +561,6 @@ func assertIterateDomainCheck(t *testing.T, st types.KVStore, mem dbm.DB, r []ke itr.Next() itr2.Next() - i++ } require.False(t, itr.Valid()) diff --git a/store/iavl/store_test.go b/store/iavl/store_test.go index cff1d2d7f1..e32fb14116 100644 --- a/store/iavl/store_test.go +++ b/store/iavl/store_test.go @@ -639,7 +639,6 @@ func TestSetInitialVersion(t *testing.T) { } for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { db := dbm.NewMemDB() store := tc.storeFn(db) diff --git a/store/rootmulti/snapshot_test.go b/store/rootmulti/snapshot_test.go index 635be92970..265e0d20c1 100644 --- a/store/rootmulti/snapshot_test.go +++ b/store/rootmulti/snapshot_test.go @@ -141,7 +141,6 @@ func TestMultistoreSnapshot_Checksum(t *testing.T) { }}, } for _, tc := range testcases { - tc := tc t.Run(fmt.Sprintf("Format %v", tc.format), func(t *testing.T) { ch := make(chan io.ReadCloser) go func() { @@ -176,7 +175,6 @@ func TestMultistoreSnapshot_Errors(t *testing.T) { "unknown height": {9, nil}, } for name, tc := range testcases { - tc := tc t.Run(name, func(t *testing.T) { err := store.Snapshot(tc.height, nil) require.Error(t, err) diff --git a/store/rootmulti/store.go b/store/rootmulti/store.go index ee1cdbd068..cd9e9fd9d2 100644 --- a/store/rootmulti/store.go +++ b/store/rootmulti/store.go @@ -873,7 +873,7 @@ func (rs *Store) Snapshot(height uint64, protoWriter protoio.Writer) error { nodeCount := 0 for { node, err := exporter.Next() - if err == iavltree.ErrorExportDone { + if errors.Is(err, iavltree.ErrorExportDone) { rs.logger.Debug("snapshot Done", "store", store.name, "nodeCount", nodeCount) break } else if err != nil { @@ -897,7 +897,6 @@ func (rs *Store) Snapshot(height uint64, protoWriter protoio.Writer) error { return nil }() - if err != nil { return err } @@ -920,7 +919,7 @@ loop: for { snapshotItem = snapshottypes.SnapshotItem{} err := protoReader.ReadMsg(&snapshotItem) - if err == io.EOF { + if errors.Is(err, io.EOF) { break } else if err != nil { return snapshottypes.SnapshotItem{}, errorsmod.Wrap(err, "invalid protobuf message") diff --git a/store/rootmulti/store_test.go b/store/rootmulti/store_test.go index 2702f3e086..c53908d035 100644 --- a/store/rootmulti/store_test.go +++ b/store/rootmulti/store_test.go @@ -520,8 +520,6 @@ func TestMultiStore_Pruning(t *testing.T) { } for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { db := dbm.NewMemDB() ms := newMultiStoreWithMounts(db, tc.po) diff --git a/store/snapshots/chunk.go b/store/snapshots/chunk.go index fdf8cbd4b9..b191d19f1f 100644 --- a/store/snapshots/chunk.go +++ b/store/snapshots/chunk.go @@ -1,10 +1,11 @@ package snapshots import ( + "errors" "io" "math" - "cosmossdk.io/errors" + sdkerrors "cosmossdk.io/errors" snapshottypes "cosmossdk.io/store/snapshots/types" storetypes "cosmossdk.io/store/types" ) @@ -72,7 +73,7 @@ func (w *ChunkWriter) CloseWithError(err error) { // Write implements io.Writer. func (w *ChunkWriter) Write(data []byte) (int, error) { if w.closed { - return 0, errors.Wrap(storetypes.ErrLogic, "cannot write to closed ChunkWriter") + return 0, sdkerrors.Wrap(storetypes.ErrLogic, "cannot write to closed ChunkWriter") } nTotal := 0 for len(data) > 0 { @@ -149,7 +150,7 @@ func (r *ChunkReader) Read(p []byte) (int, error) { } } n, err := r.reader.Read(p) - if err == io.EOF { + if errors.Is(err, io.EOF) { err = r.reader.Close() r.reader = nil if err != nil { @@ -170,14 +171,14 @@ func DrainChunks(chunks <-chan io.ReadCloser) { // ValidRestoreHeight will check height is valid for snapshot restore or not func ValidRestoreHeight(format uint32, height uint64) error { if format != snapshottypes.CurrentFormat { - return errors.Wrapf(snapshottypes.ErrUnknownFormat, "format %v", format) + return sdkerrors.Wrapf(snapshottypes.ErrUnknownFormat, "format %v", format) } if height == 0 { - return errors.Wrap(storetypes.ErrLogic, "cannot restore snapshot at height 0") + return sdkerrors.Wrap(storetypes.ErrLogic, "cannot restore snapshot at height 0") } if height > uint64(math.MaxInt64) { - return errors.Wrapf(snapshottypes.ErrInvalidMetadata, + return sdkerrors.Wrapf(snapshottypes.ErrInvalidMetadata, "snapshot height %v cannot exceed %v", height, int64(math.MaxInt64)) } diff --git a/store/snapshots/helpers_test.go b/store/snapshots/helpers_test.go index d337b53ab7..6fb379d18f 100644 --- a/store/snapshots/helpers_test.go +++ b/store/snapshots/helpers_test.go @@ -127,7 +127,7 @@ func (m *mockSnapshotter) Restore( for { item.Reset() err := protoReader.ReadMsg(&item) - if err == io.EOF { + if errors.Is(err, io.EOF) { break } else if err != nil { return snapshottypes.SnapshotItem{}, errorsmod.Wrap(err, "invalid protobuf message") @@ -309,10 +309,10 @@ func (s *extSnapshotter) SnapshotExtension(height uint64, payloadWriter snapshot return nil } -func (s *extSnapshotter) RestoreExtension(height uint64, format uint32, payloadReader snapshottypes.ExtensionPayloadReader) error { +func (s *extSnapshotter) RestoreExtension(_ uint64, _ uint32, payloadReader snapshottypes.ExtensionPayloadReader) error { for { payload, err := payloadReader() - if err == io.EOF { + if errors.Is(err, io.EOF) { break } else if err != nil { return err diff --git a/store/types/gas_test.go b/store/types/gas_test.go index f4b5a6abe5..a4f63ab6d9 100644 --- a/store/types/gas_test.go +++ b/store/types/gas_test.go @@ -47,7 +47,6 @@ func TestGasMeter(t *testing.T) { used := uint64(0) for unum, usage := range tc.usage { - usage := usage used += usage require.NotPanics(t, func() { meter.ConsumeGas(usage, "") }, "Not exceeded limit but panicked. tc #%d, usage #%d", tcnum, unum) require.Equal(t, used, meter.GasConsumed(), "Gas consumption not match. tc #%d, usage #%d", tcnum, unum) diff --git a/tests/e2e/auth/cli_test.go b/tests/e2e/auth/cli_test.go index 45688f5f91..a029338e3d 100644 --- a/tests/e2e/auth/cli_test.go +++ b/tests/e2e/auth/cli_test.go @@ -6,9 +6,11 @@ package auth import ( "testing" - "cosmossdk.io/simapp" - "github.com/cosmos/cosmos-sdk/testutil/network" "github.com/stretchr/testify/suite" + + "cosmossdk.io/simapp" + + "github.com/cosmos/cosmos-sdk/testutil/network" ) func TestE2ETestSuite(t *testing.T) { diff --git a/tests/e2e/auth/suite.go b/tests/e2e/auth/suite.go index fd12683c48..dbd0696876 100644 --- a/tests/e2e/auth/suite.go +++ b/tests/e2e/auth/suite.go @@ -340,7 +340,6 @@ func (s *E2ETestSuite) TestCLIQueryTxCmdByHash() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryTxCmd() clientCtx := val.ClientCtx @@ -470,7 +469,6 @@ func (s *E2ETestSuite) TestCLIQueryTxCmdByEvents() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryTxCmd() clientCtx := val.ClientCtx @@ -548,7 +546,6 @@ func (s *E2ETestSuite) TestCLIQueryTxsCmdByEvents() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryTxsByEventsCmd() clientCtx := val.ClientCtx @@ -1339,10 +1336,10 @@ func (s *E2ETestSuite) TestSignWithMultiSignersAminoJSON() { // because DIRECT doesn't support multi signers via the CLI. // Since we use amino, we don't need to pre-populate signer_infos. txBuilder := val0.ClientCtx.TxConfig.NewTxBuilder() - txBuilder.SetMsgs( + require.NoError(txBuilder.SetMsgs( banktypes.NewMsgSend(val0.Address, addr1, sdk.NewCoins(val0Coin)), banktypes.NewMsgSend(val1.Address, addr1, sdk.NewCoins(val1Coin)), - ) + )) txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, math.NewInt(10)))) txBuilder.SetGasLimit(testdata.NewTestGasLimit() * 2) signers, err := txBuilder.GetTx().GetSigners() @@ -1436,7 +1433,6 @@ func (s *E2ETestSuite) TestAuxSigner() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { _, err := govtestutil.MsgSubmitLegacyProposal( val.ClientCtx, @@ -1658,7 +1654,6 @@ func (s *E2ETestSuite) TestAuxToFeeWithTips() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := govtestutil.MsgSubmitLegacyProposal( val.ClientCtx, diff --git a/tests/e2e/authz/grpc.go b/tests/e2e/authz/grpc.go index 24dd529b27..68782defad 100644 --- a/tests/e2e/authz/grpc.go +++ b/tests/e2e/authz/grpc.go @@ -63,7 +63,6 @@ func (s *E2ETestSuite) TestQueryGrantGRPC() { }, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, _ := testutil.GetRequest(tc.url) require := s.Require() @@ -74,7 +73,7 @@ func (s *E2ETestSuite) TestQueryGrantGRPC() { err := val.ClientCtx.Codec.UnmarshalJSON(resp, &g) require.NoError(err) require.Len(g.Grants, 1) - g.Grants[0].UnpackInterfaces(val.ClientCtx.InterfaceRegistry) + require.NoError(g.Grants[0].UnpackInterfaces(val.ClientCtx.InterfaceRegistry)) auth, err := g.Grants[0].GetAuthorization() require.NoError(err) require.Equal(auth.MsgTypeURL(), banktypes.SendAuthorization{}.MsgTypeURL()) @@ -150,7 +149,6 @@ func (s *E2ETestSuite) TestQueryGrantsGRPC() { }, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { tc.preRun() resp, err := testutil.GetRequest(tc.url) diff --git a/tests/e2e/authz/tx.go b/tests/e2e/authz/tx.go index 225a8332e8..c41a41fd70 100644 --- a/tests/e2e/authz/tx.go +++ b/tests/e2e/authz/tx.go @@ -308,7 +308,6 @@ func (s *E2ETestSuite) TestCmdRevokeAuthorizations() { }, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdRevokeAuthorization(addresscodec.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx @@ -455,7 +454,6 @@ func (s *E2ETestSuite) TestNewExecGenericAuthorized() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -561,7 +559,6 @@ func (s *E2ETestSuite) TestNewExecGrantAuthorized() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -760,7 +757,6 @@ func (s *E2ETestSuite) TestExecDelegateAuthorization() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -827,7 +823,6 @@ func (s *E2ETestSuite) TestExecDelegateAuthorization() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -985,7 +980,6 @@ func (s *E2ETestSuite) TestExecUndelegateAuthorization() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -1053,7 +1047,6 @@ func (s *E2ETestSuite) TestExecUndelegateAuthorization() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx diff --git a/tests/e2e/bank/cli_test.go b/tests/e2e/bank/cli_test.go index 8ff0878935..4560aea6bf 100644 --- a/tests/e2e/bank/cli_test.go +++ b/tests/e2e/bank/cli_test.go @@ -6,10 +6,11 @@ package client import ( "testing" - "cosmossdk.io/simapp" - "github.com/cosmos/cosmos-sdk/testutil/network" - "github.com/stretchr/testify/suite" + + "cosmossdk.io/simapp" + + "github.com/cosmos/cosmos-sdk/testutil/network" ) func TestE2ETestSuite(t *testing.T) { diff --git a/tests/e2e/bank/grpc.go b/tests/e2e/bank/grpc.go index d60c6a203b..ed7c56e3d3 100644 --- a/tests/e2e/bank/grpc.go +++ b/tests/e2e/bank/grpc.go @@ -89,7 +89,6 @@ func (s *E2ETestSuite) TestTotalSupplyGRPCHandler() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) @@ -210,7 +209,6 @@ func (s *E2ETestSuite) TestDenomMetadataGRPCHandler() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) @@ -274,7 +272,6 @@ func (s *E2ETestSuite) TestBalancesGRPCHandler() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequest(tc.url) s.Require().NoError(err) diff --git a/tests/e2e/bank/suite.go b/tests/e2e/bank/suite.go index 48b34f12b4..2d709abe80 100644 --- a/tests/e2e/bank/suite.go +++ b/tests/e2e/bank/suite.go @@ -234,8 +234,6 @@ func (s *E2ETestSuite) TestNewSendTxCmd() { } for _, tc := range testCases { - tc := tc - s.Require().NoError(s.network.WaitForNextBlock()) s.Run(tc.name, func() { clientCtx := val.ClientCtx @@ -369,8 +367,6 @@ func (s *E2ETestSuite) TestNewMultiSendTxCmd() { } for _, tc := range testCases { - tc := tc - s.Require().NoError(s.network.WaitForNextBlock()) s.Run(tc.name, func() { clientCtx := val.ClientCtx diff --git a/tests/e2e/client/grpc/cmtservice/service_test.go b/tests/e2e/client/grpc/cmtservice/service_test.go index 48010f625b..d4c97dfae4 100644 --- a/tests/e2e/client/grpc/cmtservice/service_test.go +++ b/tests/e2e/client/grpc/cmtservice/service_test.go @@ -8,9 +8,10 @@ import ( "fmt" "testing" - "cosmossdk.io/simapp" "github.com/stretchr/testify/suite" + "cosmossdk.io/simapp" + "github.com/cosmos/cosmos-sdk/client/grpc/cmtservice" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -92,7 +93,7 @@ func (s *E2ETestSuite) TestQueryLatestBlock() { s.Require().NoError(err) var blockInfoRes cmtservice.GetLatestBlockResponse s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(restRes, &blockInfoRes)) - s.Require().Equal(types.ConsAddress(blockInfoRes.Block.Header.ProposerAddress).String(), blockInfoRes.SdkBlock.Header.ProposerAddress) + s.Require().Equal(types.ConsAddress(blockInfoRes.Block.Header.ProposerAddress).String(), blockInfoRes.SdkBlock.Header.ProposerAddress) //nolint:staticcheck // this test is for checking equality from the old and new types s.Require().Contains(blockInfoRes.SdkBlock.Header.ProposerAddress, "cosmosvalcons") } @@ -156,7 +157,6 @@ func (s *E2ETestSuite) TestLatestValidatorSet_GRPC() { {"with pagination", &cmtservice.GetLatestValidatorSetRequest{Pagination: &qtypes.PageRequest{Offset: 0, Limit: uint64(len(vals))}}, false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { grpcRes, err := s.queryClient.GetLatestValidatorSet(context.Background(), tc.req) if tc.expErr { @@ -187,7 +187,6 @@ func (s *E2ETestSuite) TestLatestValidatorSet_GRPCGateway() { {"with pagination", fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validatorsets/latest?pagination.offset=0&pagination.limit=2", vals[0].APIAddress), false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := testutil.GetRequest(tc.url) s.Require().NoError(err) @@ -220,7 +219,6 @@ func (s *E2ETestSuite) TestValidatorSetByHeight_GRPC() { {"with pagination", &cmtservice.GetValidatorSetByHeightRequest{Height: 1, Pagination: &qtypes.PageRequest{Offset: 0, Limit: 1}}, false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { grpcRes, err := s.queryClient.GetValidatorSetByHeight(context.Background(), tc.req) if tc.expErr { @@ -249,7 +247,6 @@ func (s *E2ETestSuite) TestValidatorSetByHeight_GRPCGateway() { {"with pagination", fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validatorsets/%d?pagination.offset=0&pagination.limit=2", vals[0].APIAddress, 1), false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := testutil.GetRequest(tc.url) s.Require().NoError(err) @@ -328,8 +325,6 @@ func (s *E2ETestSuite) TestABCIQuery() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { res, err := s.queryClient.ABCIQuery(context.Background(), tc.req) if tc.expectErr { diff --git a/tests/e2e/distribution/grpc_query_suite.go b/tests/e2e/distribution/grpc_query_suite.go index 6d40625d7e..8ee8683b13 100644 --- a/tests/e2e/distribution/grpc_query_suite.go +++ b/tests/e2e/distribution/grpc_query_suite.go @@ -64,7 +64,6 @@ func (s *GRPCQueryTestSuite) TestQueryParamsGRPC() { } for _, tc := range testCases { - tc := tc resp, err := sdktestutil.GetRequest(tc.url) s.Run(tc.name, func() { s.Require().NoError(err) @@ -99,7 +98,6 @@ func (s *GRPCQueryTestSuite) TestQueryValidatorDistributionInfoGRPC() { } for _, tc := range testCases { - tc := tc resp, err := sdktestutil.GetRequest(tc.url) s.Run(tc.name, func() { if tc.expErr { @@ -152,7 +150,6 @@ func (s *GRPCQueryTestSuite) TestQueryOutstandingRewardsGRPC() { } for _, tc := range testCases { - tc := tc resp, err := sdktestutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { if tc.expErr { @@ -206,7 +203,6 @@ func (s *GRPCQueryTestSuite) TestQueryValidatorCommissionGRPC() { } for _, tc := range testCases { - tc := tc resp, err := sdktestutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { if tc.expErr { @@ -264,7 +260,6 @@ func (s *GRPCQueryTestSuite) TestQuerySlashesGRPC() { } for _, tc := range testCases { - tc := tc resp, err := sdktestutil.GetRequest(tc.url) s.Run(tc.name, func() { @@ -340,7 +335,6 @@ func (s *GRPCQueryTestSuite) TestQueryDelegatorRewardsGRPC() { } for _, tc := range testCases { - tc := tc resp, err := sdktestutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { @@ -392,7 +386,6 @@ func (s *GRPCQueryTestSuite) TestQueryDelegatorValidatorsGRPC() { } for _, tc := range testCases { - tc := tc resp, err := sdktestutil.GetRequest(tc.url) s.Run(tc.name, func() { @@ -444,7 +437,6 @@ func (s *GRPCQueryTestSuite) TestQueryWithdrawAddressGRPC() { } for _, tc := range testCases { - tc := tc resp, err := sdktestutil.GetRequest(tc.url) s.Run(tc.name, func() { @@ -489,7 +481,6 @@ func (s *GRPCQueryTestSuite) TestQueryValidatorCommunityPoolGRPC() { } for _, tc := range testCases { - tc := tc resp, err := sdktestutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { diff --git a/tests/e2e/distribution/suite.go b/tests/e2e/distribution/suite.go index 54d02961f7..28a982c145 100644 --- a/tests/e2e/distribution/suite.go +++ b/tests/e2e/distribution/suite.go @@ -129,8 +129,6 @@ func (s *E2ETestSuite) TestNewWithdrawRewardsCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { clientCtx := val.ClientCtx @@ -224,8 +222,6 @@ func (s *E2ETestSuite) TestNewWithdrawAllRewardsCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewWithdrawAllRewardsCmd(address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx @@ -309,8 +305,6 @@ func (s *E2ETestSuite) TestNewSetWithdrawAddrCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewSetWithdrawAddrCmd(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx @@ -364,8 +358,6 @@ func (s *E2ETestSuite) TestNewFundCommunityPoolCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewFundCommunityPoolCmd(address.NewBech32Codec("cosmos")) clientCtx := val.ClientCtx diff --git a/tests/e2e/gov/cli_test.go b/tests/e2e/gov/cli_test.go index 451f763512..4f6f8b125d 100644 --- a/tests/e2e/gov/cli_test.go +++ b/tests/e2e/gov/cli_test.go @@ -7,13 +7,13 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + "cosmossdk.io/simapp" "github.com/cosmos/cosmos-sdk/testutil/network" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" ) func TestE2ETestSuite(t *testing.T) { diff --git a/tests/e2e/gov/grpc.go b/tests/e2e/gov/grpc.go index 77560ba3a4..673f50be00 100644 --- a/tests/e2e/gov/grpc.go +++ b/tests/e2e/gov/grpc.go @@ -38,7 +38,6 @@ func (s *E2ETestSuite) TestGetProposalGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequest(tc.url) s.Require().NoError(err) @@ -92,7 +91,6 @@ func (s *E2ETestSuite) TestGetProposalsGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) @@ -159,7 +157,6 @@ func (s *E2ETestSuite) TestGetProposalVoteGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequest(tc.url) s.Require().NoError(err) @@ -203,7 +200,6 @@ func (s *E2ETestSuite) TestGetProposalVotesGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequest(tc.url) s.Require().NoError(err) @@ -252,7 +248,6 @@ func (s *E2ETestSuite) TestGetProposalDepositGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequest(tc.url) s.Require().NoError(err) @@ -291,7 +286,6 @@ func (s *E2ETestSuite) TestGetProposalDepositsGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequest(tc.url) s.Require().NoError(err) @@ -336,7 +330,6 @@ func (s *E2ETestSuite) TestGetTallyGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequest(tc.url) s.Require().NoError(err) @@ -398,7 +391,6 @@ func (s *E2ETestSuite) TestGetParamsGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequest(tc.url) s.Require().NoError(err) diff --git a/tests/e2e/gov/tx.go b/tests/e2e/gov/tx.go index 5bcff67937..d804c35c1a 100644 --- a/tests/e2e/gov/tx.go +++ b/tests/e2e/gov/tx.go @@ -165,8 +165,6 @@ func (s *E2ETestSuite) TestNewCmdSubmitProposal() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewCmdSubmitProposal() clientCtx := val.ClientCtx @@ -261,8 +259,6 @@ func (s *E2ETestSuite) TestNewCmdSubmitLegacyProposal() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewCmdSubmitLegacyProposal() clientCtx := val.ClientCtx @@ -446,7 +442,6 @@ func (s *E2ETestSuite) TestNewCmdVote() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdVote() clientCtx := val.ClientCtx @@ -543,7 +538,6 @@ func (s *E2ETestSuite) TestNewCmdWeightedVote() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdWeightedVote() clientCtx := val.ClientCtx diff --git a/tests/e2e/group/cli_test.go b/tests/e2e/group/cli_test.go index 438686bc38..7c6e860886 100644 --- a/tests/e2e/group/cli_test.go +++ b/tests/e2e/group/cli_test.go @@ -6,10 +6,11 @@ package group import ( "testing" - "cosmossdk.io/simapp" - "github.com/cosmos/cosmos-sdk/testutil/network" - "github.com/stretchr/testify/suite" + + "cosmossdk.io/simapp" + + "github.com/cosmos/cosmos-sdk/testutil/network" ) func TestE2ETestSuite(t *testing.T) { diff --git a/tests/e2e/mint/cli_test.go b/tests/e2e/mint/cli_test.go index 35dc54d4e3..08158c2796 100644 --- a/tests/e2e/mint/cli_test.go +++ b/tests/e2e/mint/cli_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/suite" "cosmossdk.io/simapp" + "github.com/cosmos/cosmos-sdk/testutil/network" ) diff --git a/tests/e2e/server/export_test.go b/tests/e2e/server/export_test.go index 45616e7029..f50e369593 100644 --- a/tests/e2e/server/export_test.go +++ b/tests/e2e/server/export_test.go @@ -20,6 +20,7 @@ import ( "cosmossdk.io/log" "cosmossdk.io/simapp" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" @@ -95,10 +96,12 @@ func TestExportCmd_Height(t *testing.T) { // Fast forward to block `tc.fastForward`. for i := int64(2); i <= tc.fastForward; i++ { - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: i, }) - app.Commit() + assert.NilError(t, err) + _, err = app.Commit() + assert.NilError(t, err) } output := &bytes.Buffer{} @@ -182,16 +185,20 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, ge err = genutil.ExportGenesisFile(&appGenesis, serverCtx.Config.GenesisFile()) assert.NilError(t, err) - app.InitChain(&abci.RequestInitChain{ + _, err = app.InitChain(&abci.RequestInitChain{ Validators: []abci.ValidatorUpdate{}, ConsensusParams: simtestutil.DefaultConsensusParams, AppStateBytes: appGenesis.AppState, - }, - ) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + }) + assert.NilError(t, err) + + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: 1, }) - app.Commit() + assert.NilError(t, err) + + _, err = app.Commit() + assert.NilError(t, err) cmd := server.ExportCmd( func(_ log.Logger, _ dbm.DB, _ io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, appOptions types.AppOptions, modulesToExport []string) (types.ExportedApp, error) { diff --git a/tests/e2e/staking/cli_test.go b/tests/e2e/staking/cli_test.go index 6f74d310fb..0705c5645e 100644 --- a/tests/e2e/staking/cli_test.go +++ b/tests/e2e/staking/cli_test.go @@ -6,9 +6,11 @@ package testutil import ( "testing" - "cosmossdk.io/simapp" - "github.com/cosmos/cosmos-sdk/testutil/network" "github.com/stretchr/testify/suite" + + "cosmossdk.io/simapp" + + "github.com/cosmos/cosmos-sdk/testutil/network" ) func TestE2ETestSuite(t *testing.T) { diff --git a/tests/e2e/staking/suite.go b/tests/e2e/staking/suite.go index 5852446f21..efbf5170d9 100644 --- a/tests/e2e/staking/suite.go +++ b/tests/e2e/staking/suite.go @@ -133,7 +133,7 @@ func (s *E2ETestSuite) TestBlockResults() { // Loop until we find a block result with the correct validator updates. // By experience, it happens around 2 blocks after `delHeight`. - s.network.RetryForBlocks(func() error { + _ = s.network.RetryForBlocks(func() error { latestHeight, err := s.network.LatestHeight() require.NoError(err) res, err := rpcClient.BlockResults(context.Background(), &latestHeight) @@ -153,4 +153,5 @@ func (s *E2ETestSuite) TestBlockResults() { return nil }, 10) + // TODO: revisit if this test is doing anything useful } diff --git a/tests/e2e/tx/service_test.go b/tests/e2e/tx/service_test.go index cee50c6a5a..363924c307 100644 --- a/tests/e2e/tx/service_test.go +++ b/tests/e2e/tx/service_test.go @@ -174,7 +174,6 @@ func (s *E2ETestSuite) TestSimulateTx_GRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { // Broadcast the tx via gRPC via the validator's clientCtx (which goes // through Tendermint). @@ -505,7 +504,6 @@ func (s *E2ETestSuite) TestBroadcastTx_GRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { // Broadcast the tx via gRPC via the validator's clientCtx (which goes // through Tendermint). @@ -765,7 +763,6 @@ func (s *E2ETestSuite) TestTxEncode_GRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := s.queryClient.TxEncode(context.Background(), tc.req) if tc.expErr { @@ -844,7 +841,6 @@ func (s *E2ETestSuite) TestTxDecode_GRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := s.queryClient.TxDecode(context.Background(), tc.req) if tc.expErr { @@ -934,7 +930,6 @@ func (s *E2ETestSuite) TestTxEncodeAmino_GRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := s.queryClient.TxEncodeAmino(context.Background(), tc.req) if tc.expErr { @@ -1020,7 +1015,6 @@ func (s *E2ETestSuite) TestTxDecodeAmino_GRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := s.queryClient.TxDecodeAmino(context.Background(), tc.req) if tc.expErr { diff --git a/tests/fuzz/tests/crypto_hd_deriveprivatekeyforpath_test.go b/tests/fuzz/tests/crypto_hd_deriveprivatekeyforpath_test.go index 0f235262c6..d10d9dcc6b 100644 --- a/tests/fuzz/tests/crypto_hd_deriveprivatekeyforpath_test.go +++ b/tests/fuzz/tests/crypto_hd_deriveprivatekeyforpath_test.go @@ -6,7 +6,7 @@ import ( "bytes" "testing" - bip39 "github.com/cosmos/go-bip39" + "github.com/cosmos/go-bip39" "github.com/cosmos/cosmos-sdk/crypto/hd" ) @@ -30,6 +30,6 @@ func FuzzCryptoHDDerivePrivateKeyForPath(f *testing.F) { } seed := mnemonicToSeed(string(mnemonic)) master, ch := hd.ComputeMastersFromSeed(seed) - hd.DerivePrivateKeyForPath(master, ch, string(path)) + _, _ = hd.DerivePrivateKeyForPath(master, ch, string(path)) }) } diff --git a/tests/fuzz/tests/crypto_hd_newparamsfrompath_test.go b/tests/fuzz/tests/crypto_hd_newparamsfrompath_test.go index df178d0505..4d955c775f 100644 --- a/tests/fuzz/tests/crypto_hd_newparamsfrompath_test.go +++ b/tests/fuzz/tests/crypto_hd_newparamsfrompath_test.go @@ -10,6 +10,6 @@ import ( func FuzzCryptoHDNewParamsFromPath(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { - hd.NewParamsFromPath(string(data)) + _, _ = hd.NewParamsFromPath(string(data)) }) } diff --git a/tests/fuzz/tests/types_parsecoin_test.go b/tests/fuzz/tests/types_parsecoin_test.go index 2204454379..631cdcea2f 100644 --- a/tests/fuzz/tests/types_parsecoin_test.go +++ b/tests/fuzz/tests/types_parsecoin_test.go @@ -10,6 +10,6 @@ import ( func FuzzTypesParseCoin(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { - types.ParseCoinNormalized(string(data)) + _, _ = types.ParseCoinNormalized(string(data)) }) } diff --git a/tests/fuzz/tests/types_parsedeccoin_test.go b/tests/fuzz/tests/types_parsedeccoin_test.go index a9b64e3384..210444554b 100644 --- a/tests/fuzz/tests/types_parsedeccoin_test.go +++ b/tests/fuzz/tests/types_parsedeccoin_test.go @@ -10,6 +10,6 @@ import ( func FuzzTypesParseDecCoin(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { - types.ParseDecCoin(string(data)) + _, _ = types.ParseDecCoin(string(data)) }) } diff --git a/tests/fuzz/tests/types_verifyaddressformat_test.go b/tests/fuzz/tests/types_verifyaddressformat_test.go index 7df912e711..55e0014cc7 100644 --- a/tests/fuzz/tests/types_verifyaddressformat_test.go +++ b/tests/fuzz/tests/types_verifyaddressformat_test.go @@ -10,6 +10,6 @@ import ( func FuzzTypesVerifyAddressFormat(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { - types.VerifyAddressFormat(data) + _ = types.VerifyAddressFormat(data) }) } diff --git a/tests/fuzz/tests/unknownproto_test.go b/tests/fuzz/tests/unknownproto_test.go index 0e2eda4aac..1f814405e3 100644 --- a/tests/fuzz/tests/unknownproto_test.go +++ b/tests/fuzz/tests/unknownproto_test.go @@ -13,7 +13,7 @@ func FuzzUnknownProto(f *testing.F) { f.Fuzz(func(t *testing.T, b []byte) { msg := new(testdata.TestVersion2) resolver := new(unknownproto.DefaultAnyResolver) - unknownproto.RejectUnknownFields(b, msg, true, resolver) - unknownproto.RejectUnknownFields(b, msg, false, resolver) + _, _ = unknownproto.RejectUnknownFields(b, msg, true, resolver) + _, _ = unknownproto.RejectUnknownFields(b, msg, false, resolver) }) } diff --git a/tests/integration/auth/client/cli/suite_test.go b/tests/integration/auth/client/cli/suite_test.go index 290568b705..6a41708ef5 100644 --- a/tests/integration/auth/client/cli/suite_test.go +++ b/tests/integration/auth/client/cli/suite_test.go @@ -268,7 +268,6 @@ func (s *CLITestSuite) TestCLIQueryTxCmdByHash() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryTxCmd() cmd.SetArgs(tc.args) @@ -334,7 +333,6 @@ func (s *CLITestSuite) TestCLIQueryTxCmdByEvents() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryTxCmd() cmd.SetArgs(tc.args) @@ -377,7 +375,6 @@ func (s *CLITestSuite) TestCLIQueryTxsCmdByEvents() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryTxsByEventsCmd() @@ -940,10 +937,10 @@ func (s *CLITestSuite) TestSignWithMultiSignersAminoJSON() { // because DIRECT doesn't support multi signers via the CLI. // Since we use amino, we don't need to pre-populate signer_infos. txBuilder := s.clientCtx.TxConfig.NewTxBuilder() - txBuilder.SetMsgs( + s.Require().NoError(txBuilder.SetMsgs( banktypes.NewMsgSend(val0, addr1, sdk.NewCoins(val0Coin)), banktypes.NewMsgSend(val1, addr1, sdk.NewCoins(val1Coin)), - ) + )) txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(10)))) txBuilder.SetGasLimit(testdata.NewTestGasLimit() * 2) signers, err := txBuilder.GetTx().GetSigners() @@ -1026,7 +1023,6 @@ func (s *CLITestSuite) TestAuxSigner() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { _, err := govtestutil.MsgSubmitLegacyProposal( s.clientCtx, @@ -1245,7 +1241,6 @@ func (s *CLITestSuite) TestAuxToFeeWithTips() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := govtestutil.MsgSubmitLegacyProposal( s.clientCtx, diff --git a/tests/integration/bank/keeper/deterministic_test.go b/tests/integration/bank/keeper/deterministic_test.go index 86bce29111..d5fe027f5c 100644 --- a/tests/integration/bank/keeper/deterministic_test.go +++ b/tests/integration/bank/keeper/deterministic_test.go @@ -4,6 +4,7 @@ import ( "testing" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/stretchr/testify/require" "gotest.tools/v3/assert" "pgregory.net/rapid" @@ -63,6 +64,8 @@ type deterministicFixture struct { } func initDeterministicFixture(t *testing.T) *deterministicFixture { + t.Helper() + keys := storetypes.NewKVStoreKeys(authtypes.StoreKey, banktypes.StoreKey) cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, bank.AppModuleBasic{}).Codec @@ -311,7 +314,7 @@ func TestGRPCQueryParams(t *testing.T) { DefaultSendEnabled: rapid.Bool().Draw(rt, "send"), } - f.bankKeeper.SetParams(f.ctx, params) + require.NoError(t, f.bankKeeper.SetParams(f.ctx, params)) req := &banktypes.QueryParamsRequest{} testdata.DeterministicIterations(f.ctx, t, req, f.queryClient.Params, 0, true) @@ -327,7 +330,7 @@ func TestGRPCQueryParams(t *testing.T) { DefaultSendEnabled: false, } - f.bankKeeper.SetParams(f.ctx, params) + require.NoError(t, f.bankKeeper.SetParams(f.ctx, params)) req := &banktypes.QueryParamsRequest{} testdata.DeterministicIterations(f.ctx, t, req, f.queryClient.Params, 1003, false) diff --git a/tests/integration/distribution/keeper/msg_server_test.go b/tests/integration/distribution/keeper/msg_server_test.go index fbb883da63..bc0434af88 100644 --- a/tests/integration/distribution/keeper/msg_server_test.go +++ b/tests/integration/distribution/keeper/msg_server_test.go @@ -57,13 +57,14 @@ type fixture struct { valAddr sdk.ValAddress } -func initFixture(t testing.TB) *fixture { +func initFixture(tb testing.TB) *fixture { + tb.Helper() keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, distrtypes.StoreKey, stakingtypes.StoreKey, ) cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, distribution.AppModuleBasic{}).Codec - logger := log.NewTestLogger(t) + logger := log.NewTestLogger(tb) cms := integration.CreateMultiStore(keys, logger) newCtx := sdk.NewContext(cms, types.Header{}, true, logger) @@ -280,7 +281,6 @@ func TestMsgWithdrawDelegatorReward(t *testing.T) { assert.Equal(t, proposerAddr.Empty(), true) for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( tc.msg, @@ -428,7 +428,6 @@ func TestMsgSetWithdrawAddress(t *testing.T) { }, } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { tc.preRun() res, err := f.app.RunMsg( @@ -525,7 +524,6 @@ func TestMsgWithdrawValidatorCommission(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( tc.msg, @@ -558,7 +556,6 @@ func TestMsgWithdrawValidatorCommission(t *testing.T) { }, remainder.Commission) } }) - } } @@ -627,7 +624,6 @@ func TestMsgFundCommunityPool(t *testing.T) { }, } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( tc.msg, @@ -661,7 +657,6 @@ func TestMsgUpdateParams(t *testing.T) { // default params communityTax := math.LegacyNewDecWithPrec(2, 2) // 2% - withdrawAddrEnabled := true testCases := []struct { name string @@ -675,7 +670,7 @@ func TestMsgUpdateParams(t *testing.T) { Authority: "invalid", Params: distrtypes.Params{ CommunityTax: math.LegacyNewDecWithPrec(2, 0), - WithdrawAddrEnabled: withdrawAddrEnabled, + WithdrawAddrEnabled: true, BaseProposerReward: math.LegacyZeroDec(), BonusProposerReward: math.LegacyZeroDec(), }, @@ -689,7 +684,7 @@ func TestMsgUpdateParams(t *testing.T) { Authority: f.distrKeeper.GetAuthority(), Params: distrtypes.Params{ CommunityTax: math.LegacyDec{}, - WithdrawAddrEnabled: withdrawAddrEnabled, + WithdrawAddrEnabled: true, BaseProposerReward: math.LegacyZeroDec(), BonusProposerReward: math.LegacyZeroDec(), }, @@ -703,7 +698,7 @@ func TestMsgUpdateParams(t *testing.T) { Authority: f.distrKeeper.GetAuthority(), Params: distrtypes.Params{ CommunityTax: math.LegacyNewDecWithPrec(2, 0), - WithdrawAddrEnabled: withdrawAddrEnabled, + WithdrawAddrEnabled: true, BaseProposerReward: math.LegacyZeroDec(), BonusProposerReward: math.LegacyZeroDec(), }, @@ -717,7 +712,7 @@ func TestMsgUpdateParams(t *testing.T) { Authority: f.distrKeeper.GetAuthority(), Params: distrtypes.Params{ CommunityTax: math.LegacyNewDecWithPrec(-2, 1), - WithdrawAddrEnabled: withdrawAddrEnabled, + WithdrawAddrEnabled: true, BaseProposerReward: math.LegacyZeroDec(), BonusProposerReward: math.LegacyZeroDec(), }, @@ -733,7 +728,7 @@ func TestMsgUpdateParams(t *testing.T) { CommunityTax: communityTax, BaseProposerReward: math.LegacyNewDecWithPrec(1, 2), BonusProposerReward: math.LegacyZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, + WithdrawAddrEnabled: true, }, }, expErr: true, @@ -747,7 +742,7 @@ func TestMsgUpdateParams(t *testing.T) { CommunityTax: communityTax, BaseProposerReward: math.LegacyZeroDec(), BonusProposerReward: math.LegacyNewDecWithPrec(1, 2), - WithdrawAddrEnabled: withdrawAddrEnabled, + WithdrawAddrEnabled: true, }, }, expErr: true, @@ -761,7 +756,7 @@ func TestMsgUpdateParams(t *testing.T) { CommunityTax: communityTax, BaseProposerReward: math.LegacyZeroDec(), BonusProposerReward: math.LegacyZeroDec(), - WithdrawAddrEnabled: withdrawAddrEnabled, + WithdrawAddrEnabled: true, }, }, expErr: false, @@ -769,7 +764,6 @@ func TestMsgUpdateParams(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( tc.msg, @@ -848,7 +842,6 @@ func TestMsgCommunityPoolSpend(t *testing.T) { }, } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( tc.msg, @@ -950,7 +943,6 @@ func TestMsgDepositValidatorRewardsPool(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { res, err := f.app.RunMsg( tc.msg, diff --git a/tests/integration/evidence/keeper/infraction_test.go b/tests/integration/evidence/keeper/infraction_test.go index fc72d14c60..ec6e70765f 100644 --- a/tests/integration/evidence/keeper/infraction_test.go +++ b/tests/integration/evidence/keeper/infraction_test.go @@ -78,13 +78,14 @@ type fixture struct { stakingKeeper *stakingkeeper.Keeper } -func initFixture(t testing.TB) *fixture { +func initFixture(tb testing.TB) *fixture { + tb.Helper() keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, consensusparamtypes.StoreKey, evidencetypes.StoreKey, stakingtypes.StoreKey, slashingtypes.StoreKey, ) cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, evidence.AppModuleBasic{}).Codec - logger := log.NewTestLogger(t) + logger := log.NewTestLogger(tb) cms := integration.CreateMultiStore(keys, logger) newCtx := sdk.NewContext(cms, cmtproto.Header{}, true, logger) @@ -148,10 +149,10 @@ func initFixture(t testing.TB) *fixture { evidencetypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), keeper.NewMsgServerImpl(*evidenceKeeper)) evidencetypes.RegisterQueryServer(integrationApp.QueryHelper(), keeper.NewQuerier(evidenceKeeper)) - assert.NilError(t, slashingKeeper.SetParams(sdkCtx, testutil.TestParams())) + assert.NilError(tb, slashingKeeper.SetParams(sdkCtx, testutil.TestParams())) // set default staking params - assert.NilError(t, stakingKeeper.SetParams(sdkCtx, stakingtypes.DefaultParams())) + assert.NilError(tb, stakingKeeper.SetParams(sdkCtx, stakingtypes.DefaultParams())) return &fixture{ app: integrationApp, @@ -193,10 +194,10 @@ func TestHandleDoubleSign(t *testing.T) { assert.NilError(t, f.slashingKeeper.AddPubkey(f.sdkCtx, valpubkey)) info := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(valpubkey.Address()), f.sdkCtx.BlockHeight(), int64(0), time.Unix(0, 0), false, int64(0)) - f.slashingKeeper.SetValidatorSigningInfo(f.sdkCtx, sdk.ConsAddress(valpubkey.Address()), info) + assert.NilError(t, f.slashingKeeper.SetValidatorSigningInfo(f.sdkCtx, sdk.ConsAddress(valpubkey.Address()), info)) // handle a signature to set signing info - f.slashingKeeper.HandleValidatorSignature(ctx, valpubkey.Address(), selfDelegation.Int64(), comet.BlockIDFlagCommit) + assert.NilError(t, f.slashingKeeper.HandleValidatorSignature(ctx, valpubkey.Address(), selfDelegation.Int64(), comet.BlockIDFlagCommit)) // double sign less than max age val, err = f.stakingKeeper.Validator(ctx, operatorAddr) diff --git a/tests/integration/gov/common_test.go b/tests/integration/gov/common_test.go index 3ade7cde3c..3519bb20ff 100644 --- a/tests/integration/gov/common_test.go +++ b/tests/integration/gov/common_test.go @@ -24,6 +24,8 @@ var ( // mkTestLegacyContent creates a MsgExecLegacyContent for testing purposes. func mkTestLegacyContent(t *testing.T) *v1.MsgExecLegacyContent { + t.Helper() + msgContent, err := v1.NewLegacyContent(TestProposal, authtypes.NewModuleAddress(types.ModuleName).String()) assert.NilError(t, err) diff --git a/tests/integration/gov/genesis_test.go b/tests/integration/gov/genesis_test.go index ecf82c02f8..6e7bbae25f 100644 --- a/tests/integration/gov/genesis_test.go +++ b/tests/integration/gov/genesis_test.go @@ -189,6 +189,8 @@ func TestImportExportQueues(t *testing.T) { } func clearDB(t *testing.T, db *dbm.MemDB) { + t.Helper() + iter, err := db.Iterator(nil, nil) assert.NilError(t, err) defer iter.Close() diff --git a/tests/integration/gov/keeper/common_test.go b/tests/integration/gov/keeper/common_test.go index 9e1bca0b45..80a21d3fef 100644 --- a/tests/integration/gov/keeper/common_test.go +++ b/tests/integration/gov/keeper/common_test.go @@ -36,6 +36,8 @@ func getTestProposal() []sdk.Msg { } func createValidators(t *testing.T, f *fixture, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress) { + t.Helper() + addrs := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.ctx, 5, math.NewInt(30000000)) valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) pks := simtestutil.CreateTestPubKeys(5) @@ -47,21 +49,22 @@ func createValidators(t *testing.T, f *fixture, powers []int64) ([]sdk.AccAddres val3, err := stakingtypes.NewValidator(valAddrs[2].String(), pks[2], stakingtypes.Description{}) assert.NilError(t, err) - f.stakingKeeper.SetValidator(f.ctx, val1) - f.stakingKeeper.SetValidator(f.ctx, val2) - f.stakingKeeper.SetValidator(f.ctx, val3) - f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val1) - f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val2) - f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val3) - f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val1) - f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val2) - f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val3) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val1)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val2)) + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, val3)) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val1)) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val2)) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, val3)) + assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val1)) + assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val2)) + assert.NilError(t, f.stakingKeeper.SetNewValidatorByPowerIndex(f.ctx, val3)) _, _ = f.stakingKeeper.Delegate(f.ctx, addrs[0], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[0]), stakingtypes.Unbonded, val1, true) _, _ = f.stakingKeeper.Delegate(f.ctx, addrs[1], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[1]), stakingtypes.Unbonded, val2, true) _, _ = f.stakingKeeper.Delegate(f.ctx, addrs[2], f.stakingKeeper.TokensFromConsensusPower(f.ctx, powers[2]), stakingtypes.Unbonded, val3, true) - f.stakingKeeper.EndBlocker(f.ctx) + _, err = f.stakingKeeper.EndBlocker(f.ctx) + assert.NilError(t, err) return addrs, valAddrs } diff --git a/tests/integration/gov/keeper/grpc_query_test.go b/tests/integration/gov/keeper/grpc_query_test.go index 87ff886830..7729807c5f 100644 --- a/tests/integration/gov/keeper/grpc_query_test.go +++ b/tests/integration/gov/keeper/grpc_query_test.go @@ -79,7 +79,7 @@ func TestGRPCQueryTally(t *testing.T) { "request tally after few votes", func() { proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) @@ -103,7 +103,7 @@ func TestGRPCQueryTally(t *testing.T) { "request final tally after status changed", func() { proposal.Status = v1.StatusPassed - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) proposal, _ = f.govKeeper.Proposals.Get(ctx, proposal.Id) req = &v1.QueryTallyResultRequest{ProposalId: proposal.Id} @@ -201,7 +201,7 @@ func TestLegacyGRPCQueryTally(t *testing.T) { "request tally after few votes", func() { proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposal.Id, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) @@ -225,7 +225,7 @@ func TestLegacyGRPCQueryTally(t *testing.T) { "request final tally after status changed", func() { proposal.Status = v1.StatusPassed - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) proposal, _ = f.govKeeper.Proposals.Get(ctx, proposal.Id) req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} diff --git a/tests/integration/gov/keeper/keeper_test.go b/tests/integration/gov/keeper/keeper_test.go index 4e385e8f0d..388e0be915 100644 --- a/tests/integration/gov/keeper/keeper_test.go +++ b/tests/integration/gov/keeper/keeper_test.go @@ -48,13 +48,14 @@ type fixture struct { govKeeper *keeper.Keeper } -func initFixture(t testing.TB) *fixture { +func initFixture(tb testing.TB) *fixture { + tb.Helper() keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, distrtypes.StoreKey, stakingtypes.StoreKey, types.StoreKey, ) cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, bank.AppModuleBasic{}, gov.AppModuleBasic{}).Codec - logger := log.NewTestLogger(t) + logger := log.NewTestLogger(tb) cms := integration.CreateMultiStore(keys, logger) newCtx := sdk.NewContext(cms, cmtproto.Header{}, true, logger) @@ -94,7 +95,7 @@ func initFixture(t testing.TB) *fixture { stakingKeeper := stakingkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[stakingtypes.StoreKey]), accountKeeper, bankKeeper, authority.String(), addresscodec.NewBech32Codec(sdk.Bech32PrefixValAddr), addresscodec.NewBech32Codec(sdk.Bech32PrefixConsAddr)) // set default staking params - stakingKeeper.SetParams(newCtx, stakingtypes.DefaultParams()) + assert.NilError(tb, stakingKeeper.SetParams(newCtx, stakingtypes.DefaultParams())) distrKeeper := distrkeeper.NewKeeper( cdc, runtime.NewKVStoreService(keys[distrtypes.StoreKey]), accountKeeper, bankKeeper, stakingKeeper, distrtypes.ModuleName, authority.String(), @@ -117,12 +118,12 @@ func initFixture(t testing.TB) *fixture { authority.String(), ) err := govKeeper.ProposalID.Set(newCtx, 1) - assert.NilError(t, err) + assert.NilError(tb, err) govRouter := v1beta1.NewRouter() govRouter.AddRoute(types.RouterKey, v1beta1.ProposalHandler) govKeeper.SetLegacyRouter(govRouter) err = govKeeper.Params.Set(newCtx, v1.DefaultParams()) - assert.NilError(t, err) + assert.NilError(tb, err) authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts, nil) bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil) diff --git a/tests/integration/gov/keeper/tally_test.go b/tests/integration/gov/keeper/tally_test.go index 8f77b5db18..2a3f1bca23 100644 --- a/tests/integration/gov/keeper/tally_test.go +++ b/tests/integration/gov/keeper/tally_test.go @@ -26,7 +26,7 @@ func TestTallyNoOneVotes(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) proposal, ok := f.govKeeper.Proposals.Get(ctx, proposalID) assert.Assert(t, ok) @@ -53,7 +53,7 @@ func TestTallyNoQuorum(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) err = f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "") assert.NilError(t, err) @@ -79,7 +79,7 @@ func TestTallyOnlyValidatorsAllYes(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) @@ -108,7 +108,7 @@ func TestTallyOnlyValidators51No(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) @@ -135,7 +135,7 @@ func TestTallyOnlyValidators51Yes(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionNo), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) @@ -163,7 +163,7 @@ func TestTallyOnlyValidatorsVetoed(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) @@ -192,7 +192,7 @@ func TestTallyOnlyValidatorsAbstainPasses(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) @@ -221,7 +221,7 @@ func TestTallyOnlyValidatorsAbstainFails(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) @@ -251,7 +251,7 @@ func TestTallyOnlyValidatorsNonVoter(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddr1, v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, valAccAddr2, v1.NewNonSplitVoteOption(v1.OptionNo), "")) @@ -281,14 +281,15 @@ func TestTallyDelgatorOverride(t *testing.T) { _, err := f.stakingKeeper.Delegate(ctx, addrs[4], delTokens, stakingtypes.Unbonded, val1, true) assert.NilError(t, err) - f.stakingKeeper.EndBlocker(ctx) + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) tp := TestProposal proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[2], v1.NewNonSplitVoteOption(v1.OptionYes), "")) @@ -320,14 +321,15 @@ func TestTallyDelgatorInherit(t *testing.T) { _, err := f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) assert.NilError(t, err) - f.stakingKeeper.EndBlocker(ctx) + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) tp := TestProposal proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionNo), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) @@ -362,14 +364,15 @@ func TestTallyDelgatorMultipleOverride(t *testing.T) { _, err = f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val2, true) assert.NilError(t, err) - f.stakingKeeper.EndBlocker(ctx) + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) tp := TestProposal proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionYes), "")) @@ -407,14 +410,15 @@ func TestTallyDelgatorMultipleInherit(t *testing.T) { _, err = f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) assert.NilError(t, err) - f.stakingKeeper.EndBlocker(ctx) + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) tp := TestProposal proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) @@ -449,18 +453,19 @@ func TestTallyJailedValidator(t *testing.T) { _, err = f.stakingKeeper.Delegate(ctx, addrs[3], delTokens, stakingtypes.Unbonded, val3, true) assert.NilError(t, err) - f.stakingKeeper.EndBlocker(ctx) + _, err = f.stakingKeeper.EndBlocker(ctx) + assert.NilError(t, err) consAddr, err := val2.GetConsAddr() assert.NilError(t, err) - f.stakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr)) + assert.NilError(t, f.stakingKeeper.Jail(ctx, consAddr)) tp := TestProposal proposal, err := f.govKeeper.SubmitProposal(ctx, tp, "", "test", "description", addrs[0], false) assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) @@ -496,7 +501,7 @@ func TestTallyValidatorMultipleDelegations(t *testing.T) { assert.NilError(t, err) proposalID := proposal.Id proposal.Status = v1.StatusVotingPeriod - f.govKeeper.SetProposal(ctx, proposal) + assert.NilError(t, f.govKeeper.SetProposal(ctx, proposal)) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), "")) assert.NilError(t, f.govKeeper.AddVote(ctx, proposalID, addrs[1], v1.NewNonSplitVoteOption(v1.OptionNo), "")) diff --git a/tests/integration/rapidgen/rapidgen.go b/tests/integration/rapidgen/rapidgen.go index ec37e51ddd..102ebda9ab 100644 --- a/tests/integration/rapidgen/rapidgen.go +++ b/tests/integration/rapidgen/rapidgen.go @@ -129,9 +129,9 @@ var ( GenType(&disttypes.MsgWithdrawDelegatorReward{}, &distapi.MsgWithdrawDelegatorReward{}, GenOpts), GenType(&disttypes.MsgWithdrawValidatorCommission{}, &distapi.MsgWithdrawValidatorCommission{}, GenOpts), GenType(&disttypes.MsgSetWithdrawAddress{}, &distapi.MsgSetWithdrawAddress{}, GenOpts), - GenType(&disttypes.MsgFundCommunityPool{}, &distapi.MsgFundCommunityPool{}, GenOpts), // nolint:staticcheck // testing legacy code path + GenType(&disttypes.MsgFundCommunityPool{}, &distapi.MsgFundCommunityPool{}, GenOpts), GenType(&disttypes.MsgUpdateParams{}, &distapi.MsgUpdateParams{}, GenOpts.WithDisallowNil()), - GenType(&disttypes.MsgCommunityPoolSpend{}, &distapi.MsgCommunityPoolSpend{}, GenOpts), // nolint:staticcheck // testing legacy code path + GenType(&disttypes.MsgCommunityPoolSpend{}, &distapi.MsgCommunityPoolSpend{}, GenOpts), GenType(&disttypes.MsgDepositValidatorRewardsPool{}, &distapi.MsgDepositValidatorRewardsPool{}, GenOpts), // evidence @@ -273,8 +273,8 @@ var ( GenType(&stakingtypes.StakeAuthorization{}, &stakingapi.StakeAuthorization{}, GenOpts), - GenType(&upgradetypes.CancelSoftwareUpgradeProposal{}, &upgradeapi.CancelSoftwareUpgradeProposal{}, GenOpts), // nolint:staticcheck // testing legacy code path - GenType(&upgradetypes.SoftwareUpgradeProposal{}, &upgradeapi.SoftwareUpgradeProposal{}, GenOpts.WithDisallowNil()), // nolint:staticcheck // testing legacy code path + GenType(&upgradetypes.CancelSoftwareUpgradeProposal{}, &upgradeapi.CancelSoftwareUpgradeProposal{}, GenOpts), //nolint:staticcheck // testing registration of legacy deprecated type + GenType(&upgradetypes.SoftwareUpgradeProposal{}, &upgradeapi.SoftwareUpgradeProposal{}, GenOpts.WithDisallowNil()), //nolint:staticcheck // testing registration of legacy deprecated type GenType(&upgradetypes.Plan{}, &upgradeapi.Plan{}, GenOpts.WithDisallowNil()), GenType(&vestingtypes.BaseVestingAccount{}, &vestingapi.BaseVestingAccount{}, GenOpts.WithDisallowNil()), diff --git a/tests/integration/runtime/query_test.go b/tests/integration/runtime/query_test.go index 3ae7a2835f..00dbe8dd76 100644 --- a/tests/integration/runtime/query_test.go +++ b/tests/integration/runtime/query_test.go @@ -72,7 +72,7 @@ func TestQueryAppConfig(t *testing.T) { t.Parallel() f := initFixture(t) - res, err := f.appQueryClient.Config(f.ctx, &appv1alpha1.QueryConfigRequest{}) + res, err := f.appQueryClient.Config(f.ctx, &appv1alpha1.QueryConfigRequest{}) //nolint:staticcheck // used for testing the deprecated code assert.NilError(t, err) // app config is not nil assert.Assert(t, res != nil && res.Config != nil) diff --git a/tests/integration/slashing/keeper/keeper_test.go b/tests/integration/slashing/keeper/keeper_test.go index d43c07f1df..fc296c86d3 100644 --- a/tests/integration/slashing/keeper/keeper_test.go +++ b/tests/integration/slashing/keeper/keeper_test.go @@ -50,13 +50,14 @@ type fixture struct { valAddrs []sdk.ValAddress } -func initFixture(t testing.TB) *fixture { +func initFixture(tb testing.TB) *fixture { + tb.Helper() keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, slashingtypes.StoreKey, stakingtypes.StoreKey, ) cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}).Codec - logger := log.NewTestLogger(t) + logger := log.NewTestLogger(tb) cms := integration.CreateMultiStore(keys, logger) newCtx := sdk.NewContext(cms, cmtproto.Header{}, true, logger) @@ -112,18 +113,18 @@ func initFixture(t testing.TB) *fixture { slashingtypes.RegisterQueryServer(integrationApp.QueryHelper(), slashingkeeper.NewQuerier(slashingKeeper)) // set default staking params - stakingKeeper.SetParams(sdkCtx, stakingtypes.DefaultParams()) + require.NoError(tb, stakingKeeper.SetParams(sdkCtx, stakingtypes.DefaultParams())) // TestParams set the SignedBlocksWindow to 1000 and MaxMissedBlocksPerWindow to 500 - slashingKeeper.SetParams(sdkCtx, testutil.TestParams()) + require.NoError(tb, slashingKeeper.SetParams(sdkCtx, testutil.TestParams())) addrDels := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, sdkCtx, 6, stakingKeeper.TokensFromConsensusPower(sdkCtx, 200)) valAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels) info1 := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[0]), int64(4), int64(3), time.Unix(2, 0), false, int64(10)) info2 := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addrDels[1]), int64(5), int64(4), time.Unix(2, 0), false, int64(10)) - slashingKeeper.SetValidatorSigningInfo(sdkCtx, sdk.ConsAddress(addrDels[0]), info1) - slashingKeeper.SetValidatorSigningInfo(sdkCtx, sdk.ConsAddress(addrDels[1]), info2) + require.NoError(tb, slashingKeeper.SetValidatorSigningInfo(sdkCtx, sdk.ConsAddress(addrDels[0]), info1)) + require.NoError(tb, slashingKeeper.SetValidatorSigningInfo(sdkCtx, sdk.ConsAddress(addrDels[1]), info2)) return &fixture{ app: integrationApp, @@ -143,7 +144,7 @@ func TestUnJailNotBonded(t *testing.T) { p, err := f.stakingKeeper.GetParams(f.ctx) assert.NilError(t, err) p.MaxValidators = 5 - f.stakingKeeper.SetParams(f.ctx, p) + require.NoError(t, f.stakingKeeper.SetParams(f.ctx, p)) pks := simtestutil.CreateTestPubKeys(6) tstaking := stakingtestutil.NewHelper(t, f.ctx, f.stakingKeeper) @@ -154,7 +155,8 @@ func TestUnJailNotBonded(t *testing.T) { tstaking.CreateValidatorWithValPower(addr, val, 100, true) } - f.stakingKeeper.EndBlocker(f.ctx) + _, err = f.stakingKeeper.EndBlocker(f.ctx) + require.NoError(t, err) f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // create a 6th validator with less power than the cliff validator (won't be bonded) @@ -167,7 +169,8 @@ func TestUnJailNotBonded(t *testing.T) { assert.NilError(t, err) assert.Assert(t, res != nil) - f.stakingKeeper.EndBlocker(f.ctx) + _, err = f.stakingKeeper.EndBlocker(f.ctx) + require.NoError(t, err) f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) tstaking.CheckValidator(addr, stakingtypes.Unbonded, false) @@ -176,7 +179,8 @@ func TestUnJailNotBonded(t *testing.T) { assert.Equal(t, p.BondDenom, tstaking.Denom) tstaking.Undelegate(sdk.AccAddress(addr), addr, f.stakingKeeper.TokensFromConsensusPower(f.ctx, 1), true) - f.stakingKeeper.EndBlocker(f.ctx) + _, err = f.stakingKeeper.EndBlocker(f.ctx) + require.NoError(t, err) f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // verify that validator is jailed @@ -193,12 +197,14 @@ func TestUnJailNotBonded(t *testing.T) { ) assert.ErrorContains(t, err, "cannot be unjailed") - f.stakingKeeper.EndBlocker(f.ctx) + _, err = f.stakingKeeper.EndBlocker(f.ctx) + require.NoError(t, err) f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // bond to meet minimum self-delegation tstaking.DelegateWithPower(sdk.AccAddress(addr), addr, 1) - f.stakingKeeper.EndBlocker(f.ctx) + _, err = f.stakingKeeper.EndBlocker(f.ctx) + require.NoError(t, err) f.ctx = f.ctx.WithBlockHeight(f.ctx.BlockHeight() + 1) // verify we can immediately unjail @@ -343,7 +349,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { params, err := f.stakingKeeper.GetParams(f.ctx) require.NoError(t, err) params.MaxValidators = 1 - f.stakingKeeper.SetParams(f.ctx, params) + require.NoError(t, f.stakingKeeper.SetParams(f.ctx, params)) power := int64(100) pks := simtestutil.CreateTestPubKeys(3) @@ -437,7 +443,7 @@ func TestValidatorDippingInAndOut(t *testing.T) { assert.NilError(t, err) // validator rejoins and starts signing again - f.stakingKeeper.Unjail(f.ctx, consAddr) + require.NoError(t, f.stakingKeeper.Unjail(f.ctx, consAddr)) err = f.slashingKeeper.HandleValidatorSignature(f.ctx, val.Address(), newPower, comet.BlockIDFlagCommit) assert.NilError(t, err) diff --git a/tests/integration/staking/keeper/common_test.go b/tests/integration/staking/keeper/common_test.go index f4958b1b86..7ed49482d3 100644 --- a/tests/integration/staking/keeper/common_test.go +++ b/tests/integration/staking/keeper/common_test.go @@ -53,6 +53,8 @@ func init() { // intended to be used with require/assert: require.True(ValEq(...)) func ValEq(t *testing.T, exp, got types.Validator) (*testing.T, bool, string, types.Validator, types.Validator) { + t.Helper() + return t, exp.MinEqual(&got), "expected:\n%v\ngot:\n%v", exp, got } @@ -65,6 +67,8 @@ func generateAddresses(f *fixture, numAddrs int) ([]sdk.AccAddress, []sdk.ValAdd } func createValidators(t *testing.T, f *fixture, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress, []types.Validator) { + t.Helper() + addrs := simtestutil.AddTestAddrsIncremental(f.bankKeeper, f.stakingKeeper, f.sdkCtx, 5, f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 300)) valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) pks := simtestutil.CreateTestPubKeys(5) @@ -91,13 +95,15 @@ func createValidators(t *testing.T, f *fixture, powers []int64) ([]sdk.AccAddres return addrs, valAddrs, vals } -func initFixture(t testing.TB) *fixture { +func initFixture(tb testing.TB) *fixture { + tb.Helper() + keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, types.StoreKey, ) cdc := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, staking.AppModuleBasic{}).Codec - logger := log.NewTestLogger(t) + logger := log.NewTestLogger(tb) cms := integration.CreateMultiStore(keys, logger) newCtx := sdk.NewContext(cms, cmtprototypes.Header{}, true, logger) @@ -152,7 +158,7 @@ func initFixture(t testing.TB) *fixture { types.RegisterQueryServer(integrationApp.QueryHelper(), stakingkeeper.NewQuerier(stakingKeeper)) // set default staking params - assert.NilError(t, stakingKeeper.SetParams(sdkCtx, types.DefaultParams())) + assert.NilError(tb, stakingKeeper.SetParams(sdkCtx, types.DefaultParams())) f := fixture{ app: integrationApp, diff --git a/tests/integration/staking/keeper/determinstic_test.go b/tests/integration/staking/keeper/determinstic_test.go index c6c0f6377d..170c51535d 100644 --- a/tests/integration/staking/keeper/determinstic_test.go +++ b/tests/integration/staking/keeper/determinstic_test.go @@ -65,6 +65,8 @@ type deterministicFixture struct { } func initDeterministicFixture(t *testing.T) *deterministicFixture { + t.Helper() + keys := storetypes.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, ) @@ -184,7 +186,9 @@ func bondTypeGenerator() *rapid.Generator[stakingtypes.BondStatus] { } // createValidator creates a validator with random values. -func createValidator(rt *rapid.T, f *deterministicFixture, t *testing.T) stakingtypes.Validator { +func createValidator(t *testing.T, rt *rapid.T) stakingtypes.Validator { + t.Helper() + pubkey := pubKeyGenerator().Draw(rt, "pubkey") pubkeyAny, err := codectypes.NewAnyWithValue(&pubkey) assert.NilError(t, err) @@ -214,21 +218,27 @@ func createValidator(rt *rapid.T, f *deterministicFixture, t *testing.T) staking } // createAndSetValidatorWithStatus creates a validator with random values but with given status and sets to the state -func createAndSetValidatorWithStatus(rt *rapid.T, f *deterministicFixture, t *testing.T, status stakingtypes.BondStatus) stakingtypes.Validator { - val := createValidator(rt, f, t) +func createAndSetValidatorWithStatus(t *testing.T, rt *rapid.T, f *deterministicFixture, status stakingtypes.BondStatus) stakingtypes.Validator { + t.Helper() + + val := createValidator(t, rt) val.Status = status - setValidator(f, t, val) + setValidator(t, f, val) return val } // createAndSetValidator creates a validator with random values and sets to the state -func createAndSetValidator(rt *rapid.T, f *deterministicFixture, t *testing.T) stakingtypes.Validator { - val := createValidator(rt, f, t) - setValidator(f, t, val) +func createAndSetValidator(t *testing.T, rt *rapid.T, f *deterministicFixture) stakingtypes.Validator { + t.Helper() + + val := createValidator(t, rt) + setValidator(t, f, val) return val } -func setValidator(f *deterministicFixture, t *testing.T, validator stakingtypes.Validator) { +func setValidator(t *testing.T, f *deterministicFixture, validator stakingtypes.Validator) { + t.Helper() + assert.NilError(t, f.stakingKeeper.SetValidator(f.ctx, validator)) assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.ctx, validator)) assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.ctx, validator)) @@ -246,14 +256,16 @@ func setValidator(f *deterministicFixture, t *testing.T, validator stakingtypes. } // getStaticValidator creates a validator with hard-coded values and sets to the state. -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) +func getStaticValidator(t *testing.T, f *deterministicFixture) stakingtypes.Validator { + t.Helper() + + 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) assert.NilError(t, err) validator := stakingtypes.Validator{ OperatorAddress: validator1, - ConsensusPubkey: pubkeyAny, + ConsensusPubkey: pubKeyAny, Jailed: false, Status: stakingtypes.Bonded, Tokens: math.NewInt(100), @@ -275,19 +287,21 @@ func getStaticValidator(f *deterministicFixture, t *testing.T) stakingtypes.Vali MinSelfDelegation: math.NewInt(10), } - setValidator(f, t, validator) + setValidator(t, f, validator) return validator } // getStaticValidator2 creates a validator with hard-coded values and sets to the state. -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) +func getStaticValidator2(t *testing.T, f *deterministicFixture) stakingtypes.Validator { + t.Helper() + + 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) assert.NilError(t, err) validator := stakingtypes.Validator{ OperatorAddress: validator2, - ConsensusPubkey: pubkeyAny, + ConsensusPubkey: pubKeyAny, Jailed: true, Status: stakingtypes.Bonded, Tokens: math.NewInt(10012), @@ -308,19 +322,23 @@ func getStaticValidator2(f *deterministicFixture, t *testing.T) stakingtypes.Val ), MinSelfDelegation: math.NewInt(1), } - setValidator(f, t, validator) + setValidator(t, f, validator) return validator } // createDelegationAndDelegate funds the delegator account with a random delegation in range 100-1000 and delegates. -func createDelegationAndDelegate(rt *rapid.T, f *deterministicFixture, t *testing.T, delegator sdk.AccAddress, validator stakingtypes.Validator) (newShares math.LegacyDec, err error) { +func createDelegationAndDelegate(t *testing.T, rt *rapid.T, f *deterministicFixture, delegator sdk.AccAddress, validator stakingtypes.Validator) (newShares math.LegacyDec, err error) { + t.Helper() + amt := f.stakingKeeper.TokensFromConsensusPower(f.ctx, rapid.Int64Range(100, 1000).Draw(rt, "amount")) - return fundAccountAndDelegate(f, t, delegator, validator, amt) + return fundAccountAndDelegate(t, f, delegator, validator, amt) } // fundAccountAndDelegate funds the delegator account with the specified delegation and delegates. -func fundAccountAndDelegate(f *deterministicFixture, t *testing.T, delegator sdk.AccAddress, validator stakingtypes.Validator, amt math.Int) (newShares math.LegacyDec, err error) { +func fundAccountAndDelegate(t *testing.T, f *deterministicFixture, delegator sdk.AccAddress, validator stakingtypes.Validator, amt math.Int) (newShares math.LegacyDec, err error) { + t.Helper() + coins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amt)) assert.NilError(t, f.bankKeeper.MintCoins(f.ctx, minttypes.ModuleName, coins)) @@ -335,7 +353,7 @@ func TestGRPCValidator(t *testing.T) { f := initDeterministicFixture(t) rapid.Check(t, func(rt *rapid.T) { - val := createAndSetValidator(rt, f, t) + val := createAndSetValidator(t, rt, f) req := &stakingtypes.QueryValidatorRequest{ ValidatorAddr: val.OperatorAddress, } @@ -344,7 +362,7 @@ func TestGRPCValidator(t *testing.T) { }) f = initDeterministicFixture(t) // reset - val := getStaticValidator(f, t) + val := getStaticValidator(t, f) req := &stakingtypes.QueryValidatorRequest{ ValidatorAddr: val.OperatorAddress, } @@ -360,7 +378,7 @@ func TestGRPCValidators(t *testing.T) { rapid.Check(t, func(rt *rapid.T) { valsCount := rapid.IntRange(1, 3).Draw(rt, "num-validators") for i := 0; i < valsCount; i++ { - createAndSetValidator(rt, f, t) + createAndSetValidator(t, rt, f) } req := &stakingtypes.QueryValidatorsRequest{ @@ -372,8 +390,8 @@ func TestGRPCValidators(t *testing.T) { }) f = initDeterministicFixture(t) // reset - getStaticValidator(f, t) - getStaticValidator2(f, t) + getStaticValidator(t, f) + getStaticValidator2(t, f) testdata.DeterministicIterations(f.ctx, t, &stakingtypes.QueryValidatorsRequest{}, f.queryClient.Validators, 2862, false) } @@ -383,12 +401,12 @@ func TestGRPCValidatorDelegations(t *testing.T) { f := initDeterministicFixture(t) rapid.Check(t, func(rt *rapid.T) { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) numDels := rapid.IntRange(1, 5).Draw(rt, "num-dels") for i := 0; i < numDels; i++ { delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") - _, err := createDelegationAndDelegate(rt, f, t, delegator, validator) + _, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) } @@ -402,12 +420,12 @@ func TestGRPCValidatorDelegations(t *testing.T) { f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) + validator := getStaticValidator(t, f) - _, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1) + _, err := fundAccountAndDelegate(t, f, delegatorAddr1, validator, f.amt1) assert.NilError(t, err) - _, err = fundAccountAndDelegate(f, t, delegatorAddr2, validator, f.amt2) + _, err = fundAccountAndDelegate(t, f, delegatorAddr2, validator, f.amt2) assert.NilError(t, err) req := &stakingtypes.QueryValidatorDelegationsRequest{ @@ -422,12 +440,12 @@ func TestGRPCValidatorUnbondingDelegations(t *testing.T) { f := initDeterministicFixture(t) rapid.Check(t, func(rt *rapid.T) { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) numDels := rapid.IntRange(1, 3).Draw(rt, "num-dels") for i := 0; i < numDels; i++ { delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") - shares, err := createDelegationAndDelegate(rt, f, t, delegator, validator) + shares, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) assert.NilError(t, err) @@ -445,14 +463,14 @@ func TestGRPCValidatorUnbondingDelegations(t *testing.T) { f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) - shares1, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1) + validator := getStaticValidator(t, f) + shares1, err := fundAccountAndDelegate(t, f, delegatorAddr1, validator, f.amt1) assert.NilError(t, err) _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegatorAddr1, validatorAddr1, shares1) assert.NilError(t, err) - shares2, err := fundAccountAndDelegate(f, t, delegatorAddr2, validator, f.amt2) + shares2, err := fundAccountAndDelegate(t, f, delegatorAddr2, validator, f.amt2) assert.NilError(t, err) _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegatorAddr2, validatorAddr1, shares2) @@ -470,9 +488,9 @@ func TestGRPCDelegation(t *testing.T) { f := initDeterministicFixture(t) rapid.Check(t, func(rt *rapid.T) { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") - _, err := createDelegationAndDelegate(rt, f, t, delegator, validator) + _, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) req := &stakingtypes.QueryDelegationRequest{ @@ -485,8 +503,8 @@ func TestGRPCDelegation(t *testing.T) { f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) - _, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1) + validator := getStaticValidator(t, f) + _, err := fundAccountAndDelegate(t, f, delegatorAddr1, validator, f.amt1) assert.NilError(t, err) req := &stakingtypes.QueryDelegationRequest{ @@ -502,9 +520,9 @@ func TestGRPCUnbondingDelegation(t *testing.T) { f := initDeterministicFixture(t) rapid.Check(t, func(rt *rapid.T) { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") - shares, err := createDelegationAndDelegate(rt, f, t, delegator, validator) + shares, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) @@ -521,9 +539,9 @@ func TestGRPCUnbondingDelegation(t *testing.T) { }) f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) + validator := getStaticValidator(t, f) - shares1, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1) + shares1, err := fundAccountAndDelegate(t, f, delegatorAddr1, validator, f.amt1) assert.NilError(t, err) _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegatorAddr1, validatorAddr1, shares1) @@ -546,8 +564,8 @@ func TestGRPCDelegatorDelegations(t *testing.T) { delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") for i := 0; i < numVals; i++ { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) - _, err := createDelegationAndDelegate(rt, f, t, delegator, validator) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) + _, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) } @@ -561,8 +579,8 @@ func TestGRPCDelegatorDelegations(t *testing.T) { f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) - _, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1) + validator := getStaticValidator(t, f) + _, err := fundAccountAndDelegate(t, f, delegatorAddr1, validator, f.amt1) assert.NilError(t, err) req := &stakingtypes.QueryDelegatorDelegationsRequest{ @@ -577,10 +595,10 @@ func TestGRPCDelegatorValidator(t *testing.T) { f := initDeterministicFixture(t) rapid.Check(t, func(rt *rapid.T) { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") - _, err := createDelegationAndDelegate(rt, f, t, delegator, validator) + _, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) req := &stakingtypes.QueryDelegatorValidatorRequest{ @@ -593,8 +611,8 @@ func TestGRPCDelegatorValidator(t *testing.T) { f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) - _, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1) + validator := getStaticValidator(t, f) + _, err := fundAccountAndDelegate(t, f, delegatorAddr1, validator, f.amt1) assert.NilError(t, err) @@ -615,8 +633,8 @@ func TestGRPCDelegatorUnbondingDelegations(t *testing.T) { delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") for i := 0; i < numVals; i++ { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) - shares, err := createDelegationAndDelegate(rt, f, t, delegator, validator) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) + shares, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) valbz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validator.GetOperator()) assert.NilError(t, err) @@ -634,8 +652,8 @@ func TestGRPCDelegatorUnbondingDelegations(t *testing.T) { f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) - shares1, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1) + validator := getStaticValidator(t, f) + shares1, err := fundAccountAndDelegate(t, f, delegatorAddr1, validator, f.amt1) assert.NilError(t, err) _, _, err = f.stakingKeeper.Undelegate(f.ctx, delegatorAddr1, validatorAddr1, shares1) @@ -656,7 +674,7 @@ func TestGRPCHistoricalInfo(t *testing.T) { numVals := rapid.IntRange(1, 5).Draw(rt, "num-vals") vals := stakingtypes.Validators{} for i := 0; i < numVals; i++ { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) vals.Validators = append(vals.Validators, validator) } @@ -682,7 +700,7 @@ func TestGRPCHistoricalInfo(t *testing.T) { f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) + validator := getStaticValidator(t, f) historicalInfo := stakingtypes.HistoricalInfo{ Header: cmtproto.Header{}, @@ -713,8 +731,8 @@ func TestGRPCDelegatorValidators(t *testing.T) { delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") for i := 0; i < numVals; i++ { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) - _, err := createDelegationAndDelegate(rt, f, t, delegator, validator) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) + _, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) } @@ -728,9 +746,9 @@ func TestGRPCDelegatorValidators(t *testing.T) { f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) + validator := getStaticValidator(t, f) - _, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1) + _, err := fundAccountAndDelegate(t, f, delegatorAddr1, validator, f.amt1) assert.NilError(t, err) req := &stakingtypes.QueryDelegatorValidatorsRequest{DelegatorAddr: delegator1} @@ -742,13 +760,13 @@ func TestGRPCPool(t *testing.T) { f := initDeterministicFixture(t) rapid.Check(t, func(rt *rapid.T) { - createAndSetValidator(rt, f, t) + createAndSetValidator(t, rt, f) testdata.DeterministicIterations(f.ctx, t, &stakingtypes.QueryPoolRequest{}, f.queryClient.Pool, 0, true) }) f = initDeterministicFixture(t) // reset - getStaticValidator(f, t) + getStaticValidator(t, f) testdata.DeterministicIterations(f.ctx, t, &stakingtypes.QueryPoolRequest{}, f.queryClient.Pool, 6242, false) } @@ -757,18 +775,18 @@ func TestGRPCRedelegations(t *testing.T) { f := initDeterministicFixture(t) rapid.Check(t, func(rt *rapid.T) { - validator := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) + validator := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) srcValAddr, err := sdk.ValAddressFromBech32(validator.OperatorAddress) assert.NilError(t, err) - validator2 := createAndSetValidatorWithStatus(rt, f, t, stakingtypes.Bonded) + validator2 := createAndSetValidatorWithStatus(t, rt, f, stakingtypes.Bonded) dstValAddr, err := sdk.ValAddressFromBech32(validator2.OperatorAddress) assert.NilError(t, err) numDels := rapid.IntRange(1, 5).Draw(rt, "num-dels") delegator := testdata.AddressGenerator(rt).Draw(rt, "delegator") - shares, err := createDelegationAndDelegate(rt, f, t, delegator, validator) + shares, err := createDelegationAndDelegate(t, rt, f, delegator, validator) assert.NilError(t, err) _, err = f.stakingKeeper.BeginRedelegation(f.ctx, delegator, srcValAddr, dstValAddr, shares) @@ -799,10 +817,10 @@ func TestGRPCRedelegations(t *testing.T) { }) f = initDeterministicFixture(t) // reset - validator := getStaticValidator(f, t) - _ = getStaticValidator2(f, t) + validator := getStaticValidator(t, f) + _ = getStaticValidator2(t, f) - shares, err := fundAccountAndDelegate(f, t, delegatorAddr1, validator, f.amt1) + shares, err := fundAccountAndDelegate(t, f, delegatorAddr1, validator, f.amt1) assert.NilError(t, err) _, err = f.stakingKeeper.BeginRedelegation(f.ctx, delegatorAddr1, validatorAddr1, validatorAddr2, shares) diff --git a/tests/integration/staking/keeper/genesis_test.go b/tests/integration/staking/keeper/genesis_test.go index 78e830dc82..ded4bc0185 100644 --- a/tests/integration/staking/keeper/genesis_test.go +++ b/tests/integration/staking/keeper/genesis_test.go @@ -18,7 +18,9 @@ import ( ) func bootstrapGenesisTest(t *testing.T, numAddrs int) (*fixture, []sdk.AccAddress) { + t.Helper() t.Parallel() + f := initFixture(t) addrDels, _ := generateAddresses(f, numAddrs) diff --git a/tests/integration/staking/keeper/grpc_query_test.go b/tests/integration/staking/keeper/grpc_query_test.go index 54d77dc67f..7675eecc8f 100644 --- a/tests/integration/staking/keeper/grpc_query_test.go +++ b/tests/integration/staking/keeper/grpc_query_test.go @@ -17,6 +17,8 @@ import ( ) func createValidatorAccs(t *testing.T, f *fixture) ([]sdk.AccAddress, []types.Validator) { + t.Helper() + addrs, _, validators := createValidators(&testing.T{}, f, []int64{9, 8, 7}) header := cmtproto.Header{ ChainID: "HelloChain", diff --git a/tests/integration/staking/keeper/slash_test.go b/tests/integration/staking/keeper/slash_test.go index 9397814b1a..294b248939 100644 --- a/tests/integration/staking/keeper/slash_test.go +++ b/tests/integration/staking/keeper/slash_test.go @@ -20,7 +20,9 @@ import ( // bootstrapSlashTest creates 3 validators and bootstrap the app. func bootstrapSlashTest(t *testing.T, power int64) (*fixture, []sdk.AccAddress, []sdk.ValAddress) { + t.Helper() t.Parallel() + f := initFixture(t) addrDels, addrVals := generateAddresses(f, 100) diff --git a/tests/integration/staking/keeper/unbonding_test.go b/tests/integration/staking/keeper/unbonding_test.go index c3a43049cd..5f730f6998 100644 --- a/tests/integration/staking/keeper/unbonding_test.go +++ b/tests/integration/staking/keeper/unbonding_test.go @@ -19,6 +19,8 @@ import ( // SetupUnbondingTests creates two validators and setup mocked staking hooks for testing unbonding func SetupUnbondingTests(t *testing.T, f *fixture, hookCalled *bool, ubdeID *uint64) (bondDenom string, addrDels []sdk.AccAddress, addrVals []sdk.ValAddress) { + t.Helper() + // setup hooks mockCtrl := gomock.NewController(t) mockStackingHooks := testutil.NewMockStakingHooks(mockCtrl) @@ -92,6 +94,8 @@ func doUnbondingDelegation( addrVals []sdk.ValAddress, hookCalled *bool, ) (completionTime time.Time, bondedAmt, notBondedAmt math.Int) { + t.Helper() + // UNDELEGATE // Save original bonded and unbonded amounts bondedAmt1 := bankKeeper.GetBalance(ctx, stakingKeeper.GetBondedPool(ctx).GetAddress(), bondDenom).Amount @@ -129,6 +133,8 @@ func doRedelegation( addrVals []sdk.ValAddress, hookCalled *bool, ) (completionTime time.Time) { + t.Helper() + var err error completionTime, err = stakingKeeper.BeginRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1], math.LegacyNewDec(1)) assert.NilError(t, err) @@ -152,6 +158,8 @@ func doValidatorUnbonding( addrVal sdk.ValAddress, hookCalled *bool, ) (validator types.Validator) { + t.Helper() + validator, found := stakingKeeper.GetValidator(ctx, addrVal) assert.Assert(t, found) // Check that status is bonded diff --git a/tests/integration/staking/keeper/validator_bench_test.go b/tests/integration/staking/keeper/validator_bench_test.go index d69d6fe4f3..adbe85519c 100644 --- a/tests/integration/staking/keeper/validator_bench_test.go +++ b/tests/integration/staking/keeper/validator_bench_test.go @@ -5,6 +5,8 @@ import ( "fmt" "testing" + "github.com/stretchr/testify/require" + "cosmossdk.io/math" storetypes "cosmossdk.io/store/types" @@ -13,7 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) -func BenchmarkGetValidator(b *testing.B) { +func BenchmarkGetValidator(tb *testing.B) { // 900 is the max number we are allowed to use in order to avoid simtestutil.CreateTestPubKeys // panic: encoding/hex: odd length hex string powersNumber := 900 @@ -25,21 +27,21 @@ func BenchmarkGetValidator(b *testing.B) { totalPower += int64(i) } - f, _, valAddrs, vals := initValidators(b, totalPower, len(powers), powers) + f, _, valAddrs, vals := initValidators(tb, totalPower, len(powers), powers) for _, validator := range vals { - f.stakingKeeper.SetValidator(f.sdkCtx, validator) + require.NoError(tb, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) } - b.ResetTimer() - for n := 0; n < b.N; n++ { + tb.ResetTimer() + for n := 0; n < tb.N; n++ { for _, addr := range valAddrs { _, _ = f.stakingKeeper.GetValidator(f.sdkCtx, addr) } } } -func BenchmarkGetValidatorDelegations(b *testing.B) { +func BenchmarkGetValidatorDelegations(tb *testing.B) { var totalPower int64 powersNumber := 10 @@ -49,17 +51,17 @@ func BenchmarkGetValidatorDelegations(b *testing.B) { totalPower += int64(i) } - f, _, valAddrs, vals := initValidators(b, totalPower, len(powers), powers) + f, _, valAddrs, vals := initValidators(tb, totalPower, len(powers), powers) for _, validator := range vals { - f.stakingKeeper.SetValidator(f.sdkCtx, validator) + require.NoError(tb, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) } delegationsNum := 1000 for _, val := range valAddrs { for i := 0; i < delegationsNum; i++ { delegator := sdk.AccAddress(fmt.Sprintf("address%d", i)) - banktestutil.FundAccount(f.sdkCtx, f.bankKeeper, delegator, - sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(int64(i))))) + require.NoError(tb, banktestutil.FundAccount(f.sdkCtx, f.bankKeeper, delegator, + sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(int64(i)))))) NewDel := types.NewDelegation(delegator.String(), val.String(), math.LegacyNewDec(int64(i))) if err := f.stakingKeeper.SetDelegation(f.sdkCtx, NewDel); err != nil { @@ -68,13 +70,13 @@ func BenchmarkGetValidatorDelegations(b *testing.B) { } } - b.ResetTimer() - for n := 0; n < b.N; n++ { + tb.ResetTimer() + for n := 0; n < tb.N; n++ { updateValidatorDelegations(f, valAddrs[0], sdk.ValAddress("val")) } } -func BenchmarkGetValidatorDelegationsLegacy(b *testing.B) { +func BenchmarkGetValidatorDelegationsLegacy(tb *testing.B) { var totalPower int64 powersNumber := 10 @@ -84,17 +86,17 @@ func BenchmarkGetValidatorDelegationsLegacy(b *testing.B) { totalPower += int64(i) } - f, _, valAddrs, vals := initValidators(b, totalPower, len(powers), powers) + f, _, valAddrs, vals := initValidators(tb, totalPower, len(powers), powers) for _, validator := range vals { - f.stakingKeeper.SetValidator(f.sdkCtx, validator) + require.NoError(tb, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) } delegationsNum := 1000 for _, val := range valAddrs { for i := 0; i < delegationsNum; i++ { delegator := sdk.AccAddress(fmt.Sprintf("address%d", i)) - banktestutil.FundAccount(f.sdkCtx, f.bankKeeper, delegator, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(int64(i))))) + require.NoError(tb, banktestutil.FundAccount(f.sdkCtx, f.bankKeeper, delegator, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(int64(i)))))) NewDel := types.NewDelegation(delegator.String(), val.String(), math.LegacyNewDec(int64(i))) if err := f.stakingKeeper.SetDelegation(f.sdkCtx, NewDel); err != nil { panic(err) @@ -102,8 +104,8 @@ func BenchmarkGetValidatorDelegationsLegacy(b *testing.B) { } } - b.ResetTimer() - for n := 0; n < b.N; n++ { + tb.ResetTimer() + for n := 0; n < tb.N; n++ { updateValidatorDelegationsLegacy(f, valAddrs[0], sdk.ValAddress("val")) } } @@ -129,7 +131,9 @@ func updateValidatorDelegationsLegacy(f *fixture, existingValAddr, newValAddr sd panic(err) } delegation.ValidatorAddress = newValAddr.String() - k.SetDelegation(f.sdkCtx, delegation) + if err := k.SetDelegation(f.sdkCtx, delegation); err != nil { + panic(err) + } } } } @@ -160,6 +164,8 @@ func updateValidatorDelegations(f *fixture, existingValAddr, newValAddr sdk.ValA delegation.ValidatorAddress = newValAddr.String() // add with new operator addr - k.SetDelegation(f.sdkCtx, delegation) + if err := k.SetDelegation(f.sdkCtx, delegation); err != nil { + panic(err) + } } } diff --git a/tests/integration/staking/keeper/validator_test.go b/tests/integration/staking/keeper/validator_test.go index 06b8f8d381..e5a8b291b0 100644 --- a/tests/integration/staking/keeper/validator_test.go +++ b/tests/integration/staking/keeper/validator_test.go @@ -25,13 +25,15 @@ func newMonikerValidator(tb testing.TB, operator sdk.ValAddress, pubKey cryptoty return v } -func bootstrapValidatorTest(t testing.TB, power int64, numAddrs int) (*fixture, []sdk.AccAddress, []sdk.ValAddress) { - f := initFixture(t) +func bootstrapValidatorTest(tb testing.TB, power int64, numAddrs int) (*fixture, []sdk.AccAddress, []sdk.ValAddress) { + tb.Helper() + + f := initFixture(tb) addrDels, addrVals := generateAddresses(f, numAddrs) bondDenom, err := f.stakingKeeper.BondDenom(f.sdkCtx) - assert.NilError(t, err) + assert.NilError(tb, err) amt := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) totalSupply := sdk.NewCoins(sdk.NewCoin(bondDenom, amt.MulRaw(int64(len(addrDels))))) @@ -41,18 +43,20 @@ func bootstrapValidatorTest(t testing.TB, power int64, numAddrs int) (*fixture, // set bonded pool supply f.accountKeeper.SetModuleAccount(f.sdkCtx, notBondedPool) - assert.NilError(t, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), totalSupply)) + assert.NilError(tb, banktestutil.FundModuleAccount(f.sdkCtx, f.bankKeeper, notBondedPool.GetName(), totalSupply)) return f, addrDels, addrVals } -func initValidators(t testing.TB, power int64, numAddrs int, powers []int64) (*fixture, []sdk.AccAddress, []sdk.ValAddress, []types.Validator) { - f, addrs, valAddrs := bootstrapValidatorTest(t, power, numAddrs) +func initValidators(tb testing.TB, power int64, numAddrs int, powers []int64) (*fixture, []sdk.AccAddress, []sdk.ValAddress, []types.Validator) { + tb.Helper() + + f, addrs, valAddrs := bootstrapValidatorTest(tb, power, numAddrs) pks := simtestutil.CreateTestPubKeys(numAddrs) vs := make([]types.Validator, len(powers)) for i, power := range powers { - vs[i] = testutil.NewValidator(t, sdk.ValAddress(addrs[i]), pks[i]) + vs[i] = testutil.NewValidator(tb, sdk.ValAddress(addrs[i]), pks[i]) tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) vs[i], _ = vs[i].AddTokensFromDel(tokens) } @@ -100,7 +104,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { // remove enough tokens to kick out the validator below the current cliff // validator and next in line cliff validator - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, nextCliffVal) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, nextCliffVal)) shares := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 21) nextCliffVal, _ = nextCliffVal.RemoveDelShares(math.LegacyNewDecFromInt(shares)) _ = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, nextCliffVal, true) @@ -142,12 +146,13 @@ func TestSlashToZeroPowerRemoved(t *testing.T) { validator, _ = validator.AddTokensFromDel(valTokens) assert.Equal(t, types.Unbonded, validator.Status) assert.DeepEqual(t, valTokens, validator.Tokens) - f.stakingKeeper.SetValidatorByConsAddr(f.sdkCtx, validator) + assert.NilError(t, f.stakingKeeper.SetValidatorByConsAddr(f.sdkCtx, validator)) validator = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validator, true) assert.DeepEqual(t, valTokens, validator.Tokens) // slash the validator by 100% - f.stakingKeeper.Slash(f.sdkCtx, sdk.ConsAddress(PKs[0].Address()), 0, 100, math.LegacyOneDec()) + _, err = f.stakingKeeper.Slash(f.sdkCtx, sdk.ConsAddress(PKs[0].Address()), 0, 100, math.LegacyOneDec()) + assert.NilError(t, err) // apply TM updates applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, -1) // validator should be unbonding @@ -318,7 +323,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { assert.NilError(t, err) nMax := uint32(2) params.MaxValidators = nMax - f.stakingKeeper.SetParams(f.sdkCtx, params) + assert.NilError(t, f.stakingKeeper.SetParams(f.sdkCtx, params)) // initialize some validators into the state powers := []int64{0, 100, 400, 400} @@ -344,7 +349,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { assert.Assert(ValEq(t, validators[3], resValidators[1])) // delegate 500 tokens to validator 0 - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0]) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0])) delTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 500) validators[0], _ = validators[0].AddTokensFromDel(delTokens) notBondedPool := f.stakingKeeper.GetNotBondedPool(f.sdkCtx) @@ -381,7 +386,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { validators[3], err = f.stakingKeeper.GetValidator(f.sdkCtx, valbz) assert.NilError(t, err) - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3]) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3])) validators[3], _ = validators[3].AddTokensFromDel(f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1)) notBondedPool = f.stakingKeeper.GetNotBondedPool(f.sdkCtx) @@ -397,7 +402,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { assert.Assert(ValEq(t, validators[3], resValidators[1])) // validator 3 kicked out temporarily - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3]) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3])) rmTokens := validators[3].TokensFromShares(math.LegacyNewDec(201)).TruncateInt() validators[3], _ = validators[3].RemoveDelShares(math.LegacyNewDec(201)) @@ -413,7 +418,7 @@ func TestGetValidatorsEdgeCases(t *testing.T) { assert.Assert(ValEq(t, validators[2], resValidators[1])) // validator 3 does not get spot back - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3]) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[3])) validators[3], _ = validators[3].AddTokensFromDel(math.NewInt(200)) notBondedPool = f.stakingKeeper.GetNotBondedPool(f.sdkCtx) @@ -437,7 +442,7 @@ func TestValidatorBondHeight(t *testing.T) { params, err := f.stakingKeeper.GetParams(f.sdkCtx) assert.NilError(t, err) params.MaxValidators = 2 - f.stakingKeeper.SetParams(f.sdkCtx, params) + assert.NilError(t, f.stakingKeeper.SetParams(f.sdkCtx, params)) // initialize some validators into the state var validators [3]types.Validator @@ -466,8 +471,8 @@ func TestValidatorBondHeight(t *testing.T) { assert.Assert(ValEq(t, validators[0], resValidators[0])) assert.Assert(ValEq(t, validators[1], resValidators[1])) - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[1]) - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[2]) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[1])) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[2])) delTokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 50) validators[1], _ = validators[1].AddTokensFromDel(delTokens) validators[2], _ = validators[2].AddTokensFromDel(delTokens) @@ -484,8 +489,8 @@ func TestFullValidatorSetPowerChange(t *testing.T) { f, addrs, _ := bootstrapValidatorTest(t, 1000, 20) params, err := f.stakingKeeper.GetParams(f.sdkCtx) assert.NilError(t, err) - max := 2 - params.MaxValidators = uint32(2) + maxValidators := 2 + params.MaxValidators = uint32(maxValidators) assert.NilError(t, f.stakingKeeper.SetParams(f.sdkCtx, params)) // initialize some validators into the state @@ -511,7 +516,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { assert.Equal(t, types.Unbonded, validators[4].Status) resValidators, err := f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) assert.NilError(t, err) - assert.Equal(t, max, len(resValidators)) + assert.Equal(t, maxValidators, len(resValidators)) assert.Assert(ValEq(t, validators[2], resValidators[0])) // in the order of txs assert.Assert(ValEq(t, validators[3], resValidators[1])) @@ -522,7 +527,7 @@ func TestFullValidatorSetPowerChange(t *testing.T) { validators[0] = keeper.TestingUpdateValidator(f.stakingKeeper, f.sdkCtx, validators[0], true) resValidators, err = f.stakingKeeper.GetBondedValidatorsByPower(f.sdkCtx) assert.NilError(t, err) - assert.Equal(t, max, len(resValidators)) + assert.Equal(t, maxValidators, len(resValidators)) assert.Assert(ValEq(t, validators[0], resValidators[0])) assert.Assert(ValEq(t, validators[2], resValidators[1])) } @@ -544,10 +549,10 @@ func TestApplyAndReturnValidatorSetUpdatesAllNone(t *testing.T) { // test from nothing to something // tendermintUpdate set: {} -> {c1, c3} applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) - f.stakingKeeper.SetValidator(f.sdkCtx, validators[0]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[0]) - f.stakingKeeper.SetValidator(f.sdkCtx, validators[1]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[1]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[0])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[0])) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[1])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[1])) updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) val0bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[0].GetOperator()) @@ -642,8 +647,8 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { // test validtor added at the beginning // tendermintUpdate set: {} -> {c0} - f.stakingKeeper.SetValidator(f.sdkCtx, validators[2]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[2]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[2])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[2])) updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) val2bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[2].GetOperator()) assert.NilError(t, err) @@ -652,8 +657,8 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { // test validtor added at the beginning // tendermintUpdate set: {} -> {c0} - f.stakingKeeper.SetValidator(f.sdkCtx, validators[3]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[3]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[3])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[3])) updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) val3bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[3].GetOperator()) assert.NilError(t, err) @@ -662,8 +667,8 @@ func TestApplyAndReturnValidatorSetUpdatesInserted(t *testing.T) { // test validtor added at the end // tendermintUpdate set: {} -> {c0} - f.stakingKeeper.SetValidator(f.sdkCtx, validators[4]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[4]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[4])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[4])) updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) val4bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[4].GetOperator()) assert.NilError(t, err) @@ -675,7 +680,7 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) { f, addrs, _ := bootstrapValidatorTest(t, 1000, 20) params := types.DefaultParams() params.MaxValidators = 2 - f.stakingKeeper.SetParams(f.sdkCtx, params) + assert.NilError(t, f.stakingKeeper.SetParams(f.sdkCtx, params)) powers := []int64{10, 20, 5} var validators [5]types.Validator @@ -699,8 +704,8 @@ func TestApplyAndReturnValidatorSetUpdatesWithCliffValidator(t *testing.T) { tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 10) validators[2], _ = validators[2].AddTokensFromDel(tokens) - f.stakingKeeper.SetValidator(f.sdkCtx, validators[2]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[2]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[2])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[2])) updates := applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 2) val2bz, err := f.stakingKeeper.ValidatorAddressCodec().StringToBytes(validators[2].GetOperator()) assert.NilError(t, err) @@ -729,8 +734,8 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) - f.stakingKeeper.SetValidator(f.sdkCtx, validators[i]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[i]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[i])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[i])) } // verify initial CometBFT updates are correct @@ -750,12 +755,12 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { // update initial validator set for i, power := range powers { - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[i]) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[i])) tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) - f.stakingKeeper.SetValidator(f.sdkCtx, validators[i]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[i]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[i])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[i])) } // add a new validator that goes from zero power, to non-zero power, back to @@ -767,11 +772,11 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { validator := testutil.NewValidator(t, valAddr, valPubKey) validator, _ = validator.AddTokensFromDel(amt) - f.stakingKeeper.SetValidator(f.sdkCtx, validator) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) validator, _ = validator.RemoveDelShares(math.LegacyNewDecFromInt(amt)) - f.stakingKeeper.SetValidator(f.sdkCtx, validator) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validator) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validator)) // add a new validator that increases in power valPubKey = PKs[len(validators)+2] @@ -780,8 +785,8 @@ func TestApplyAndReturnValidatorSetUpdatesNewValidator(t *testing.T) { validator = testutil.NewValidator(t, valAddr, valPubKey) tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 500) validator, _ = validator.AddTokensFromDel(tokens) - f.stakingKeeper.SetValidator(f.sdkCtx, validator) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validator) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validator)) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validator)) // verify initial CometBFT updates are correct updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, len(validators)+1) @@ -815,8 +820,8 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { validators[i] = newMonikerValidator(t, valAddr, valPubKey, moniker) tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, power) validators[i], _ = validators[i].AddTokensFromDel(tokens) - f.stakingKeeper.SetValidator(f.sdkCtx, validators[i]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[i]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[i])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[i])) } // verify initial CometBFT updates are correct @@ -840,11 +845,11 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { validators[0], err = f.stakingKeeper.GetValidator(f.sdkCtx, val0bz) assert.NilError(t, err) - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0]) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0])) tokens := f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 1) validators[0], _ = validators[0].AddTokensFromDel(tokens) - f.stakingKeeper.SetValidator(f.sdkCtx, validators[0]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[0]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[0])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[0])) // verify initial CometBFT updates are correct applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) @@ -856,17 +861,17 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { validators[1], err = f.stakingKeeper.GetValidator(f.sdkCtx, val1bz) assert.NilError(t, err) - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0]) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[0])) validators[0], _ = validators[0].RemoveDelShares(validators[0].DelegatorShares) - f.stakingKeeper.SetValidator(f.sdkCtx, validators[0]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[0]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[0])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[0])) applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 0) - f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[1]) + assert.NilError(t, f.stakingKeeper.DeleteValidatorByPowerIndex(f.sdkCtx, validators[1])) tokens = f.stakingKeeper.TokensFromConsensusPower(f.sdkCtx, 250) validators[1], _ = validators[1].AddTokensFromDel(tokens) - f.stakingKeeper.SetValidator(f.sdkCtx, validators[1]) - f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[1]) + assert.NilError(t, f.stakingKeeper.SetValidator(f.sdkCtx, validators[1])) + assert.NilError(t, f.stakingKeeper.SetValidatorByPowerIndex(f.sdkCtx, validators[1])) // verify initial CometBFT updates are correct updates = applyValidatorSetUpdates(t, f.sdkCtx, f.stakingKeeper, 1) @@ -876,6 +881,8 @@ func TestApplyAndReturnValidatorSetUpdatesBondTransition(t *testing.T) { } func applyValidatorSetUpdates(t *testing.T, ctx sdk.Context, k *keeper.Keeper, expectedUpdatesLen int) []abci.ValidatorUpdate { + t.Helper() + updates, err := k.ApplyAndReturnValidatorSetUpdates(ctx) assert.NilError(t, err) if expectedUpdatesLen >= 0 { diff --git a/tests/integration/store/rootmulti/rollback_test.go b/tests/integration/store/rootmulti/rollback_test.go index 9e4454bdcb..08f6a93fdc 100644 --- a/tests/integration/store/rootmulti/rollback_test.go +++ b/tests/integration/store/rootmulti/rollback_test.go @@ -7,6 +7,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" cmtproto "github.com/cometbft/cometbft/proto/tendermint/types" dbm "github.com/cosmos/cosmos-db" + "github.com/stretchr/testify/require" "gotest.tools/v3/assert" "cosmossdk.io/log" @@ -31,16 +32,19 @@ func TestRollback(t *testing.T) { AppHash: app.LastCommitID().Hash, } - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: header.Height, }) + require.NoError(t, err) ctx := app.NewContextLegacy(false, header) store := ctx.KVStore(app.GetKey("bank")) store.Set([]byte("key"), []byte(fmt.Sprintf("value%d", i))) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: header.Height, }) - app.Commit() + require.NoError(t, err) + _, err = app.Commit() + require.NoError(t, err) } assert.Equal(t, ver0+10, app.LastBlockHeight()) @@ -63,14 +67,17 @@ func TestRollback(t *testing.T) { Height: ver0 + i, AppHash: app.LastCommitID().Hash, } - app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: header.Height}) + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: header.Height}) + require.NoError(t, err) ctx := app.NewContextLegacy(false, header) store := ctx.KVStore(app.GetKey("bank")) store.Set([]byte("key"), []byte(fmt.Sprintf("VALUE%d", i))) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: header.Height, }) - app.Commit() + require.NoError(t, err) + _, err = app.Commit() + require.NoError(t, err) } assert.Equal(t, ver0+10, app.LastBlockHeight()) diff --git a/tests/integration/tx/aminojson/aminojson_test.go b/tests/integration/tx/aminojson/aminojson_test.go index 8d4c32e7b6..42e2dbffd7 100644 --- a/tests/integration/tx/aminojson/aminojson_test.go +++ b/tests/integration/tx/aminojson/aminojson_test.go @@ -185,6 +185,8 @@ func TestAminoJSON_Equivalence(t *testing.T) { } func newAny(t *testing.T, msg proto.Message) *anypb.Any { + t.Helper() + bz, err := proto.Marshal(msg) require.NoError(t, err) typeName := fmt.Sprintf("/%s", msg.ProtoReflect().Descriptor().FullName()) @@ -271,7 +273,7 @@ func TestAminoJSON_LegacyParity(t *testing.T) { }, "distribution/community_pool_spend_proposal_with_deposit": { gogo: &disttypes.CommunityPoolSpendProposalWithDeposit{}, - pulsar: &distapi.CommunityPoolSpendProposalWithDeposit{}, //nolint:staticcheck // keep test as is testing legacy parity + pulsar: &distapi.CommunityPoolSpendProposalWithDeposit{}, }, "distribution/msg_withdraw_delegator_reward": { gogo: &disttypes.MsgWithdrawDelegatorReward{DelegatorAddress: "foo"}, diff --git a/testutil/cmdtest/system.go b/testutil/cmdtest/system.go index 66e2604302..8146261ad0 100644 --- a/testutil/cmdtest/system.go +++ b/testutil/cmdtest/system.go @@ -61,7 +61,7 @@ func (s *System) RunWithInputC(ctx context.Context, in io.Reader, args ...string rootCmd.SetIn(in) var res RunResult - rootCmd.SetOutput(&res.Stdout) + rootCmd.SetOut(&res.Stdout) rootCmd.SetErr(&res.Stderr) rootCmd.SetArgs(args) @@ -78,7 +78,7 @@ func (s *System) MustRun(t TestingT, args ...string) RunResult { } // MustRunC calls s.RunWithInput, but also calls t.FailNow if RunResult.Err is not nil. -func (s *System) MustRunC(t TestingT, ctx context.Context, args ...string) RunResult { //nolint:revive // As a variation of MustRun, t is more important than ctx. +func (s *System) MustRunC(t TestingT, ctx context.Context, args ...string) RunResult { t.Helper() return s.MustRunWithInputC(t, ctx, bytes.NewReader(nil), args...) @@ -92,7 +92,7 @@ func (s *System) MustRunWithInput(t TestingT, in io.Reader, args ...string) RunR } // MustRunWithInputC calls s.RunWithInputC, but also calls t.FailNow if RunResult.Err is not nil. -func (s *System) MustRunWithInputC(t TestingT, ctx context.Context, in io.Reader, args ...string) RunResult { //nolint:revive // As a variation of MustRun, t is more important than ctx. +func (s *System) MustRunWithInputC(t TestingT, ctx context.Context, in io.Reader, args ...string) RunResult { t.Helper() res := s.RunWithInputC(ctx, in, args...) diff --git a/testutil/integration/router.go b/testutil/integration/router.go index 0bb9d6e792..cae9a308e3 100644 --- a/testutil/integration/router.go +++ b/testutil/integration/router.go @@ -103,7 +103,10 @@ func NewIntegrationApp( } } - bApp.Commit() + _, err := bApp.Commit() + if err != nil { + panic(fmt.Errorf("failed to commit application: %w", err)) + } ctx := sdkCtx.WithBlockHeader(cmtproto.Header{ChainID: appName}).WithIsCheckTx(true) @@ -130,7 +133,7 @@ func (app *App) RunMsg(msg sdk.Msg, option ...Option) (*codectypes.Any, error) { } if cfg.AutomaticCommit { - defer app.Commit() + defer app.Commit() //nolint:errcheck // not needed in testing } if cfg.AutomaticFinalizeBlock { diff --git a/testutil/sims/simulation_helpers_test.go b/testutil/sims/simulation_helpers_test.go index 67eef0d1a0..ed95e7b6a6 100644 --- a/testutil/sims/simulation_helpers_test.go +++ b/testutil/sims/simulation_helpers_test.go @@ -47,7 +47,6 @@ func TestGetSimulationLog(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.store, func(t *testing.T) { require.Equal(t, tt.expectedLog, GetSimulationLog(tt.store, decoders, tt.kvPairs, tt.kvPairs), tt.store) }) @@ -110,6 +109,8 @@ func checkDiffResults(t *testing.T, store1, store2 storetypes.KVStore, noDiff bo } func initTestStores(t *testing.T) (storetypes.KVStore, storetypes.KVStore) { + t.Helper() + db := dbm.NewMemDB() ms := rootmulti.NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) @@ -117,6 +118,6 @@ func initTestStores(t *testing.T) (storetypes.KVStore, storetypes.KVStore) { key2 := storetypes.NewKVStoreKey("store2") require.NotPanics(t, func() { ms.MountStoreWithDB(key1, storetypes.StoreTypeIAVL, db) }) require.NotPanics(t, func() { ms.MountStoreWithDB(key2, storetypes.StoreTypeIAVL, db) }) - require.NotPanics(t, func() { ms.LoadLatestVersion() }) + require.NotPanics(t, func() { _ = ms.LoadLatestVersion() }) return ms.GetKVStore(key1), ms.GetKVStore(key2) } diff --git a/testutil/sims/tx_helpers.go b/testutil/sims/tx_helpers.go index 0557e6b647..fd9637c53e 100644 --- a/testutil/sims/tx_helpers.go +++ b/testutil/sims/tx_helpers.go @@ -96,6 +96,8 @@ func SignCheckDeliver( t *testing.T, txCfg client.TxConfig, app *baseapp.BaseApp, header types.Header, msgs []sdk.Msg, chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { + t.Helper() + tx, err := GenSignedMockTx( rand.New(rand.NewSource(time.Now().UnixNano())), txCfg, @@ -140,7 +142,8 @@ func SignCheckDeliver( require.False(t, finalizeSuccess) } - app.Commit() + _, err = app.Commit() + require.NoError(t, err) gInfo := sdk.GasInfo{GasWanted: uint64(txResult.GasWanted), GasUsed: uint64(txResult.GasUsed)} txRes := sdk.Result{Data: txResult.Data, Log: txResult.Log, Events: txResult.Events} diff --git a/types/address.go b/types/address.go index ed725103c3..49e5980bd2 100644 --- a/types/address.go +++ b/types/address.go @@ -320,11 +320,11 @@ func (aa AccAddress) String() string { func (aa AccAddress) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(aa.String())) + _, _ = s.Write([]byte(aa.String())) case 'p': - s.Write([]byte(fmt.Sprintf("%p", aa))) + _, _ = s.Write([]byte(fmt.Sprintf("%p", aa))) default: - s.Write([]byte(fmt.Sprintf("%X", []byte(aa)))) + _, _ = s.Write([]byte(fmt.Sprintf("%X", []byte(aa)))) } } @@ -484,11 +484,11 @@ func (va ValAddress) String() string { func (va ValAddress) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(va.String())) + _, _ = s.Write([]byte(va.String())) case 'p': - s.Write([]byte(fmt.Sprintf("%p", va))) + _, _ = s.Write([]byte(fmt.Sprintf("%p", va))) default: - s.Write([]byte(fmt.Sprintf("%X", []byte(va)))) + _, _ = s.Write([]byte(fmt.Sprintf("%X", []byte(va)))) } } @@ -668,11 +668,11 @@ func MustBech32ifyAddressBytes(prefix string, bs []byte) string { func (ca ConsAddress) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(ca.String())) + _, _ = s.Write([]byte(ca.String())) case 'p': - s.Write([]byte(fmt.Sprintf("%p", ca))) + _, _ = s.Write([]byte(fmt.Sprintf("%p", ca))) default: - s.Write([]byte(fmt.Sprintf("%X", []byte(ca)))) + _, _ = s.Write([]byte(fmt.Sprintf("%X", []byte(ca)))) } } diff --git a/types/address/hash_test.go b/types/address/hash_test.go index f124f5ada0..b48a27e6ff 100644 --- a/types/address/hash_test.go +++ b/types/address/hash_test.go @@ -115,6 +115,8 @@ func (a addrMock) Address() []byte { } func (a addrMock) AddressWithLen(t *testing.T) []byte { + t.Helper() + addr, err := LengthPrefix(a.Addr) assert.NoError(t, err) return addr diff --git a/types/address/store_key_test.go b/types/address/store_key_test.go index ac28f814cc..07f2915014 100644 --- a/types/address/store_key_test.go +++ b/types/address/store_key_test.go @@ -32,7 +32,6 @@ func (suite *StoreKeySuite) TestLengthPrefix() { } for _, tt := range tests { - tt := tt suite.Run(tt.name, func() { storeKey, err := address.LengthPrefix(tt.addr) if tt.expErr { diff --git a/types/address_test.go b/types/address_test.go index 230b1a16f1..780fee0e62 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -58,14 +58,17 @@ func (s *addressTestSuite) TestEmptyAddresses() { s.Require().Equal((types.ConsAddress{}).String(), "") accAddr, err := types.AccAddressFromBech32("") + s.Require().NotNil(accAddr) s.Require().True(accAddr.Empty()) s.Require().Error(err) valAddr, err := types.ValAddressFromBech32("") + s.Require().NotNil(accAddr) s.Require().True(valAddr.Empty()) s.Require().Error(err) consAddr, err := types.ConsAddressFromBech32("") + s.Require().NotNil(accAddr) s.Require().True(consAddr.Empty()) s.Require().Error(err) } @@ -92,7 +95,8 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() { pub := &ed25519.PubKey{Key: pubBz} for i := 0; i < 1000; i++ { - rand.Read(pub.Key) + _, err := rand.Read(pub.Key) + s.Require().NoError(err) acc := types.AccAddress(pub.Address()) res := types.AccAddress{} @@ -101,7 +105,7 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() { s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res, err := types.AccAddressFromBech32(str) + res, err = types.AccAddressFromBech32(str) s.Require().Nil(err) s.Require().Equal(acc, res) @@ -133,7 +137,8 @@ func (s *addressTestSuite) TestAddrCache() { // Use a random key pubBz := make([]byte, ed25519.PubKeySize) pub := &ed25519.PubKey{Key: pubBz} - rand.Read(pub.Key) + _, err := rand.Read(pub.Key) + s.Require().NoError(err) // Set SDK bech32 prefixes to 'osmo' prefix := "osmo" @@ -170,7 +175,8 @@ func (s *addressTestSuite) TestAddrCacheDisabled() { // Use a random key pubBz := make([]byte, ed25519.PubKeySize) pub := &ed25519.PubKey{Key: pubBz} - rand.Read(pub.Key) + _, err := rand.Read(pub.Key) + s.Require().NoError(err) // Set SDK bech32 prefixes to 'osmo' prefix := "osmo" @@ -202,7 +208,8 @@ func (s *addressTestSuite) TestValAddr() { pub := &ed25519.PubKey{Key: pubBz} for i := 0; i < 20; i++ { - rand.Read(pub.Key) + _, err := rand.Read(pub.Key) + s.Require().NoError(err) acc := types.ValAddress(pub.Address()) res := types.ValAddress{} @@ -211,7 +218,7 @@ func (s *addressTestSuite) TestValAddr() { s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res, err := types.ValAddressFromBech32(str) + res, err = types.ValAddressFromBech32(str) s.Require().Nil(err) s.Require().Equal(acc, res) @@ -243,7 +250,8 @@ func (s *addressTestSuite) TestConsAddress() { pub := &ed25519.PubKey{Key: pubBz} for i := 0; i < 20; i++ { - rand.Read(pub.Key[:]) + _, err := rand.Read(pub.Key) + s.Require().NoError(err) acc := types.ConsAddress(pub.Address()) res := types.ConsAddress{} @@ -252,7 +260,7 @@ func (s *addressTestSuite) TestConsAddress() { s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res, err := types.ConsAddressFromBech32(str) + res, err = types.ConsAddressFromBech32(str) s.Require().Nil(err) s.Require().Equal(acc, res) @@ -293,7 +301,8 @@ func (s *addressTestSuite) TestConfiguredPrefix() { pub := &ed25519.PubKey{Key: pubBz} for length := 1; length < 10; length++ { for times := 1; times < 20; times++ { - rand.Read(pub.Key[:]) + _, err := rand.Read(pub.Key[:]) + s.Require().NoError(err) // Test if randomly generated prefix of a given length works prefix := RandString(length) @@ -308,7 +317,7 @@ func (s *addressTestSuite) TestConfiguredPrefix() { acc.String(), prefix+types.PrefixAccount), acc.String()) - bech32Pub := legacybech32.MustMarshalPubKey(legacybech32.AccPK, pub) //nolint:staticcheck // SA1019: legacybech32 is deprecated: use the bech32 package instead. + bech32Pub := legacybech32.MustMarshalPubKey(legacybech32.AccPK, pub) s.Require().True(strings.HasPrefix( bech32Pub, prefix+types.PrefixPublic)) @@ -322,7 +331,7 @@ func (s *addressTestSuite) TestConfiguredPrefix() { val.String(), prefix+types.PrefixValidator+types.PrefixAddress)) - bech32ValPub := legacybech32.MustMarshalPubKey(legacybech32.ValPK, pub) //nolint:staticcheck // SA1019: legacybech32 is deprecated: use the bech32 package instead. + bech32ValPub := legacybech32.MustMarshalPubKey(legacybech32.ValPK, pub) s.Require().True(strings.HasPrefix( bech32ValPub, prefix+types.PrefixValidator+types.PrefixPublic)) @@ -336,7 +345,7 @@ func (s *addressTestSuite) TestConfiguredPrefix() { cons.String(), prefix+types.PrefixConsensus+types.PrefixAddress)) - bech32ConsPub := legacybech32.MustMarshalPubKey(legacybech32.ConsPK, pub) //nolint:staticcheck // SA1019: legacybech32 is deprecated: use the bech32 package instead. + bech32ConsPub := legacybech32.MustMarshalPubKey(legacybech32.ConsPK, pub) s.Require().True(strings.HasPrefix( bech32ConsPub, prefix+types.PrefixConsensus+types.PrefixPublic)) @@ -347,7 +356,8 @@ func (s *addressTestSuite) TestConfiguredPrefix() { func (s *addressTestSuite) TestAddressInterface() { pubBz := make([]byte, ed25519.PubKeySize) pub := &ed25519.PubKey{Key: pubBz} - rand.Read(pub.Key) + _, err := rand.Read(pub.Key) + s.Require().NoError(err) addrs := []types.Address{ types.ConsAddress(pub.Address()), @@ -453,7 +463,6 @@ func (s *addressTestSuite) TestBech32ifyAddressBytes() { {"20-byte address", args{"prefixb", addr20byte}, "prefixb1qqqsyqcyq5rqwzqfpg9scrgwpugpzysnrujsuw", false}, } for _, tt := range tests { - tt := tt s.T().Run(tt.name, func(t *testing.T) { got, err := types.Bech32ifyAddressBytes(tt.args.prefix, tt.args.bs) if (err != nil) != tt.wantErr { @@ -486,7 +495,6 @@ func (s *addressTestSuite) TestMustBech32ifyAddressBytes() { {"20-byte address", args{"prefixb", addr20byte}, "prefixb1qqqsyqcyq5rqwzqfpg9scrgwpugpzysnrujsuw", false}, } for _, tt := range tests { - tt := tt s.T().Run(tt.name, func(t *testing.T) { if tt.wantPanic { require.Panics(t, func() { types.MustBech32ifyAddressBytes(tt.args.prefix, tt.args.bs) }) diff --git a/types/coin.go b/types/coin.go index 136295eed2..6b5ff76106 100644 --- a/types/coin.go +++ b/types/coin.go @@ -420,7 +420,6 @@ func (coins Coins) SafeMulInt(x math.Int) (Coins, bool) { res := make(Coins, len(coins)) for i, coin := range coins { - coin := coin res[i] = NewCoin(coin.Denom, coin.Amount.Mul(x)) } @@ -454,7 +453,6 @@ func (coins Coins) SafeQuoInt(x math.Int) (Coins, bool) { var res Coins for _, coin := range coins { - coin := coin res = append(res, NewCoin(coin.Denom, coin.Amount.Quo(x))) } diff --git a/types/coin_benchmark_test.go b/types/coin_benchmark_test.go index 955578cf67..188208d048 100644 --- a/types/coin_benchmark_test.go +++ b/types/coin_benchmark_test.go @@ -15,6 +15,7 @@ func BenchmarkCoinsAdditionIntersect(b *testing.B) { b.ReportAllocs() benchmarkingFunc := func(numCoinsA, numCoinsB int) func(b *testing.B) { return func(b *testing.B) { + b.Helper() b.ReportAllocs() coinsA := Coins(make([]Coin, numCoinsA)) coinsB := Coins(make([]Coin, numCoinsB)) @@ -46,6 +47,7 @@ func BenchmarkCoinsAdditionNoIntersect(b *testing.B) { b.ReportAllocs() benchmarkingFunc := func(numCoinsA, numCoinsB int) func(b *testing.B) { return func(b *testing.B) { + b.Helper() b.ReportAllocs() coinsA := Coins(make([]Coin, numCoinsA)) coinsB := Coins(make([]Coin, numCoinsB)) @@ -80,6 +82,7 @@ func BenchmarkSumOfCoinAdds(b *testing.B) { // already in the sum, and (coinsPerAdd - numIntersectingCoins) that are new denoms. benchmarkingFunc := func(numAdds, coinsPerAdd, numIntersectingCoins int, sumFn func([]Coins) Coins) func(b *testing.B) { return func(b *testing.B) { + b.Helper() b.ReportAllocs() addCoins := make([]Coins, numAdds) nonIntersectingCoins := coinsPerAdd - numIntersectingCoins diff --git a/types/context_test.go b/types/context_test.go index 1a31e9becb..975964b39c 100644 --- a/types/context_test.go +++ b/types/context_test.go @@ -139,7 +139,7 @@ func (s *contextTestSuite) TestContextWithCustom() { s.Require().Equal(cp, ctx.WithConsensusParams(cp).ConsensusParams()) // test inner context - newContext := context.WithValue(ctx.Context(), struct{}{}, "value") + newContext := context.WithValue(ctx.Context(), struct{}{}, "value") //nolint:staticcheck // this is fine for testing s.Require().NotEqual(ctx.Context(), ctx.WithContext(newContext).Context()) } @@ -237,7 +237,7 @@ func (s *contextTestSuite) TestUnwrapSDKContext() { s.Require().Panics(func() { types.UnwrapSDKContext(ctx) }) // test unwrapping when we've used context.WithValue - ctx = context.WithValue(sdkCtx, struct{}{}, "bar") + ctx = context.WithValue(sdkCtx, struct{}{}, "bar") //nolint:staticcheck // this is fine for testing sdkCtx2 = types.UnwrapSDKContext(ctx) s.Require().Equal(sdkCtx, sdkCtx2) } diff --git a/types/dec_coin.go b/types/dec_coin.go index 14c40bd329..87dad30782 100644 --- a/types/dec_coin.go +++ b/types/dec_coin.go @@ -639,7 +639,7 @@ func ParseDecCoin(coinStr string) (coin DecCoin, err error) { } if err := ValidateDenom(denomStr); err != nil { - return DecCoin{}, fmt.Errorf("invalid denom cannot contain spaces: %s", err) + return DecCoin{}, fmt.Errorf("invalid denom cannot contain spaces: %w", err) } return NewDecCoinFromDec(denomStr, amount), nil diff --git a/types/mempool/priority_nonce_test.go b/types/mempool/priority_nonce_test.go index 1a0fd657f2..f4e5dd44ab 100644 --- a/types/mempool/priority_nonce_test.go +++ b/types/mempool/priority_nonce_test.go @@ -541,10 +541,8 @@ func (s *MempoolTestSuite) TestRandomTxOrderManyTimes() { // validateOrder checks that the txs are ordered by priority and nonce // in O(n^2) time by checking each tx against all the other txs func validateOrder(mtxs []sdk.Tx) error { - iterations := 0 var itxs []txSpec for i, mtx := range mtxs { - iterations++ tx := mtx.(testTx) itxs = append(itxs, txSpec{p: int(tx.priority), n: int(tx.nonce), a: tx.address, i: i}) } @@ -557,7 +555,6 @@ func validateOrder(mtxs []sdk.Tx) error { for _, a := range itxs { for _, b := range itxs { - iterations++ // when b is before a // when a is before b @@ -575,7 +572,6 @@ func validateOrder(mtxs []sdk.Tx) error { // find a tx with same sender as b and lower nonce found := false for _, c := range itxs { - iterations++ if c.a.Equals(b.a) && c.n < b.n && c.p <= a.p { found = true break diff --git a/types/module/module.go b/types/module/module.go index 506f4393b6..834c1dd72e 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -619,7 +619,6 @@ func (m *Manager) assertNoForgottenModules(setOrderFnName string, moduleNames [] } var missing []string for m := range m.Modules { - m := m if pass != nil && pass(m) { continue } @@ -861,7 +860,6 @@ func (m *Manager) GetVersionMap() VersionMap { if v, ok := v.(HasConsensusVersion); ok { version = v.ConsensusVersion() } - name := name vermap[name] = version } diff --git a/types/module/module_test.go b/types/module/module_test.go index 263314da95..026ab38c8d 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -190,7 +190,7 @@ func TestManager_RegisterQueryServices(t *testing.T) { mockAppModule1.EXPECT().RegisterServices(cfg).Times(1) mockAppModule2.EXPECT().RegisterServices(cfg).Times(1) - require.NotPanics(t, func() { mm.RegisterServices(cfg) }) + require.NotPanics(t, func() { _ = mm.RegisterServices(cfg) }) } func TestManager_InitGenesis(t *testing.T) { @@ -591,7 +591,7 @@ func (MockCoreAppModule) DefaultGenesis(target appmodule.GenesisTarget) error { if err != nil { return err } - someFieldWriter.Write([]byte(`"someKey"`)) + _, _ = someFieldWriter.Write([]byte(`"someKey"`)) return someFieldWriter.Close() } @@ -618,7 +618,7 @@ func (MockCoreAppModule) ExportGenesis(ctx context.Context, target appmodule.Gen if err != nil { return err } - wrt.Write([]byte(`"someKey"`)) + _, _ = wrt.Write([]byte(`"someKey"`)) return wrt.Close() } diff --git a/types/query/collections_pagination_test.go b/types/query/collections_pagination_test.go index 365b44cc68..87cfc549a9 100644 --- a/types/query/collections_pagination_test.go +++ b/types/query/collections_pagination_test.go @@ -169,7 +169,6 @@ func TestCollectionPagination(t *testing.T) { } for name, tc := range tcs { - tc := tc t.Run(name, func(t *testing.T) { gotResults, gotResponse, err := CollectionFilteredPaginate( ctx, diff --git a/types/simulation/account_test.go b/types/simulation/account_test.go index 85034a0d24..fd89223d95 100644 --- a/types/simulation/account_test.go +++ b/types/simulation/account_test.go @@ -24,7 +24,6 @@ func TestRandomAccounts(t *testing.T) { {"100-accounts", 100, 100}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got := simulation.RandomAccounts(r, tt.n) require.Equal(t, tt.want, len(got)) @@ -65,8 +64,6 @@ func TestRandomFees(t *testing.T) { {"0 coins", sdk.NewCoins(sdk.NewInt64Coin("aaa", 10), sdk.NewInt64Coin("bbb", 5)), false, false}, } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { got, err := simulation.RandomFees(r, sdk.Context{}, tt.spendableCoins) if (err != nil) != tt.wantErr { diff --git a/types/simulation/rand_util_test.go b/types/simulation/rand_util_test.go index c487625ed0..f00e17919d 100644 --- a/types/simulation/rand_util_test.go +++ b/types/simulation/rand_util_test.go @@ -23,7 +23,6 @@ func TestRandSubsetCoins(t *testing.T) { {"seed=99", rand.New(rand.NewSource(99)), mustParseCoins("100stake,2testtoken")}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got := simulation.RandSubsetCoins(tt.r, tt.coins) gotStringRep := got.String() @@ -46,8 +45,6 @@ func TestRandStringOfLength(t *testing.T) { {"1_000_000-size", 1_000_000, 1_000_000}, } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { got := simulation.RandStringOfLength(r, tt.n) require.Equal(t, tt.want, len(got)) diff --git a/types/tx/ext.go b/types/tx/ext.go index f0cd824d7e..fb2e1ed448 100644 --- a/types/tx/ext.go +++ b/types/tx/ext.go @@ -5,7 +5,7 @@ import ( ) // TxExtensionOptionI defines the interface for tx extension options -type TxExtensionOptionI interface{} //nolint:revive // to avoid breaking change +type TxExtensionOptionI interface{} // unpackTxExtensionOptionsI unpacks Any's to TxExtensionOptionI's. func unpackTxExtensionOptionsI(unpacker types.AnyUnpacker, anys []*types.Any) error { diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 7588db6343..0f3b89e600 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -1087,7 +1087,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) { privs, accNums, accSeqs := []cryptotypes.PrivKey{accs[1].priv}, []uint64{accs[1].acc.GetAccountNumber()}, []uint64{accs[1].acc.GetSequence()} msgs := []sdk.Msg{testdata.NewTestMsg(accs[1].acc.GetAddress())} - suite.txBuilder.SetMsgs(msgs...) + require.NoError(t, suite.txBuilder.SetMsgs(msgs...)) suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) @@ -1133,7 +1133,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) { privs, accNums, accSeqs := []cryptotypes.PrivKey{accs[1].priv}, []uint64{accs[1].acc.GetAccountNumber()}, []uint64{accs[1].acc.GetSequence()} msgs := []sdk.Msg{testdata.NewTestMsg(accs[1].acc.GetAddress())} - suite.txBuilder.SetMsgs(msgs...) + require.NoError(t, suite.txBuilder.SetMsgs(msgs...)) suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) diff --git a/x/auth/ante/basic_test.go b/x/auth/ante/basic_test.go index aacadbc4f3..defce32521 100644 --- a/x/auth/ante/basic_test.go +++ b/x/auth/ante/basic_test.go @@ -214,7 +214,6 @@ func TestTxHeightTimeoutDecorator(t *testing.T) { } for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() diff --git a/x/auth/ante/setup_test.go b/x/auth/ante/setup_test.go index e806a9b244..c9fa03b461 100644 --- a/x/auth/ante/setup_test.go +++ b/x/auth/ante/setup_test.go @@ -118,7 +118,7 @@ func TestRecoverPanic(t *testing.T) { require.Equal(t, gasLimit, newCtx.GasMeter().Limit()) antehandler = sdk.ChainAnteDecorators(sud, PanicDecorator{}) - require.Panics(t, func() { antehandler(suite.ctx, tx, false) }, "Recovered from non-Out-of-Gas panic") + require.Panics(t, func() { _, _ = antehandler(suite.ctx, tx, false) }, "Recovered from non-Out-of-Gas panic") } type OutOfGasDecorator struct{} diff --git a/x/auth/ante/sigverify_test.go b/x/auth/ante/sigverify_test.go index b50dafa80a..e729c5f69c 100644 --- a/x/auth/ante/sigverify_test.go +++ b/x/auth/ante/sigverify_test.go @@ -230,7 +230,7 @@ func TestSigVerification(t *testing.T) { }, Sequence: tc.accSeqs[0], } - suite.txBuilder.SetSignatures(txSigs...) + require.NoError(t, suite.txBuilder.SetSignatures(txSigs...)) tx = suite.txBuilder.GetTx() } @@ -269,6 +269,8 @@ func TestSigIntegration(t *testing.T) { } func runSigDecorators(t *testing.T, params types.Params, _ bool, privs ...cryptotypes.PrivKey) (storetypes.Gas, error) { + t.Helper() + suite := SetupTestSuite(t, true) suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go index f04321a6e2..58fca4832c 100644 --- a/x/auth/ante/testutil_test.go +++ b/x/auth/ante/testutil_test.go @@ -58,6 +58,8 @@ type AnteTestSuite struct { // SetupTest setups a new test, with new app, context, and anteHandler. func SetupTestSuite(t *testing.T, isCheckTx bool) *AnteTestSuite { + t.Helper() + suite := &AnteTestSuite{} ctrl := gomock.NewController(t) suite.bankKeeper = authtestutil.NewMockBankKeeper(ctrl) @@ -118,7 +120,10 @@ func (suite *AnteTestSuite) CreateTestAccounts(numAccs int) []TestAccount { for i := 0; i < numAccs; i++ { priv, _, addr := testdata.KeyTestPubAddr() acc := suite.accountKeeper.NewAccountWithAddress(suite.ctx, addr) - acc.SetAccountNumber(uint64(i + 1000)) + err := acc.SetAccountNumber(uint64(i + 1000)) + if err != nil { + panic(err) + } suite.accountKeeper.SetAccount(suite.ctx, acc) accounts = append(accounts, TestAccount{acc, priv}) } @@ -158,6 +163,8 @@ func (t TestCaseArgs) WithAccountsInfo(accs []TestAccount) TestCaseArgs { // DeliverMsgs constructs a tx and runs it through the ante handler. This is used to set the context for a test case, for // example to test for replay protection. func (suite *AnteTestSuite) DeliverMsgs(t *testing.T, privs []cryptotypes.PrivKey, msgs []sdk.Msg, feeAmount sdk.Coins, gasLimit uint64, accNums, accSeqs []uint64, chainID string, simulate bool) (sdk.Context, error) { + t.Helper() + require.NoError(t, suite.txBuilder.SetMsgs(msgs...)) suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) @@ -171,6 +178,8 @@ func (suite *AnteTestSuite) DeliverMsgs(t *testing.T, privs []cryptotypes.PrivKe } func (suite *AnteTestSuite) RunTestCase(t *testing.T, tc TestCase, args TestCaseArgs) { + t.Helper() + require.NoError(t, suite.txBuilder.SetMsgs(args.msgs...)) suite.txBuilder.SetFeeAmount(args.feeAmount) suite.txBuilder.SetGasLimit(args.gasLimit) diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index d4195585aa..2a65124a16 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -79,7 +79,7 @@ func makeMultiSignCmd() func(cmd *cobra.Command, args []string) (err error) { } parsedTx, err := authclient.ReadTxFromFile(clientCtx, args[0]) if err != nil { - return + return err } txFactory, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index a5dec4d00f..14b21d6bac 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -60,7 +60,7 @@ account key. It implies --signature-only. flags.AddTxFlagsToCmd(cmd) - cmd.MarkFlagRequired(flags.FlagFrom) + _ = cmd.MarkFlagRequired(flags.FlagFrom) return cmd } @@ -147,7 +147,10 @@ func makeSignBatchCmd() func(cmd *cobra.Command, args []string) error { msgs = append(msgs, unsignedStdTx.GetMsgs()...) } // set the new appened msgs into builder - txBuilder.SetMsgs(msgs...) + err := txBuilder.SetMsgs(msgs...) + if err != nil { + return err + } // set the memo,fees,feeGranter,feePayer from cmd flags txBuilder.SetMemo(txFactory.Memo()) @@ -319,7 +322,7 @@ func setOutputFile(cmd *cobra.Command) (func(), error) { cmd.SetOut(fp) - return func() { fp.Close() }, nil + return func() { _ = fp.Close() }, nil } // GetSignCommand returns the transaction sign command. @@ -352,7 +355,7 @@ be generated via the 'multisign' command. cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT") flags.AddTxFlagsToCmd(cmd) - cmd.MarkFlagRequired(flags.FlagFrom) + _ = cmd.MarkFlagRequired(flags.FlagFrom) return cmd } @@ -361,8 +364,8 @@ func preSignCmd(cmd *cobra.Command, _ []string) { // Conditionally mark the account and sequence numbers required as no RPC // query will be done. if offline, _ := cmd.Flags().GetBool(flags.FlagOffline); offline { - cmd.MarkFlagRequired(flags.FlagAccountNumber) - cmd.MarkFlagRequired(flags.FlagSequence) + _ = cmd.MarkFlagRequired(flags.FlagAccountNumber) + _ = cmd.MarkFlagRequired(flags.FlagSequence) } } diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 027e27d3b0..3f377f2828 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -53,7 +53,7 @@ func SignTx(txFactory tx.Factory, clientCtx client.Context, name string, txBuild return err } if !isTxSigner(addr, signers) { - return fmt.Errorf("%s: %s", errors.ErrorInvalidSigner, name) + return fmt.Errorf("%w: %s", errors.ErrorInvalidSigner, name) } if !offline { txFactory, err = populateAccountFromState(txFactory, clientCtx, addr) diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index ae88666db4..99d12d5ab8 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -107,7 +107,6 @@ func TestBatchScanner_Scan(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { scanner, i := authclient.NewBatchScanner(clientCtx.TxConfig, strings.NewReader(tt.batch)), 0 for scanner.Scan() { diff --git a/x/auth/migrations/v2/store_test.go b/x/auth/migrations/v2/store_test.go index 83989a1c17..78a5be9ed7 100644 --- a/x/auth/migrations/v2/store_test.go +++ b/x/auth/migrations/v2/store_test.go @@ -74,7 +74,7 @@ func TestMigrateVestingAccounts(t *testing.T) { require.NoError(t, v4.Migrate(ctx, storeService, legacySubspace, cdc)) ctx = app.BaseApp.NewContextLegacy(false, cmtproto.Header{Time: time.Now()}) - stakingKeeper.SetParams(ctx, stakingtypes.DefaultParams()) + require.NoError(t, stakingKeeper.SetParams(ctx, stakingtypes.DefaultParams())) lastAccNum := uint64(1000) createBaseAccount := func(addr sdk.AccAddress) *authtypes.BaseAccount { baseAccount := authtypes.NewBaseAccountWithAddress(addr) @@ -659,7 +659,6 @@ func TestMigrateVestingAccounts(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { err := accountKeeper.Params.Set(ctx, authtypes.DefaultParams()) require.NoError(t, err) @@ -701,8 +700,8 @@ func TestMigrateVestingAccounts(t *testing.T) { } trackingCorrected( - ctx, t, + ctx, accountKeeper, savedAccount.GetAddress(), expVested, @@ -712,7 +711,7 @@ func TestMigrateVestingAccounts(t *testing.T) { } } -func trackingCorrected(ctx sdk.Context, t *testing.T, ak keeper.AccountKeeper, addr sdk.AccAddress, expDelVesting, expDelFree sdk.Coins) { +func trackingCorrected(t *testing.T, ctx sdk.Context, ak keeper.AccountKeeper, addr sdk.AccAddress, expDelVesting, expDelFree sdk.Coins) { t.Helper() baseAccount := ak.GetAccount(ctx, addr) vDA, ok := baseAccount.(exported.VestingAccount) @@ -769,6 +768,8 @@ func dirtyTrackingFields(ctx sdk.Context, vesting exported.VestingAccount, accou } func createValidator(t *testing.T, ctx sdk.Context, bankKeeper bankkeeper.Keeper, stakingKeeper *stakingkeeper.Keeper, powers int64) (sdk.AccAddress, sdk.ValAddress) { + t.Helper() + valTokens := sdk.TokensFromConsensusPower(powers, sdk.DefaultPowerReduction) addrs := simtestutil.AddTestAddrsIncremental(bankKeeper, stakingKeeper, ctx, 1, valTokens) valAddrs := simtestutil.ConvertAddrsToValAddrs(addrs) @@ -777,14 +778,15 @@ func createValidator(t *testing.T, ctx sdk.Context, bankKeeper bankkeeper.Keeper val1, err := stakingtypes.NewValidator(valAddrs[0].String(), pks[0], stakingtypes.Description{}) require.NoError(t, err) - stakingKeeper.SetValidator(ctx, val1) + require.NoError(t, stakingKeeper.SetValidator(ctx, val1)) require.NoError(t, stakingKeeper.SetValidatorByConsAddr(ctx, val1)) - stakingKeeper.SetNewValidatorByPowerIndex(ctx, val1) + require.NoError(t, stakingKeeper.SetNewValidatorByPowerIndex(ctx, val1)) _, err = stakingKeeper.Delegate(ctx, addrs[0], valTokens, stakingtypes.Unbonded, val1, true) require.NoError(t, err) - stakingKeeper.EndBlocker(ctx) + _, err = stakingKeeper.EndBlocker(ctx) + require.NoError(t, err) return addrs[0], valAddrs[0] } diff --git a/x/auth/migrations/v3/store.go b/x/auth/migrations/v3/store.go index 62deba2e49..3714c72c23 100644 --- a/x/auth/migrations/v3/store.go +++ b/x/auth/migrations/v3/store.go @@ -22,7 +22,7 @@ func mapAccountAddressToAccountID(ctx sdk.Context, storeService corestore.KVStor if err := cdc.UnmarshalInterface(iterator.Value(), &acc); err != nil { return err } - store.Set(accountNumberStoreKey(acc.GetAccountNumber()), acc.GetAddress().Bytes()) + _ = store.Set(accountNumberStoreKey(acc.GetAccountNumber()), acc.GetAddress().Bytes()) } return nil diff --git a/x/auth/migrations/v4/migrate.go b/x/auth/migrations/v4/migrate.go index 3372b248c6..fdab856ee4 100644 --- a/x/auth/migrations/v4/migrate.go +++ b/x/auth/migrations/v4/migrate.go @@ -25,7 +25,6 @@ func Migrate(ctx sdk.Context, storeService storetypes.KVStoreService, legacySubs } bz := cdc.MustMarshal(&currParams) - store.Set(ParamsKey, bz) - return nil + return store.Set(ParamsKey, bz) } diff --git a/x/auth/testutil/util.go b/x/auth/testutil/util.go index b144a7f5d8..fd54673b6f 100644 --- a/x/auth/testutil/util.go +++ b/x/auth/testutil/util.go @@ -7,6 +7,8 @@ import ( ) func AssertError(t *testing.T, err, expectedErr error, expectedErrMsg string) { + t.Helper() + switch { case expectedErr != nil: require.ErrorIs(t, err, expectedErr) diff --git a/x/auth/tx/aux_test.go b/x/auth/tx/aux_test.go index 6ba205644d..123e58503b 100644 --- a/x/auth/tx/aux_test.go +++ b/x/auth/tx/aux_test.go @@ -125,10 +125,10 @@ func TestBuilderWithAux(t *testing.T) { txSigV2 := sigs[0] aux2SigV2 := sigs[1] // Set all signer infos. - w.SetSignatures(txSigV2, aux2SigV2, signing.SignatureV2{ + require.NoError(t, w.SetSignatures(txSigV2, aux2SigV2, signing.SignatureV2{ PubKey: feepayerPk, Sequence: 15, - }) + })) signerData := authsigning.SignerData{ Address: feepayerAddr.String(), ChainID: chainID, @@ -145,14 +145,14 @@ func TestBuilderWithAux(t *testing.T) { feepayerSig, err := feepayerPriv.Sign(signBz) require.NoError(t, err) // Set all signatures. - w.SetSignatures(txSigV2, aux2SigV2, signing.SignatureV2{ + require.NoError(t, w.SetSignatures(txSigV2, aux2SigV2, signing.SignatureV2{ PubKey: feepayerPk, Data: &signing.SingleSignatureData{ SignMode: signing.SignMode_SIGN_MODE_DIRECT, Signature: feepayerSig, }, Sequence: 22, - }) + })) // Make sure tx is correct. txBz, err := txConfig.TxEncoder()(w.GetTx()) diff --git a/x/auth/tx/encode_decode_test.go b/x/auth/tx/encode_decode_test.go index 5329b3eadb..820d513646 100644 --- a/x/auth/tx/encode_decode_test.go +++ b/x/auth/tx/encode_decode_test.go @@ -103,7 +103,6 @@ func TestUnknownFields(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { bodyBz, err := tt.body.Marshal() require.NoError(t, err) @@ -246,7 +245,6 @@ func TestRejectNonADR027(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { _, err = decoder(tt.txBz) if tt.shouldErr { @@ -284,7 +282,6 @@ func TestVarintMinLength(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(fmt.Sprintf("test %d", tt.n), func(t *testing.T) { l1 := varintMinLength(tt.n) buf := make([]byte, binary.MaxVarintLen64) diff --git a/x/auth/tx/legacy_amino_json_test.go b/x/auth/tx/legacy_amino_json_test.go index dcfbe31906..9fe79c2326 100644 --- a/x/auth/tx/legacy_amino_json_test.go +++ b/x/auth/tx/legacy_amino_json_test.go @@ -32,6 +32,8 @@ var ( ) func buildTx(t *testing.T, bldr *wrapper) { + t.Helper() + bldr.SetFeeAmount(coins) bldr.SetGasLimit(gas) bldr.SetMemo(memo) @@ -81,7 +83,6 @@ func TestLegacyAminoJSONHandler_GetSignBytes(t *testing.T) { handler := signModeLegacyAminoJSONHandler{} for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { bldr := newBuilder(nil) buildTx(t, bldr) @@ -182,7 +183,6 @@ func TestLegacyAminoJSONHandler_AllGetSignBytesComparison(t *testing.T) { handler := signModeLegacyAminoJSONHandler{} for _, tc := range testcases { - tc := tc t.Run(tc.name, func(t *testing.T) { bldr := newBuilder(nil) buildTx(t, bldr) diff --git a/x/auth/tx/service.go b/x/auth/tx/service.go index a96ac8cae0..7a275a47d6 100644 --- a/x/auth/tx/service.go +++ b/x/auth/tx/service.go @@ -320,7 +320,7 @@ func RegisterTxService( // RegisterGRPCGatewayRoutes mounts the tx service's GRPC-gateway routes on the // given Mux. func RegisterGRPCGatewayRoutes(clientConn gogogrpc.ClientConn, mux *runtime.ServeMux) { - txtypes.RegisterServiceHandlerClient(context.Background(), mux, txtypes.NewServiceClient(clientConn)) + _ = txtypes.RegisterServiceHandlerClient(context.Background(), mux, txtypes.NewServiceClient(clientConn)) } func parseOrderBy(orderBy txtypes.OrderBy) string { diff --git a/x/auth/types/account_test.go b/x/auth/types/account_test.go index d29372dcd0..10e3c06e96 100644 --- a/x/auth/types/account_test.go +++ b/x/auth/types/account_test.go @@ -84,8 +84,6 @@ func TestGenesisAccountValidate(t *testing.T) { } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { require.Equal(t, tt.expErr, tt.acc.Validate() != nil) }) @@ -97,7 +95,7 @@ func TestModuleAccountString(t *testing.T) { moduleAcc := types.NewEmptyModuleAccount(name, types.Minter, types.Burner, types.Staking) want := `base_account: name:"test" permissions:"minter" permissions:"burner" permissions:"staking" ` require.Equal(t, want, moduleAcc.String()) - moduleAcc.SetSequence(10) + require.NoError(t, moduleAcc.SetSequence(10)) want = `base_account: name:"test" permissions:"minter" permissions:"burner" permissions:"staking" ` require.Equal(t, want, moduleAcc.String()) } @@ -150,7 +148,6 @@ func TestValidate(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { err := tt.acc.Validate() require.Equal(t, tt.expErr, err) diff --git a/x/auth/types/params_test.go b/x/auth/types/params_test.go index bffeb16017..ccb0dc8e34 100644 --- a/x/auth/types/params_test.go +++ b/x/auth/types/params_test.go @@ -37,7 +37,6 @@ func TestParams_Validate(t *testing.T) { types.DefaultSigVerifyCostED25519, types.DefaultSigVerifyCostSecp256k1), fmt.Errorf("invalid tx size cost per byte: 0")}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got := tt.params.Validate() if tt.wantErr == nil { diff --git a/x/auth/types/permissions_test.go b/x/auth/types/permissions_test.go index de5c256457..78133007da 100644 --- a/x/auth/types/permissions_test.go +++ b/x/auth/types/permissions_test.go @@ -41,7 +41,6 @@ func TestValidatePermissions(t *testing.T) { } for i, tc := range cases { - i, tc := i, tc t.Run(tc.name, func(t *testing.T) { err := validatePermissions(tc.permissions...) if tc.expectPass { diff --git a/x/auth/vesting/client/cli/tx_test.go b/x/auth/vesting/client/cli/tx_test.go index 4df054f0e2..00119f5d7f 100644 --- a/x/auth/vesting/client/cli/tx_test.go +++ b/x/auth/vesting/client/cli/tx_test.go @@ -52,7 +52,7 @@ func (s *CLITestSuite) SetupSuite() { func (s *CLITestSuite) TestNewMsgCreateVestingAccountCmd() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) cmd := cli.NewMsgCreateVestingAccountCmd(address.NewBech32Codec("cosmos")) - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) extraArgs := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), @@ -118,7 +118,6 @@ func (s *CLITestSuite) TestNewMsgCreateVestingAccountCmd() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -141,7 +140,7 @@ func (s *CLITestSuite) TestNewMsgCreateVestingAccountCmd() { func (s *CLITestSuite) TestNewMsgCreatePermanentLockedAccountCmd() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) cmd := cli.NewMsgCreatePermanentLockedAccountCmd(address.NewBech32Codec("cosmos")) - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) extraArgs := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), @@ -198,7 +197,6 @@ func (s *CLITestSuite) TestNewMsgCreatePermanentLockedAccountCmd() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -220,7 +218,7 @@ func (s *CLITestSuite) TestNewMsgCreatePermanentLockedAccountCmd() { func (s *CLITestSuite) TestNewMsgCreatePeriodicVestingAccountCmd() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) cmd := cli.NewMsgCreatePeriodicVestingAccountCmd(address.NewBech32Codec("cosmos")) - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) extraArgs := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), @@ -258,7 +256,6 @@ func (s *CLITestSuite) TestNewMsgCreatePeriodicVestingAccountCmd() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index 74cdfe59c5..82ee27e4f2 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -877,8 +877,6 @@ func TestGenesisAccountValidate(t *testing.T) { } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { require.Equal(t, tt.expErr, tt.acc.Validate() != nil) }) diff --git a/x/authz/client/cli/tx_test.go b/x/authz/client/cli/tx_test.go index 41de235c40..d538783663 100644 --- a/x/authz/client/cli/tx_test.go +++ b/x/authz/client/cli/tx_test.go @@ -174,7 +174,6 @@ func (s *CLITestSuite) createAccount(uid string) sdk.AccAddress { func (s *CLITestSuite) msgSendExec(grantee sdk.AccAddress) { val := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) // Send some funds to the new account. - s.ac.StringToBytes("cosmos16zex22087zs656t0vedytv5wqhm6axxd5679ry") out, err := clitestutil.MsgSendExec( s.clientCtx, val[0].Address, diff --git a/x/authz/keeper/genesis_test.go b/x/authz/keeper/genesis_test.go index fe0adcd22c..e5488efb8d 100644 --- a/x/authz/keeper/genesis_test.go +++ b/x/authz/keeper/genesis_test.go @@ -82,7 +82,7 @@ func (suite *GenesisTestSuite) TestImportExportGenesis() { // TODO, recheck! // Clear keeper - suite.keeper.DeleteGrant(suite.ctx, granteeAddr, granterAddr, grant.MsgTypeURL()) + suite.Require().NoError(suite.keeper.DeleteGrant(suite.ctx, granteeAddr, granterAddr, grant.MsgTypeURL())) newGenesis := suite.keeper.ExportGenesis(suite.ctx) suite.Require().NotEqual(genesis, newGenesis) suite.Require().Empty(newGenesis) diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index 974c18000e..12334ef2aa 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -88,16 +88,15 @@ func (k Keeper) update(ctx context.Context, grantee, granter sdk.AccAddress, upd return sdkerrors.ErrPackAny.Wrapf("cannot proto marshal %T", updated) } - any, err := codectypes.NewAnyWithValue(msg) + cdcAny, err := codectypes.NewAnyWithValue(msg) if err != nil { return err } - grant.Authorization = any + grant.Authorization = cdcAny store := k.storeService.OpenKVStore(ctx) - store.Set(skey, k.cdc.MustMarshal(&grant)) - return nil + return store.Set(skey, k.cdc.MustMarshal(&grant)) } // DispatchActions attempts to execute the provided messages via authorization diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index b760a85bdf..d4c8a0b8a3 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -148,8 +148,8 @@ func (s *TestSuite) TestKeeperIter() { e := ctx.BlockTime().AddDate(1, 0, 0) sendAuthz := banktypes.NewSendAuthorization(coins100, nil) - s.authzKeeper.SaveGrant(ctx, granteeAddr, granterAddr, sendAuthz, &e) - s.authzKeeper.SaveGrant(ctx, granteeAddr, granter2Addr, sendAuthz, &e) + s.Require().NoError(s.authzKeeper.SaveGrant(ctx, granteeAddr, granterAddr, sendAuthz, &e)) + s.Require().NoError(s.authzKeeper.SaveGrant(ctx, granteeAddr, granter2Addr, sendAuthz, &e)) s.authzKeeper.IterateGrants(ctx, func(granter, grantee sdk.AccAddress, grant authz.Grant) bool { s.Require().Equal(granteeAddr, grantee) @@ -189,7 +189,7 @@ func (s *TestSuite) TestDispatchAction() { "authorization not found", func() sdk.Context { // remove any existing authorizations - s.authzKeeper.DeleteGrant(s.ctx, granteeAddr, granterAddr, bankSendAuthMsgType) + _ = s.authzKeeper.DeleteGrant(s.ctx, granteeAddr, granterAddr, bankSendAuthMsgType) return s.ctx }, func() {}, diff --git a/x/authz/migrations/v2/store_test.go b/x/authz/migrations/v2/store_test.go index cf71c4519e..5dd2ad9a94 100644 --- a/x/authz/migrations/v2/store_test.go +++ b/x/authz/migrations/v2/store_test.go @@ -52,10 +52,10 @@ func TestMigration(t *testing.T) { grantee1, sendMsgType, func() authz.Grant { - any, err := codectypes.NewAnyWithValue(sendAuthz) + cdcAny, err := codectypes.NewAnyWithValue(sendAuthz) require.NoError(t, err) return authz.Grant{ - Authorization: any, + Authorization: cdcAny, Expiration: &oneDay, } }, @@ -65,10 +65,10 @@ func TestMigration(t *testing.T) { grantee2, sendMsgType, func() authz.Grant { - any, err := codectypes.NewAnyWithValue(sendAuthz) + cdcAny, err := codectypes.NewAnyWithValue(sendAuthz) require.NoError(t, err) return authz.Grant{ - Authorization: any, + Authorization: cdcAny, Expiration: &oneDay, } }, @@ -78,10 +78,10 @@ func TestMigration(t *testing.T) { grantee1, genericMsgType, func() authz.Grant { - any, err := codectypes.NewAnyWithValue(authz.NewGenericAuthorization(genericMsgType)) + cdcAny, err := codectypes.NewAnyWithValue(authz.NewGenericAuthorization(genericMsgType)) require.NoError(t, err) return authz.Grant{ - Authorization: any, + Authorization: cdcAny, Expiration: &oneYear, } }, @@ -91,10 +91,10 @@ func TestMigration(t *testing.T) { grantee2, genericMsgType, func() authz.Grant { - any, err := codectypes.NewAnyWithValue(authz.NewGenericAuthorization(genericMsgType)) + cdcAny, err := codectypes.NewAnyWithValue(authz.NewGenericAuthorization(genericMsgType)) require.NoError(t, err) return authz.Grant{ - Authorization: any, + Authorization: cdcAny, Expiration: &blockTime, } }, @@ -106,7 +106,7 @@ func TestMigration(t *testing.T) { for _, g := range grants { grant := g.authorization() - store.Set(v2.GrantStoreKey(g.grantee, g.granter, g.msgType), cdc.MustMarshal(&grant)) + require.NoError(t, store.Set(v2.GrantStoreKey(g.grantee, g.granter, g.msgType), cdc.MustMarshal(&grant))) } ctx = ctx.WithBlockTime(ctx.BlockTime().Add(1 * time.Hour)) diff --git a/x/authz/module/abci_test.go b/x/authz/module/abci_test.go index 0e8857377f..95b24b92ff 100644 --- a/x/authz/module/abci_test.go +++ b/x/authz/module/abci_test.go @@ -81,7 +81,7 @@ func TestExpiredGrantsQueue(t *testing.T) { queryClient := authz.NewQueryClient(queryHelper) checkGrants := func(ctx sdk.Context, expectedNum int) { - authzmodule.BeginBlocker(ctx, authzKeeper) + require.NoError(t, authzmodule.BeginBlocker(ctx, authzKeeper)) res, err := queryClient.GranterGrants(ctx.Context(), &authz.QueryGranterGrantsRequest{ Granter: granter.String(), diff --git a/x/authz/msgs_test.go b/x/authz/msgs_test.go index ea634fd395..c243376e5e 100644 --- a/x/authz/msgs_test.go +++ b/x/authz/msgs_test.go @@ -40,7 +40,7 @@ func TestMsgGrantGetAuthorization(t *testing.T) { require.Equal(a, &g) g = authz.GenericAuthorization{Msg: "some_type2"} - m.SetAuthorization(&g) + require.NoError(m.SetAuthorization(&g)) a, err = m.GetAuthorization() require.NoError(err) require.Equal(a, &g) diff --git a/x/authz/simulation/decoder_test.go b/x/authz/simulation/decoder_test.go index ffaf441195..4fa8242efa 100644 --- a/x/authz/simulation/decoder_test.go +++ b/x/authz/simulation/decoder_test.go @@ -46,7 +46,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { if tt.expectErr { require.Panics(t, func() { dec(kvPairs.Pairs[i], kvPairs.Pairs[i]) }, tt.name) diff --git a/x/authz/simulation/operations_test.go b/x/authz/simulation/operations_test.go index 8a6894dc2b..68f9fbec26 100644 --- a/x/authz/simulation/operations_test.go +++ b/x/authz/simulation/operations_test.go @@ -7,6 +7,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" "github.com/cosmos/gogoproto/proto" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "cosmossdk.io/depinject" @@ -122,10 +123,11 @@ func (suite *SimTestSuite) TestSimulateGrant() { blockTime := time.Now().UTC() ctx := suite.ctx.WithBlockTime(blockTime) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) granter := accounts[0] grantee := accounts[1] @@ -150,10 +152,11 @@ func (suite *SimTestSuite) TestSimulateRevoke() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 3) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + require.NoError(suite.T(), err) initAmt := sdk.TokensFromConsensusPower(200000, sdk.DefaultPowerReduction) initCoins := sdk.NewCoins(sdk.NewCoin("stake", initAmt)) @@ -163,7 +166,7 @@ func (suite *SimTestSuite) TestSimulateRevoke() { a := banktypes.NewSendAuthorization(initCoins, nil) expire := time.Now().Add(30 * time.Hour) - err := suite.authzKeeper.SaveGrant(suite.ctx, grantee.Address, granter.Address, a, &expire) + err = suite.authzKeeper.SaveGrant(suite.ctx, grantee.Address, granter.Address, a, &expire) suite.Require().NoError(err) // execute operation @@ -187,7 +190,8 @@ func (suite *SimTestSuite) TestSimulateExec() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 3) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash}) + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash}) + suite.Require().NoError(err) initAmt := sdk.TokensFromConsensusPower(200000, sdk.DefaultPowerReduction) initCoins := sdk.NewCoins(sdk.NewCoin("stake", initAmt)) @@ -197,7 +201,7 @@ func (suite *SimTestSuite) TestSimulateExec() { a := banktypes.NewSendAuthorization(initCoins, nil) expire := suite.ctx.BlockTime().Add(1 * time.Hour) - err := suite.authzKeeper.SaveGrant(suite.ctx, grantee.Address, granter.Address, a, &expire) + err = suite.authzKeeper.SaveGrant(suite.ctx, grantee.Address, granter.Address, a, &expire) suite.Require().NoError(err) // execute operation diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 2099b5981f..1d7e64373c 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -103,6 +103,8 @@ type suite struct { } func createTestSuite(t *testing.T, genesisAccounts []authtypes.GenesisAccount) suite { + t.Helper() + res := suite{} var genAccounts []simtestutil.GenesisAccount @@ -137,6 +139,8 @@ func createTestSuite(t *testing.T, genesisAccounts []authtypes.GenesisAccount) s // CheckBalance checks the balance of an account. func checkBalance(t *testing.T, baseApp *baseapp.BaseApp, addr sdk.AccAddress, balances sdk.Coins, keeper bankkeeper.Keeper) { + t.Helper() + ctxCheck := baseApp.NewContext(true) keeperBalances := keeper.GetAllBalances(ctxCheck, addr) require.True(t, balances.Equal(keeperBalances)) diff --git a/x/bank/client/cli/tx.go b/x/bank/client/cli/tx.go index 6b7e40554a..1edc19883d 100644 --- a/x/bank/client/cli/tx.go +++ b/x/bank/client/cli/tx.go @@ -47,7 +47,10 @@ When using '--dry-run' a key name cannot be used, only a bech32 address. `, Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - cmd.Flags().Set(flags.FlagFrom, args[0]) + err := cmd.Flags().Set(flags.FlagFrom, args[0]) + if err != nil { + return err + } clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err @@ -92,7 +95,11 @@ When using '--dry-run' a key name cannot be used, only a bech32 address.`, Example: fmt.Sprintf("%s tx bank multi-send cosmos1... cosmos1... cosmos1... cosmos1... 10stake", version.AppName), Args: cobra.MinimumNArgs(4), RunE: func(cmd *cobra.Command, args []string) error { - cmd.Flags().Set(flags.FlagFrom, args[0]) + err := cmd.Flags().Set(flags.FlagFrom, args[0]) + if err != nil { + return err + } + clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err diff --git a/x/bank/client/cli/tx_test.go b/x/bank/client/cli/tx_test.go index 4fcbbf3f80..450b82ffb8 100644 --- a/x/bank/client/cli/tx_test.go +++ b/x/bank/client/cli/tx_test.go @@ -51,7 +51,7 @@ func (s *CLITestSuite) SetupSuite() { func (s *CLITestSuite) TestSendTxCmd() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) cmd := cli.NewSendTxCmd(address.NewBech32Codec("cosmos")) - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) extraArgs := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), @@ -136,7 +136,7 @@ func (s *CLITestSuite) TestMultiSendTxCmd() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 3) cmd := cli.NewMultiSendTxCmd(address.NewBech32Codec("cosmos")) - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) extraArgs := []string{ fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), diff --git a/x/bank/keeper/genesis.go b/x/bank/keeper/genesis.go index cb208b22d3..22162af3d8 100644 --- a/x/bank/keeper/genesis.go +++ b/x/bank/keeper/genesis.go @@ -59,7 +59,7 @@ func (k BaseKeeper) InitGenesis(ctx context.Context, genState *types.GenesisStat func (k BaseKeeper) ExportGenesis(ctx context.Context) *types.GenesisState { totalSupply, _, err := k.GetPaginatedTotalSupply(ctx, &query.PageRequest{Limit: query.PaginationMaxLimit}) if err != nil { - panic(fmt.Errorf("unable to fetch total supply %v", err)) + panic(fmt.Errorf("unable to fetch total supply %w", err)) } rv := types.NewGenesisState( diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index cdf4f5c7f7..10a1c67e84 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -78,7 +78,6 @@ func (suite *KeeperTestSuite) TestQueryBalance() { } for _, tc := range testCases { - suite.Run(tc.name, func() { res, err := queryClient.Balance(gocontext.Background(), tc.req) if tc.expectErrMsg == "" { diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 38ab8aa357..53131b00d1 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -401,18 +401,18 @@ func (suite *KeeperTestSuite) TestSupply_DelegateUndelegateCoins() { authKeeper.EXPECT().GetModuleAddress("").Return(nil) require.Panics(func() { - _ = keeper.SendCoinsFromModuleToAccount(ctx, "", holderAcc.GetAddress(), initCoins) //nolint:errcheck // we're testing for a panic, not an error + _ = keeper.SendCoinsFromModuleToAccount(ctx, "", holderAcc.GetAddress(), initCoins) }) authKeeper.EXPECT().GetModuleAddress(burnerAcc.Name).Return(burnerAcc.GetAddress()) authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) require.Panics(func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) //nolint:errcheck // we're testing for a panic, not an error + _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) }) authKeeper.EXPECT().GetModuleAddress("").Return(nil) require.Panics(func() { - _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) //nolint:errcheck // we're testing for a panic, not an error + _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) }) authKeeper.EXPECT().GetModuleAddress(holderAcc.Name).Return(holderAcc.GetAddress()) @@ -462,18 +462,18 @@ func (suite *KeeperTestSuite) TestSupply_SendCoins() { authKeeper.EXPECT().GetModuleAddress("").Return(nil) require.Panics(func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, "", holderAcc.GetName(), initCoins) //nolint:errcheck // we're testing for a panic, not an error + _ = keeper.SendCoinsFromModuleToModule(ctx, "", holderAcc.GetName(), initCoins) }) authKeeper.EXPECT().GetModuleAddress(burnerAcc.Name).Return(burnerAcc.GetAddress()) authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) require.Panics(func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) //nolint:errcheck // we're testing for a panic, not an error + _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) }) authKeeper.EXPECT().GetModuleAddress("").Return(nil) require.Panics(func() { - _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) //nolint:errcheck // we're testing for a panic, not an error + _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) }) authKeeper.EXPECT().GetModuleAddress(holderAcc.Name).Return(holderAcc.GetAddress()) @@ -514,16 +514,16 @@ func (suite *KeeperTestSuite) TestSupply_MintCoins() { require.NoError(err) authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) - require.Panics(func() { _ = keeper.MintCoins(ctx, "", initCoins) }, "no module account") //nolint:errcheck // we're testing for a panic, not an error + require.Panics(func() { _ = keeper.MintCoins(ctx, "", initCoins) }, "no module account") suite.mockMintCoins(burnerAcc) - require.Panics(func() { _ = keeper.MintCoins(ctx, authtypes.Burner, initCoins) }, "invalid permission") //nolint:errcheck // we're testing for a panic, not an error + require.Panics(func() { _ = keeper.MintCoins(ctx, authtypes.Burner, initCoins) }, "invalid permission") suite.mockMintCoins(minterAcc) require.Error(keeper.MintCoins(ctx, authtypes.Minter, sdk.Coins{sdk.Coin{Denom: "denom", Amount: math.NewInt(-10)}}), "insufficient coins") authKeeper.EXPECT().GetModuleAccount(ctx, randomPerm).Return(nil) - require.Panics(func() { _ = keeper.MintCoins(ctx, randomPerm, initCoins) }) //nolint:errcheck // we're testing for a panic, not an error + require.Panics(func() { _ = keeper.MintCoins(ctx, randomPerm, initCoins) }) suite.mockMintCoins(minterAcc) require.NoError(keeper.MintCoins(ctx, authtypes.Minter, initCoins)) @@ -567,13 +567,13 @@ func (suite *KeeperTestSuite) TestSupply_BurnCoins() { require.NoError(err) authKeeper.EXPECT().GetModuleAccount(ctx, "").Return(nil) - require.Panics(func() { _ = keeper.BurnCoins(ctx, "", initCoins) }, "no module account") //nolint:errcheck // we're testing for a panic, not an error + require.Panics(func() { _ = keeper.BurnCoins(ctx, "", initCoins) }, "no module account") authKeeper.EXPECT().GetModuleAccount(ctx, minterAcc.Name).Return(nil) - require.Panics(func() { _ = keeper.BurnCoins(ctx, authtypes.Minter, initCoins) }, "invalid permission") //nolint:errcheck // we're testing for a panic, not an error + require.Panics(func() { _ = keeper.BurnCoins(ctx, authtypes.Minter, initCoins) }, "invalid permission") authKeeper.EXPECT().GetModuleAccount(ctx, randomPerm).Return(nil) - require.Panics(func() { _ = keeper.BurnCoins(ctx, randomPerm, supplyAfterInflation) }, "random permission") //nolint:errcheck // we're testing for a panic, not an error + require.Panics(func() { _ = keeper.BurnCoins(ctx, randomPerm, supplyAfterInflation) }, "random permission") suite.mockBurnCoins(burnerAcc) require.Error(keeper.BurnCoins(ctx, authtypes.Burner, supplyAfterInflation), "insufficient coins") @@ -2416,10 +2416,10 @@ func (suite *KeeperTestSuite) TestMigrator_Migrate3to4() { require.NoError(migrator.Migrate3to4(ctx)) newParams := bankKeeper.GetParams(ctx) - require.Len(newParams.SendEnabled, 0) //nolint:staticcheck // SA1019: banktypes.Params.SendEnabled is deprecated: Use bankkeeper.IsSendEnabledDenom instead. + require.Len(newParams.SendEnabled, 0) //nolint // just using this for testing when migrating legacy require.Equal(def, newParams.DefaultSendEnabled) - for _, se := range params.SendEnabled { //nolint:staticcheck // SA1019: banktypes.Params.SendEnabled is deprecated: Use bankkeeper.IsSendEnabledDenom instead. + for _, se := range params.SendEnabled { actual := bankKeeper.IsSendEnabledDenom(ctx, se.Denom) require.Equal(se.Enabled, actual, se.Denom) } @@ -2432,7 +2432,7 @@ func (suite *KeeperTestSuite) TestSetParams() { require := suite.Require() params := banktypes.NewParams(true) - params.SendEnabled = []*banktypes.SendEnabled{ //nolint:staticcheck // SA1019: banktypes.Params.SendEnabled is deprecated: Use bankkeeper.IsSendEnabledDenom instead. + params.SendEnabled = []*banktypes.SendEnabled{ {Denom: "paramscointrue", Enabled: true}, {Denom: "paramscoinfalse", Enabled: false}, } @@ -2441,7 +2441,7 @@ func (suite *KeeperTestSuite) TestSetParams() { suite.Run("stored params are as expected", func() { actual := bankKeeper.GetParams(ctx) require.True(actual.DefaultSendEnabled, "DefaultSendEnabled") - require.Len(actual.SendEnabled, 0, "SendEnabled") //nolint:staticcheck // SA1019: banktypes.Params.SendEnabled is deprecated: Use bankkeeper.IsSendEnabledDenom instead. + require.Len(actual.SendEnabled, 0, "SendEnabled") //nolint:staticcheck // test legacy deprecated param }) suite.Run("send enabled params converted to store", func() { diff --git a/x/bank/keeper/msg_server_test.go b/x/bank/keeper/msg_server_test.go index 0a4902688a..e3eae263e6 100644 --- a/x/bank/keeper/msg_server_test.go +++ b/x/bank/keeper/msg_server_test.go @@ -52,7 +52,6 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { } for _, tc := range testCases { - tc := tc suite.Run(tc.name, func() { _, err := suite.msgServer.UpdateParams(suite.ctx, tc.input) @@ -140,10 +139,9 @@ func (suite *KeeperTestSuite) TestMsgSend() { } for _, tc := range testCases { - tc := tc suite.Run(tc.name, func() { suite.mockMintCoins(minterAcc) - suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) + _ = suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) if !tc.expErr { suite.mockSendCoins(suite.ctx, minterAcc, baseAcc.GetAddress()) } @@ -237,10 +235,9 @@ func (suite *KeeperTestSuite) TestMsgMultiSend() { } for _, tc := range testCases { - tc := tc suite.Run(tc.name, func() { suite.mockMintCoins(minterAcc) - suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) + _ = suite.bankKeeper.MintCoins(suite.ctx, minterAcc.Name, origCoins) if !tc.expErr { suite.mockInputOutputCoins([]sdk.AccountI{minterAcc}, accAddrs[:2]) } diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index 7deedf473e..7628821272 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -125,11 +125,11 @@ func (k BaseSendKeeper) GetParams(ctx context.Context) (params types.Params) { // // Note: params.SendEnabled is deprecated but it should be here regardless. func (k BaseSendKeeper) SetParams(ctx context.Context, params types.Params) error { - // Normally SendEnabled is deprecated but we still support it for backwards + // Normally SendEnabled is deprecated, but we still support it for backwards // compatibility. Using params.Validate() would fail due to the SendEnabled // deprecation. - if len(params.SendEnabled) > 0 { //nolint:staticcheck // SA1019: params.SendEnabled is deprecated - k.SetAllSendEnabled(ctx, params.SendEnabled) //nolint:staticcheck // SA1019: params.SendEnabled is deprecated + if len(params.SendEnabled) > 0 { + k.SetAllSendEnabled(ctx, params.SendEnabled) // override params without SendEnabled params = types.NewParams(params.DefaultSendEnabled) diff --git a/x/bank/migrations/v3/store_test.go b/x/bank/migrations/v3/store_test.go index a8184f75b4..ae6c54c56c 100644 --- a/x/bank/migrations/v3/store_test.go +++ b/x/bank/migrations/v3/store_test.go @@ -35,7 +35,7 @@ func TestMigrateStore(t *testing.T) { ) for _, b := range balances { - bz, err := encCfg.Codec.Marshal(&b) //nolint:gosec // G601: Implicit memory aliasing in for loop. + bz, err := encCfg.Codec.Marshal(&b) require.NoError(t, err) prefixAccStore.Set([]byte(b.Denom), bz) @@ -126,6 +126,8 @@ func TestMigrateDenomMetaData(t *testing.T) { } func assertMetaDataEqual(t *testing.T, expected, actual types.Metadata) { + t.Helper() + require.Equal(t, expected.GetBase(), actual.GetBase()) require.Equal(t, expected.GetDisplay(), actual.GetDisplay()) require.Equal(t, expected.GetDescription(), actual.GetDescription()) diff --git a/x/bank/migrations/v4/gen_state_test.go b/x/bank/migrations/v4/gen_state_test.go index 1283e65b78..52511eb70b 100644 --- a/x/bank/migrations/v4/gen_state_test.go +++ b/x/bank/migrations/v4/gen_state_test.go @@ -156,6 +156,6 @@ func TestMigrateGenState(t *testing.T) { }, } _ = v4.MigrateGenState(&origState) - assert.Len(t, origState.Params.SendEnabled, 2) //nolint:staticcheck // keep for test (linter sometimes fails) + assert.Len(t, origState.Params.SendEnabled, 2) }) } diff --git a/x/bank/module.go b/x/bank/module.go index 8f9e88b059..06ef33aa7a 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -42,7 +42,6 @@ var ( _ module.AppModuleSimulation = AppModule{} _ module.HasGenesis = AppModule{} _ module.HasServices = AppModule{} - _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} ) @@ -143,9 +142,6 @@ func NewAppModule(cdc codec.Codec, keeper keeper.Keeper, accountKeeper types.Acc } } -// RegisterInvariants is deprecated and will be removed in the next Cosmos SDK release. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - // QuerierRoute returns the bank module's querier route name. func (AppModule) QuerierRoute() string { return types.RouterKey } diff --git a/x/bank/simulation/operations_test.go b/x/bank/simulation/operations_test.go index e4f5e03a8a..3a27f32dae 100644 --- a/x/bank/simulation/operations_test.go +++ b/x/bank/simulation/operations_test.go @@ -106,10 +106,11 @@ func (suite *SimTestSuite) TestSimulateMsgSend() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 3) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgSend(suite.txConfig, suite.accountKeeper, suite.bankKeeper) @@ -135,10 +136,11 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSend() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 3) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgMultiSend(suite.txConfig, suite.accountKeeper, suite.bankKeeper) @@ -170,11 +172,11 @@ func (suite *SimTestSuite) TestSimulateModuleAccountMsgSend() { r := rand.New(s) accounts := suite.getTestingAccounts(r, accCount) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, - }, - ) + }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgSendToModuleAccount(suite.txConfig, suite.accountKeeper, suite.bankKeeper, moduleAccCount) @@ -204,10 +206,11 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSendToModuleAccount() { r := rand.New(s) accounts := suite.getTestingAccounts(r, accCount) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgMultiSendToModuleAccount(suite.txConfig, suite.accountKeeper, suite.bankKeeper, mAccCount) diff --git a/x/bank/types/balance_test.go b/x/bank/types/balance_test.go index 2374d9a2f8..c48fb01f42 100644 --- a/x/bank/types/balance_test.go +++ b/x/bank/types/balance_test.go @@ -126,7 +126,6 @@ func TestBalance_GetAddress(t *testing.T) { {"valid address", "cosmos1vy0ga0klndqy92ceqehfkvgmn4t94eteq4hmqv", false}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { b := bank.Balance{Address: tt.Address} if !tt.err { @@ -190,6 +189,7 @@ func BenchmarkSanitizeBalances1000(b *testing.B) { } func benchmarkSanitizeBalances(b *testing.B, nAddresses int) { + b.Helper() b.ReportAllocs() tokens := sdk.TokensFromConsensusPower(81, sdk.DefaultPowerReduction) coin := sdk.NewCoin("benchcoin", tokens) diff --git a/x/circuit/ante/circuit_test.go b/x/circuit/ante/circuit_test.go index 54fbbebeb4..8f1d89ff36 100644 --- a/x/circuit/ante/circuit_test.go +++ b/x/circuit/ante/circuit_test.go @@ -39,6 +39,8 @@ func (m MockCircuitBreaker) IsAllowed(ctx context.Context, typeURL string) (bool } func initFixture(t *testing.T) *fixture { + t.Helper() + mockStoreKey := storetypes.NewKVStoreKey("test") encCfg := moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}, bank.AppModuleBasic{}) mockclientCtx := client.Context{}. @@ -77,7 +79,7 @@ func TestCircuitBreakerDecorator(t *testing.T) { // CircuitBreakerDecorator AnteHandler should always return success decorator := ante.NewCircuitBreakerDecorator(circuitBreaker) - f.txBuilder.SetMsgs(tc.msg) + require.NoError(t, f.txBuilder.SetMsgs(tc.msg)) tx := f.txBuilder.GetTx() sdkCtx := sdk.UnwrapSDKContext(f.ctx) @@ -88,6 +90,7 @@ func TestCircuitBreakerDecorator(t *testing.T) { if tc.allowed { require.NoError(t, err) } else { + require.Error(t, err) require.Equal(t, "tx type not allowed", err.Error()) } } diff --git a/x/circuit/keeper/keeper_test.go b/x/circuit/keeper/keeper_test.go index f9f42b9b35..5182030189 100644 --- a/x/circuit/keeper/keeper_test.go +++ b/x/circuit/keeper/keeper_test.go @@ -39,6 +39,8 @@ type fixture struct { } func initFixture(t *testing.T) *fixture { + t.Helper() + encCfg := moduletestutil.MakeTestEncodingConfig(circuit.AppModuleBasic{}) ac := addresscodec.NewBech32Codec("cosmos") mockStoreKey := storetypes.NewKVStoreKey("test") @@ -101,7 +103,7 @@ func TestIteratePermissions(t *testing.T) { []byte("mock_address_3"), } for i, addr := range mockAddrs { - f.keeper.Permissions.Set(f.ctx, addr, mockPerms[i]) + require.NoError(t, f.keeper.Permissions.Set(f.ctx, addr, mockPerms[i])) } // Define a variable to store the returned permissions diff --git a/x/crisis/abci.go b/x/crisis/abci.go index 2eacc641c4..7cd6fae958 100644 --- a/x/crisis/abci.go +++ b/x/crisis/abci.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/crisis/types" ) -// check all registered invariants +// EndBlocker checks all registered invariants func EndBlocker(ctx context.Context, k keeper.Keeper) { defer telemetry.ModuleMeasureSince(types.ModuleName, telemetry.Now(), telemetry.MetricKeyEndBlocker) diff --git a/x/crisis/keeper/msg_server_test.go b/x/crisis/keeper/msg_server_test.go index c3bc9ab40d..62871f1f90 100644 --- a/x/crisis/keeper/msg_server_test.go +++ b/x/crisis/keeper/msg_server_test.go @@ -108,7 +108,6 @@ func (s *KeeperTestSuite) TestMsgVerifyInvariant() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { _, err = s.keeper.VerifyInvariant(s.ctx, tc.input) if tc.expErr { @@ -167,7 +166,6 @@ func (s *KeeperTestSuite) TestMsgUpdateParams() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { _, err := s.keeper.UpdateParams(s.ctx, tc.input) diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index 94e9d8af6d..a50f45c246 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -128,8 +128,6 @@ func (s *CLITestSuite) TestTxWithdrawRewardsCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { args := append([]string{tc.valAddr.String()}, tc.args...) @@ -183,8 +181,6 @@ func (s *CLITestSuite) TestTxWithdrawAllRewardsCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewWithdrawAllRewardsCmd(address.NewBech32Codec("cosmosvaloper"), address.NewBech32Codec("cosmos")) @@ -235,8 +231,6 @@ func (s *CLITestSuite) TestTxSetWithdrawAddrCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewSetWithdrawAddrCmd(address.NewBech32Codec("cosmos")) @@ -285,8 +279,6 @@ func (s *CLITestSuite) TestTxFundCommunityPoolCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewFundCommunityPoolCmd(address.NewBech32Codec("cosmos")) diff --git a/x/distribution/client/common/common_test.go b/x/distribution/client/common/common_test.go index 05fa593079..c8a7477ad6 100644 --- a/x/distribution/client/common/common_test.go +++ b/x/distribution/client/common/common_test.go @@ -30,7 +30,6 @@ func TestQueryDelegationRewardsAddrValidation(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { _, _, err := QueryDelegationRewards(clientCtx, tt.args.delAddr, tt.args.valAddr) require.True(t, err != nil, tt.wantErr) diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index 2b0e99d390..b98943bbcc 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -99,13 +99,13 @@ func (k Keeper) CalculateDelegationRewards(ctx context.Context, val stakingtypes // fetch starting info for delegation startingInfo, err := k.GetDelegatorStartingInfo(ctx, sdk.ValAddress(valAddr), sdk.AccAddress(delAddr)) if err != nil { - return + return sdk.DecCoins{}, err } sdkCtx := sdk.UnwrapSDKContext(ctx) if startingInfo.Height == uint64(sdkCtx.BlockHeight()) { // started this height, no rewards yet - return + return sdk.DecCoins{}, err } startingPeriod := startingInfo.PreviousPeriod diff --git a/x/distribution/keeper/grpc_query.go b/x/distribution/keeper/grpc_query.go index b80ca323f8..beb53e5892 100644 --- a/x/distribution/keeper/grpc_query.go +++ b/x/distribution/keeper/grpc_query.go @@ -331,7 +331,6 @@ func (k Querier) DelegatorValidators(ctx context.Context, req *types.QueryDelega return false }, ) - if err != nil { return nil, err } diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index 7bea2017a1..7e277f12d9 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -99,11 +99,10 @@ func (k Keeper) SetWithdrawAddr(ctx context.Context, delegatorAddr, withdrawAddr ), ) - k.SetDelegatorWithdrawAddr(ctx, delegatorAddr, withdrawAddr) - return nil + return k.SetDelegatorWithdrawAddr(ctx, delegatorAddr, withdrawAddr) } -// withdraw rewards from a delegation +// WithdrawDelegationRewards withdraws rewards from a delegation func (k Keeper) WithdrawDelegationRewards(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (sdk.Coins, error) { val, err := k.stakingKeeper.Validator(ctx, valAddr) if err != nil { @@ -137,7 +136,7 @@ func (k Keeper) WithdrawDelegationRewards(ctx context.Context, delAddr sdk.AccAd return rewards, nil } -// withdraw validator commission +// WithdrawValidatorCommission withdraws validator commission. func (k Keeper) WithdrawValidatorCommission(ctx context.Context, valAddr sdk.ValAddress) (sdk.Coins, error) { // fetch validator accumulated commission accumCommission, err := k.GetValidatorAccumulatedCommission(ctx, valAddr) @@ -150,7 +149,10 @@ func (k Keeper) WithdrawValidatorCommission(ctx context.Context, valAddr sdk.Val } commission, remainder := accumCommission.Commission.TruncateDecimal() - k.SetValidatorAccumulatedCommission(ctx, valAddr, types.ValidatorAccumulatedCommission{Commission: remainder}) // leave remainder to withdraw later + err = k.SetValidatorAccumulatedCommission(ctx, valAddr, types.ValidatorAccumulatedCommission{Commission: remainder}) // leave remainder to withdraw later + if err != nil { + return nil, err + } // update outstanding outstanding, err := k.GetValidatorOutstandingRewards(ctx, valAddr) diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index 5ef0395a2e..d599737f48 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -167,7 +167,10 @@ func (k Keeper) updateValidatorSlashFraction(ctx context.Context, valAddr sdk.Va } // increment reference count on period we need to track - k.incrementReferenceCount(ctx, valAddr, newPeriod) + err = k.incrementReferenceCount(ctx, valAddr, newPeriod) + if err != nil { + return err + } slashEvent := types.NewValidatorSlashEvent(newPeriod, fraction) height := uint64(sdkCtx.BlockHeight()) diff --git a/x/distribution/migrations/v2/store_test.go b/x/distribution/migrations/v2/store_test.go index ed496123eb..a9bc679f98 100644 --- a/x/distribution/migrations/v2/store_test.go +++ b/x/distribution/migrations/v2/store_test.go @@ -92,7 +92,6 @@ func TestStoreMigration(t *testing.T) { // Make sure the new keys are set and old keys are deleted. for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { if !bytes.Equal(tc.oldKey, tc.newKey) { require.Nil(t, store.Get(tc.oldKey)) diff --git a/x/distribution/module.go b/x/distribution/module.go index ed0461ef69..b80d5ce537 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -38,7 +38,6 @@ var ( _ module.AppModuleSimulation = AppModule{} _ module.HasGenesis = AppModule{} _ module.HasServices = AppModule{} - _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasBeginBlocker = AppModule{} @@ -127,9 +126,6 @@ func (am AppModule) IsOnePerModuleType() {} // IsAppModule implements the appmodule.AppModule interface. func (am AppModule) IsAppModule() {} -// RegisterInvariants is deprecated and will be removed in the next Cosmos SDK release. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) diff --git a/x/distribution/simulation/decoder_test.go b/x/distribution/simulation/decoder_test.go index 773208143f..936742bfe2 100644 --- a/x/distribution/simulation/decoder_test.go +++ b/x/distribution/simulation/decoder_test.go @@ -71,7 +71,6 @@ func TestDecodeDistributionStore(t *testing.T) { {"other", ""}, } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/distribution/simulation/operations_test.go b/x/distribution/simulation/operations_test.go index 69c5726a06..ca74f5eb73 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -74,10 +74,11 @@ func (suite *SimTestSuite) TestSimulateMsgSetWithdrawAddress() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 3) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgSetWithdrawAddress(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper) @@ -115,7 +116,7 @@ func (suite *SimTestSuite) TestSimulateMsgWithdrawDelegatorReward() { suite.Require().NoError(suite.stakingKeeper.SetDelegation(suite.ctx, delegation)) valBz, err := address.NewBech32Codec("cosmosvaloper").StringToBytes(validator0.GetOperator()) suite.Require().NoError(err) - suite.distrKeeper.SetDelegatorStartingInfo(suite.ctx, valBz, delegator.Address, types.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200)) + suite.Require().NoError(suite.distrKeeper.SetDelegatorStartingInfo(suite.ctx, valBz, delegator.Address, types.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) suite.setupValidatorRewards(valBz) @@ -179,12 +180,12 @@ func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName genVal0, err := valCodec.StringToBytes(suite.genesisVals[0].GetOperator()) suite.Require().NoError(err) - suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, val0, types.ValidatorOutstandingRewards{Rewards: valCommission}) - suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, genVal0, types.ValidatorOutstandingRewards{Rewards: valCommission}) + suite.Require().NoError(suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, val0, types.ValidatorOutstandingRewards{Rewards: valCommission})) + suite.Require().NoError(suite.distrKeeper.SetValidatorOutstandingRewards(suite.ctx, genVal0, types.ValidatorOutstandingRewards{Rewards: valCommission})) // setup validator accumulated commission - suite.distrKeeper.SetValidatorAccumulatedCommission(suite.ctx, val0, types.ValidatorAccumulatedCommission{Commission: valCommission}) - suite.distrKeeper.SetValidatorAccumulatedCommission(suite.ctx, genVal0, types.ValidatorAccumulatedCommission{Commission: valCommission}) + suite.Require().NoError(suite.distrKeeper.SetValidatorAccumulatedCommission(suite.ctx, val0, types.ValidatorAccumulatedCommission{Commission: valCommission})) + suite.Require().NoError(suite.distrKeeper.SetValidatorAccumulatedCommission(suite.ctx, genVal0, types.ValidatorAccumulatedCommission{Commission: valCommission})) _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, @@ -218,10 +219,11 @@ func (suite *SimTestSuite) TestSimulateMsgFundCommunityPool() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 3) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgFundCommunityPool(suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.distrKeeper, suite.stakingKeeper) @@ -316,7 +318,7 @@ func (suite *SimTestSuite) getTestingValidator(accounts []simtypes.Account, comm validator.DelegatorShares = math.LegacyNewDec(100) validator.Tokens = math.NewInt(1000000) - suite.stakingKeeper.SetValidator(suite.ctx, validator) + require.NoError(suite.stakingKeeper.SetValidator(suite.ctx, validator)) return validator } @@ -324,10 +326,10 @@ func (suite *SimTestSuite) getTestingValidator(accounts []simtypes.Account, comm func (suite *SimTestSuite) setupValidatorRewards(valAddress sdk.ValAddress) { decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} historicalRewards := types.NewValidatorHistoricalRewards(decCoins, 2) - suite.distrKeeper.SetValidatorHistoricalRewards(suite.ctx, valAddress, 2, historicalRewards) + suite.Require().NoError(suite.distrKeeper.SetValidatorHistoricalRewards(suite.ctx, valAddress, 2, historicalRewards)) // setup current revards currentRewards := types.NewValidatorCurrentRewards(decCoins, 3) - suite.distrKeeper.SetValidatorCurrentRewards(suite.ctx, valAddress, currentRewards) + suite.Require().NoError(suite.distrKeeper.SetValidatorCurrentRewards(suite.ctx, valAddress, currentRewards)) } func TestSimTestSuite(t *testing.T) { diff --git a/x/distribution/types/params_internal_test.go b/x/distribution/types/params_internal_test.go index 92cffd7846..21bfd0f1bf 100644 --- a/x/distribution/types/params_internal_test.go +++ b/x/distribution/types/params_internal_test.go @@ -24,7 +24,6 @@ func Test_validateAuxFuncs(t *testing.T) { {"two dec", args{math.LegacyNewDec(2)}, true}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { require.Equal(t, tt.wantErr, validateCommunityTax(tt.args.i) != nil) }) diff --git a/x/feegrant/client/cli/tx_test.go b/x/feegrant/client/cli/tx_test.go index 5ecc467901..5f86a02e3f 100644 --- a/x/feegrant/client/cli/tx_test.go +++ b/x/feegrant/client/cli/tx_test.go @@ -412,7 +412,6 @@ func (s *CLITestSuite) TestNewCmdFeeGrant() { } for _, tc := range testCases { - s.Run(tc.name, func() { cmd := cli.NewCmdFeeGrant(codecaddress.NewBech32Codec("cosmos")) out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -607,8 +606,6 @@ func (s *CLITestSuite) TestFilteredFeeAllowance() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewCmdFeeGrant(codecaddress.NewBech32Codec("cosmos")) out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -670,8 +667,6 @@ func (s *CLITestSuite) TestFilteredFeeAllowance() { } for _, tc := range cases { - tc := tc - s.Run(tc.name, func() { err := tc.malleate() s.Require().NoError(err) diff --git a/x/feegrant/keeper/genesis_test.go b/x/feegrant/keeper/genesis_test.go index f9a5e2f4d8..e83458b2e4 100644 --- a/x/feegrant/keeper/genesis_test.go +++ b/x/feegrant/keeper/genesis_test.go @@ -39,6 +39,8 @@ type genesisFixture struct { } func initFixture(t *testing.T) *genesisFixture { + t.Helper() + key := storetypes.NewKVStoreKey(feegrant.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(module.AppModuleBasic{}) diff --git a/x/feegrant/keeper/keeper.go b/x/feegrant/keeper/keeper.go index 02ec88b697..0368d598ed 100644 --- a/x/feegrant/keeper/keeper.go +++ b/x/feegrant/keeper/keeper.go @@ -254,7 +254,7 @@ func (k Keeper) UseGrantedFees(ctx context.Context, granter, grantee sdk.AccAddr if remove { // Ignoring the `revokeFeeAllowance` error, because the user has enough grants to perform this transaction. - k.revokeAllowance(ctx, granter, grantee) + _ = k.revokeAllowance(ctx, granter, grantee) if err != nil { return err } diff --git a/x/feegrant/keeper/keeper_test.go b/x/feegrant/keeper/keeper_test.go index 8ca87dcb44..ad515e63a0 100644 --- a/x/feegrant/keeper/keeper_test.go +++ b/x/feegrant/keeper/keeper_test.go @@ -307,14 +307,14 @@ func (suite *KeeperTestSuite) TestIterateGrants() { Expiration: &exp, } - suite.feegrantKeeper.GrantAllowance(suite.ctx, suite.addrs[0], suite.addrs[1], allowance) - suite.feegrantKeeper.GrantAllowance(suite.ctx, suite.addrs[2], suite.addrs[1], allowance1) + suite.Require().NoError(suite.feegrantKeeper.GrantAllowance(suite.ctx, suite.addrs[0], suite.addrs[1], allowance)) + suite.Require().NoError(suite.feegrantKeeper.GrantAllowance(suite.ctx, suite.addrs[2], suite.addrs[1], allowance1)) - suite.feegrantKeeper.IterateAllFeeAllowances(suite.ctx, func(grant feegrant.Grant) bool { + suite.Require().NoError(suite.feegrantKeeper.IterateAllFeeAllowances(suite.ctx, func(grant feegrant.Grant) bool { suite.Require().Equal(suite.addrs[1].String(), grant.Grantee) suite.Require().Contains([]string{suite.addrs[0].String(), suite.addrs[2].String()}, grant.Granter) return true - }) + })) } func (suite *KeeperTestSuite) TestPruneGrants() { diff --git a/x/feegrant/keeper/msg_server_test.go b/x/feegrant/keeper/msg_server_test.go index cf3e15c39a..54550d37c5 100644 --- a/x/feegrant/keeper/msg_server_test.go +++ b/x/feegrant/keeper/msg_server_test.go @@ -28,13 +28,13 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { { "invalid granter address", func() *feegrant.MsgGrantAllowance { - any, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{}) + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{}) suite.Require().NoError(err) invalid := "invalid-granter" return &feegrant.MsgGrantAllowance{ Granter: invalid, Grantee: suite.addrs[1].String(), - Allowance: any, + Allowance: cdcAny, } }, true, @@ -43,13 +43,13 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { { "invalid grantee address", func() *feegrant.MsgGrantAllowance { - any, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{}) + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{}) suite.Require().NoError(err) invalid := "invalid-grantee" return &feegrant.MsgGrantAllowance{ Granter: suite.addrs[0].String(), Grantee: invalid, - Allowance: any, + Allowance: cdcAny, } }, true, @@ -61,7 +61,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { grantee := "cosmos139f7kncmglres2nf3h4hc4tade85ekfr8sulz5" granteeAccAddr, err := addressCodec.StringToBytes(grantee) suite.Require().NoError(err) - any, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ SpendLimit: suite.atom, Expiration: &oneYear, }) @@ -80,7 +80,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { return &feegrant.MsgGrantAllowance{ Granter: suite.addrs[0].String(), Grantee: grantee, - Allowance: any, + Allowance: cdcAny, } }, false, @@ -89,7 +89,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { { "invalid: past expiry", func() *feegrant.MsgGrantAllowance { - any, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ SpendLimit: suite.atom, Expiration: &yesterday, }) @@ -97,7 +97,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { return &feegrant.MsgGrantAllowance{ Granter: suite.addrs[0].String(), Grantee: suite.addrs[1].String(), - Allowance: any, + Allowance: cdcAny, } }, true, @@ -106,7 +106,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { { "valid: basic fee allowance", func() *feegrant.MsgGrantAllowance { - any, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ SpendLimit: suite.atom, Expiration: &oneYear, }) @@ -114,7 +114,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { return &feegrant.MsgGrantAllowance{ Granter: suite.addrs[0].String(), Grantee: suite.addrs[1].String(), - Allowance: any, + Allowance: cdcAny, } }, false, @@ -123,7 +123,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { { "fail: fee allowance exists", func() *feegrant.MsgGrantAllowance { - any, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ SpendLimit: suite.atom, Expiration: &oneYear, }) @@ -131,7 +131,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { return &feegrant.MsgGrantAllowance{ Granter: suite.addrs[0].String(), Grantee: suite.addrs[1].String(), - Allowance: any, + Allowance: cdcAny, } }, true, @@ -140,7 +140,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { { "valid: periodic fee allowance", func() *feegrant.MsgGrantAllowance { - any, err := codectypes.NewAnyWithValue(&feegrant.PeriodicAllowance{ + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.PeriodicAllowance{ Basic: feegrant.BasicAllowance{ SpendLimit: suite.atom, Expiration: &oneYear, @@ -151,7 +151,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { return &feegrant.MsgGrantAllowance{ Granter: suite.addrs[1].String(), Grantee: suite.addrs[2].String(), - Allowance: any, + Allowance: cdcAny, } }, false, @@ -160,7 +160,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { { "error: fee allowance exists", func() *feegrant.MsgGrantAllowance { - any, err := codectypes.NewAnyWithValue(&feegrant.PeriodicAllowance{ + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.PeriodicAllowance{ Basic: feegrant.BasicAllowance{ SpendLimit: suite.atom, Expiration: &oneYear, @@ -171,7 +171,7 @@ func (suite *KeeperTestSuite) TestGrantAllowance() { return &feegrant.MsgGrantAllowance{ Granter: suite.addrs[1].String(), Grantee: suite.addrs[2].String(), - Allowance: any, + Allowance: cdcAny, } }, true, @@ -237,12 +237,12 @@ func (suite *KeeperTestSuite) TestRevokeAllowance() { }, func() { // removing fee allowance from previous tests if exists - suite.msgSrvr.RevokeAllowance(suite.ctx, &feegrant.MsgRevokeAllowance{ + _, _ = suite.msgSrvr.RevokeAllowance(suite.ctx, &feegrant.MsgRevokeAllowance{ Granter: suite.addrs[0].String(), Grantee: suite.addrs[1].String(), }) - any, err := codectypes.NewAnyWithValue(&feegrant.PeriodicAllowance{ + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.PeriodicAllowance{ Basic: feegrant.BasicAllowance{ SpendLimit: suite.atom, Expiration: &oneYear, @@ -253,7 +253,7 @@ func (suite *KeeperTestSuite) TestRevokeAllowance() { req := &feegrant.MsgGrantAllowance{ Granter: suite.addrs[0].String(), Grantee: suite.addrs[1].String(), - Allowance: any, + Allowance: cdcAny, } _, err = suite.msgSrvr.GrantAllowance(suite.ctx, req) suite.Require().NoError(err) @@ -300,7 +300,7 @@ func (suite *KeeperTestSuite) TestPruneAllowances() { continue } - any, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ + cdcAny, err := codectypes.NewAnyWithValue(&feegrant.BasicAllowance{ SpendLimit: suite.atom, Expiration: &oneYear, }) @@ -308,7 +308,7 @@ func (suite *KeeperTestSuite) TestPruneAllowances() { req := &feegrant.MsgGrantAllowance{ Granter: suite.addrs[i].String(), Grantee: suite.addrs[j].String(), - Allowance: any, + Allowance: cdcAny, } _, err = suite.msgSrvr.GrantAllowance(ctx, req) diff --git a/x/feegrant/migrations/v2/store.go b/x/feegrant/migrations/v2/store.go index 48a8d3e339..b8d0fadbaf 100644 --- a/x/feegrant/migrations/v2/store.go +++ b/x/feegrant/migrations/v2/store.go @@ -41,7 +41,10 @@ func addAllowancesByExpTimeQueue(ctx context.Context, store store.KVStore, cdc c prefixStore.Delete(key) } else { grantByExpTimeQueueKey := FeeAllowancePrefixQueue(exp, key) - store.Set(grantByExpTimeQueueKey, []byte{}) + err = store.Set(grantByExpTimeQueueKey, []byte{}) + if err != nil { + return err + } } } } @@ -50,6 +53,6 @@ func addAllowancesByExpTimeQueue(ctx context.Context, store store.KVStore, cdc c } func MigrateStore(ctx context.Context, storeService store.KVStoreService, cdc codec.BinaryCodec) error { - store := storeService.OpenKVStore(ctx) - return addAllowancesByExpTimeQueue(ctx, store, cdc) + kvStore := storeService.OpenKVStore(ctx) + return addAllowancesByExpTimeQueue(ctx, kvStore, cdc) } diff --git a/x/feegrant/module/abci_test.go b/x/feegrant/module/abci_test.go index e731fcc7a4..40f1936ce6 100644 --- a/x/feegrant/module/abci_test.go +++ b/x/feegrant/module/abci_test.go @@ -46,38 +46,38 @@ func TestFeegrantPruning(t *testing.T) { accountKeeper.EXPECT().AddressCodec().Return(address.NewBech32Codec("cosmos")).AnyTimes() - feegrantKeeper := keeper.NewKeeper(encCfg.Codec, runtime.NewKVStoreService(key), accountKeeper) + feeGrantKeeper := keeper.NewKeeper(encCfg.Codec, runtime.NewKVStoreService(key), accountKeeper) - feegrantKeeper.GrantAllowance( + require.NoError(t, feeGrantKeeper.GrantAllowance( testCtx.Ctx, granter1, grantee, &feegrant.BasicAllowance{ Expiration: &now, }, - ) - feegrantKeeper.GrantAllowance( + )) + require.NoError(t, feeGrantKeeper.GrantAllowance( testCtx.Ctx, granter2, grantee, &feegrant.BasicAllowance{ SpendLimit: spendLimit, }, - ) - feegrantKeeper.GrantAllowance( + )) + require.NoError(t, feeGrantKeeper.GrantAllowance( testCtx.Ctx, granter3, grantee, &feegrant.BasicAllowance{ Expiration: &oneDay, }, - ) + )) queryHelper := baseapp.NewQueryServerTestHelper(testCtx.Ctx, encCfg.InterfaceRegistry) - feegrant.RegisterQueryServer(queryHelper, feegrantKeeper) + feegrant.RegisterQueryServer(queryHelper, feeGrantKeeper) queryClient := feegrant.NewQueryClient(queryHelper) - require.NoError(t, module.EndBlocker(testCtx.Ctx, feegrantKeeper)) + require.NoError(t, module.EndBlocker(testCtx.Ctx, feeGrantKeeper)) res, err := queryClient.Allowances(testCtx.Ctx.Context(), &feegrant.QueryAllowancesRequest{ Grantee: grantee.String(), @@ -87,7 +87,7 @@ func TestFeegrantPruning(t *testing.T) { require.Len(t, res.Allowances, 3) testCtx.Ctx = testCtx.Ctx.WithBlockTime(now.AddDate(0, 0, 2)) - module.EndBlocker(testCtx.Ctx, feegrantKeeper) + require.NoError(t, module.EndBlocker(testCtx.Ctx, feeGrantKeeper)) res, err = queryClient.Allowances(testCtx.Ctx.Context(), &feegrant.QueryAllowancesRequest{ Grantee: grantee.String(), diff --git a/x/feegrant/simulation/decoder_test.go b/x/feegrant/simulation/decoder_test.go index e1f1bfddb4..c693fe863e 100644 --- a/x/feegrant/simulation/decoder_test.go +++ b/x/feegrant/simulation/decoder_test.go @@ -53,7 +53,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/feegrant/simulation/operations.go b/x/feegrant/simulation/operations.go index 488ab82e8c..16d0e7b804 100644 --- a/x/feegrant/simulation/operations.go +++ b/x/feegrant/simulation/operations.go @@ -140,7 +140,7 @@ func SimulateMsgRevokeAllowance( hasGrant := false var granterAddr sdk.AccAddress var granteeAddr sdk.AccAddress - k.IterateAllFeeAllowances(ctx, func(grant feegrant.Grant) bool { + if err := k.IterateAllFeeAllowances(ctx, func(grant feegrant.Grant) bool { granter, err := ac.StringToBytes(grant.Granter) if err != nil { panic(err) @@ -153,7 +153,9 @@ func SimulateMsgRevokeAllowance( granteeAddr = grantee hasGrant = true return true - }) + }); err != nil { + return simtypes.NoOpMsg(feegrant.ModuleName, TypeMsgRevokeAllowance, "no grants"), nil, err + } if !hasGrant { return simtypes.NoOpMsg(feegrant.ModuleName, TypeMsgRevokeAllowance, "no grants"), nil, nil diff --git a/x/feegrant/simulation/operations_test.go b/x/feegrant/simulation/operations_test.go index 4198d39d55..38316a6d29 100644 --- a/x/feegrant/simulation/operations_test.go +++ b/x/feegrant/simulation/operations_test.go @@ -178,7 +178,8 @@ func (suite *SimTestSuite) TestSimulateMsgRevokeAllowance() { accounts := suite.getTestingAccounts(r, 3) // begin a new block - app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash}) + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash}) + suite.Require().NoError(err) feeAmt := sdk.TokensFromConsensusPower(200000, sdk.DefaultPowerReduction) feeCoins := sdk.NewCoins(sdk.NewCoin("foo", feeAmt)) @@ -186,7 +187,7 @@ func (suite *SimTestSuite) TestSimulateMsgRevokeAllowance() { granter, grantee := accounts[0], accounts[1] oneYear := ctx.BlockTime().AddDate(1, 0, 0) - err := suite.feegrantKeeper.GrantAllowance( + err = suite.feegrantKeeper.GrantAllowance( ctx, granter.Address, grantee.Address, diff --git a/x/genutil/client/cli/genaccount_test.go b/x/genutil/client/cli/genaccount_test.go index c3a99bd973..28040a35a5 100644 --- a/x/genutil/client/cli/genaccount_test.go +++ b/x/genutil/client/cli/genaccount_test.go @@ -70,7 +70,6 @@ func TestAddGenesisAccountCmd(t *testing.T) { } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() @@ -199,7 +198,6 @@ func TestBulkAddGenesisAccountCmd(t *testing.T) { } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 7ce1d29a43..77b220cfa4 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -59,7 +59,6 @@ func TestInitCmd(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() @@ -186,11 +185,12 @@ func TestEmptyState(t *testing.T) { outC := make(chan string) go func() { var buf bytes.Buffer - io.Copy(&buf, r) + _, err := io.Copy(&buf, r) + require.NoError(t, err) outC <- buf.String() }() - w.Close() + require.NoError(t, w.Close()) os.Stdout = old out := <-outC @@ -278,11 +278,12 @@ func TestInitConfig(t *testing.T) { outC := make(chan string) go func() { var buf bytes.Buffer - io.Copy(&buf, r) + _, err := io.Copy(&buf, r) + require.NoError(t, err) outC <- buf.String() }() - w.Close() + require.NoError(t, w.Close()) os.Stdout = old out := <-outC diff --git a/x/genutil/client/cli/validate_genesis_test.go b/x/genutil/client/cli/validate_genesis_test.go index 8b518ec090..187e8493ea 100644 --- a/x/genutil/client/cli/validate_genesis_test.go +++ b/x/genutil/client/cli/validate_genesis_test.go @@ -80,7 +80,6 @@ func TestValidateGenesis(t *testing.T) { } for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { genesisFile := testutil.WriteToNewTempFile(t, tc.genesis) _, err := clitestutil.ExecTestCLICmd(client.Context{}, cli.ValidateGenesisCmd(tc.basicManager), []string{genesisFile.Name()}) diff --git a/x/genutil/client/testutil/helpers.go b/x/genutil/client/testutil/helpers.go index 7060f6ab24..7a3fdc424c 100644 --- a/x/genutil/client/testutil/helpers.go +++ b/x/genutil/client/testutil/helpers.go @@ -47,7 +47,7 @@ func CreateDefaultCometConfig(rootDir string) (*cmtcfg.Config, error) { cmtcfg.EnsureRoot(rootDir) if err := conf.ValidateBasic(); err != nil { - return nil, fmt.Errorf("error in config file: %v", err) + return nil, fmt.Errorf("error in config file: %w", err) } return conf, nil diff --git a/x/genutil/gentx.go b/x/genutil/gentx.go index e861ecac35..6b969145fb 100644 --- a/x/genutil/gentx.go +++ b/x/genutil/gentx.go @@ -97,17 +97,17 @@ func DeliverGenTxs( for _, genTx := range genTxs { tx, err := txEncodingConfig.TxJSONDecoder()(genTx) if err != nil { - return nil, fmt.Errorf("failed to decode GenTx '%s': %s", genTx, err) + return nil, fmt.Errorf("failed to decode GenTx '%s': %w", genTx, err) } bz, err := txEncodingConfig.TxEncoder()(tx) if err != nil { - return nil, fmt.Errorf("failed to encode GenTx '%s': %s", genTx, err) + return nil, fmt.Errorf("failed to encode GenTx '%s': %w", genTx, err) } err = deliverTx.ExecuteGenesisTx(bz) if err != nil { - return nil, fmt.Errorf("failed to execute DeliverTx for '%s': %s", genTx, err) + return nil, fmt.Errorf("failed to execute DeliverTx for '%s': %w", genTx, err) } } diff --git a/x/genutil/gentx_test.go b/x/genutil/gentx_test.go index 6f1e6a952f..4c87d96967 100644 --- a/x/genutil/gentx_test.go +++ b/x/genutil/gentx_test.go @@ -296,7 +296,7 @@ func (suite *GenTxTestSuite) TestDeliverGenTxs() { if tc.expPass { suite.stakingKeeper.EXPECT().ApplyAndReturnValidatorSetUpdates(gomock.Any()).Return(nil, nil).AnyTimes() suite.Require().NotPanics(func() { - genutil.DeliverGenTxs( + _, _ = genutil.DeliverGenTxs( suite.ctx, genTxs, suite.stakingKeeper, tc.deliverTxFn, suite.encodingConfig.TxConfig, ) diff --git a/x/genutil/types/genesis_state.go b/x/genutil/types/genesis_state.go index e9a6e6424d..6c30594f71 100644 --- a/x/genutil/types/genesis_state.go +++ b/x/genutil/types/genesis_state.go @@ -124,7 +124,7 @@ func DefaultMessageValidator(msgs []sdk.Msg) error { func ValidateAndGetGenTx(genTx json.RawMessage, txJSONDecoder sdk.TxDecoder, validator MessageValidator) (sdk.Tx, error) { tx, err := txJSONDecoder(genTx) if err != nil { - return tx, fmt.Errorf("failed to decode gentx: %s, error: %s", genTx, err) + return tx, fmt.Errorf("failed to decode gentx: %s, error: %w", genTx, err) } return tx, validator(tx.GetMsgs()) diff --git a/x/genutil/utils_test.go b/x/genutil/utils_test.go index 7e0dd4b17d..da960dcd90 100644 --- a/x/genutil/utils_test.go +++ b/x/genutil/utils_test.go @@ -51,7 +51,6 @@ func TestInitializeNodeValidatorFilesFromMnemonic(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { _, _, err := InitializeNodeValidatorFilesFromMnemonic(cfg, tt.mnemonic) diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 6c8a009fa2..b174c189d8 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -87,10 +87,11 @@ func TestTickExpiredDepositPeriod(t *testing.T) { ctx := app.BaseApp.NewContext(false) addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) @@ -138,10 +139,11 @@ func TestTickMultipleExpiredDepositPeriod(t *testing.T) { ctx := app.BaseApp.NewContext(false) addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) @@ -209,10 +211,11 @@ func TestTickPassedDepositPeriod(t *testing.T) { ctx := app.BaseApp.NewContext(false) addrs := simtestutil.AddTestAddrs(suite.BankKeeper, suite.StakingKeeper, ctx, 10, valTokens) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) @@ -274,10 +277,11 @@ func TestTickPassedVotingPeriod(t *testing.T) { SortAddresses(addrs) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) @@ -368,16 +372,18 @@ func TestProposalPassedEndblocker(t *testing.T) { govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) stakingMsgSvr := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) valAddr := sdk.ValAddress(addrs[0]) proposer := addrs[0] createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) - suite.StakingKeeper.EndBlocker(ctx) + _, err = suite.StakingKeeper.EndBlocker(ctx) + require.NoError(t, err) macc := suite.GovKeeper.GetGovernanceAccount(ctx) require.NotNil(t, macc) @@ -408,7 +414,7 @@ func TestProposalPassedEndblocker(t *testing.T) { newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(*params.VotingPeriod) ctx = ctx.WithBlockHeader(newHeader) - gov.EndBlocker(ctx, suite.GovKeeper) + require.NoError(t, gov.EndBlocker(ctx, suite.GovKeeper)) macc = suite.GovKeeper.GetGovernanceAccount(ctx) require.NotNil(t, macc) @@ -427,16 +433,18 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { stakingMsgSvr := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) valAddr := sdk.ValAddress(addrs[0]) proposer := addrs[0] createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) - suite.StakingKeeper.EndBlocker(ctx) + _, err = suite.StakingKeeper.EndBlocker(ctx) + require.NoError(t, err) msg := banktypes.NewMsgSend(authtypes.NewModuleAddress(types.ModuleName), addrs[0], sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(100000)))) proposal, err := suite.GovKeeper.SubmitProposal(ctx, []sdk.Msg{msg}, "", "title", "summary", proposer, false) @@ -459,7 +467,7 @@ func TestEndBlockerProposalHandlerFailed(t *testing.T) { ctx = ctx.WithBlockHeader(newHeader) // validate that the proposal fails/has been rejected - gov.EndBlocker(ctx, suite.GovKeeper) + require.NoError(t, gov.EndBlocker(ctx, suite.GovKeeper)) // check proposal events events := ctx.EventManager().Events() @@ -511,17 +519,19 @@ func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { govMsgSvr := keeper.NewMsgServerImpl(suite.GovKeeper) stakingMsgSvr := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) valAddr := sdk.ValAddress(addrs[0]) proposer := addrs[0] // Create a validator so that able to vote on proposal. createValidators(t, stakingMsgSvr, ctx, []sdk.ValAddress{valAddr}, []int64{10}) - suite.StakingKeeper.EndBlocker(ctx) + _, err = suite.StakingKeeper.EndBlocker(ctx) + require.NoError(t, err) checkInactiveProposalsQueue(t, ctx, suite.GovKeeper) checkActiveProposalsQueue(t, ctx, suite.GovKeeper) @@ -571,7 +581,7 @@ func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { } // Here the expedited proposal is converted to regular after expiry. - gov.EndBlocker(ctx, suite.GovKeeper) + require.NoError(t, gov.EndBlocker(ctx, suite.GovKeeper)) if tc.expeditedPasses { checkActiveProposalsQueue(t, ctx, suite.GovKeeper) @@ -626,7 +636,7 @@ func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { } // Here we validate the converted regular proposal - gov.EndBlocker(ctx, suite.GovKeeper) + require.NoError(t, gov.EndBlocker(ctx, suite.GovKeeper)) macc = suite.GovKeeper.GetGovernanceAccount(ctx) require.NotNil(t, macc) @@ -661,6 +671,8 @@ func TestExpeditedProposal_PassAndConversionToRegular(t *testing.T) { } func createValidators(t *testing.T, stakingMsgSvr stakingtypes.MsgServer, ctx sdk.Context, addrs []sdk.ValAddress, powerAmt []int64) { + t.Helper() + require.True(t, len(addrs) <= len(pubkeys), "Not enough pubkeys specified at top of file.") for i := 0; i < len(addrs); i++ { @@ -688,6 +700,8 @@ func getDepositMultiplier(expedited bool) int64 { } func checkActiveProposalsQueue(t *testing.T, ctx sdk.Context, k *keeper.Keeper) { + t.Helper() + err := k.ActiveProposalsQueue.Walk(ctx, collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime()), func(key collections.Pair[time.Time, uint64], value uint64) (stop bool, err error) { return false, err }) @@ -696,6 +710,8 @@ func checkActiveProposalsQueue(t *testing.T, ctx sdk.Context, k *keeper.Keeper) } func checkInactiveProposalsQueue(t *testing.T, ctx sdk.Context, k *keeper.Keeper) { + t.Helper() + err := k.InactiveProposalsQueue.Walk(ctx, collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.BlockTime()), func(key collections.Pair[time.Time, uint64], value uint64) (stop bool, err error) { return false, err }) diff --git a/x/gov/client/cli/prompt_test.go b/x/gov/client/cli/prompt_test.go index e5b01d7da3..673c9da183 100644 --- a/x/gov/client/cli/prompt_test.go +++ b/x/gov/client/cli/prompt_test.go @@ -47,7 +47,7 @@ func TestPromptIntegerOverflow(t *testing.T) { fin, fw := readline.NewFillableStdin(os.Stdin) readline.Stdin = fin - fw.Write([]byte(overflowStr + "\n")) + _, _ = fw.Write([]byte(overflowStr + "\n")) v, err := cli.Prompt(st{}, "") assert.Equal(t, st{}, v, "expected a value of zero") @@ -69,7 +69,6 @@ func TestPromptParseInteger(t *testing.T) { } for _, tc := range values { - tc := tc t.Run(tc.in, func(t *testing.T) { origStdin := readline.Stdin defer func() { @@ -78,7 +77,7 @@ func TestPromptParseInteger(t *testing.T) { fin, fw := readline.NewFillableStdin(os.Stdin) readline.Stdin = fin - fw.Write([]byte(tc.in + "\n")) + _, _ = fw.Write([]byte(tc.in + "\n")) v, err := cli.Prompt(st{}, "") assert.Nil(t, err, "expected a nil error") diff --git a/x/gov/client/cli/util_test.go b/x/gov/client/cli/util_test.go index 956ea66960..ad04e1e712 100644 --- a/x/gov/client/cli/util_test.go +++ b/x/gov/client/cli/util_test.go @@ -41,17 +41,17 @@ func TestParseSubmitLegacyProposal(t *testing.T) { fs := NewCmdSubmitLegacyProposal().Flags() // nonexistent json - fs.Set(FlagProposal, "fileDoesNotExist") + require.NoError(t, fs.Set(FlagProposal, "fileDoesNotExist")) _, err := parseSubmitLegacyProposal(fs) require.Error(t, err) // invalid json - fs.Set(FlagProposal, badJSON.Name()) + require.NoError(t, fs.Set(FlagProposal, badJSON.Name())) _, err = parseSubmitLegacyProposal(fs) require.Error(t, err) // ok json - fs.Set(FlagProposal, okJSON.Name()) + require.NoError(t, fs.Set(FlagProposal, okJSON.Name())) proposal1, err := parseSubmitLegacyProposal(fs) require.Nil(t, err, "unexpected error") require.Equal(t, "Test Proposal", proposal1.Title) @@ -61,14 +61,14 @@ func TestParseSubmitLegacyProposal(t *testing.T) { // flags that can't be used with --proposal for _, incompatibleFlag := range ProposalFlags { - fs.Set(incompatibleFlag, "some value") + require.NoError(t, fs.Set(incompatibleFlag, "some value")) _, err := parseSubmitLegacyProposal(fs) require.Error(t, err) - fs.Set(incompatibleFlag, "") + require.NoError(t, fs.Set(incompatibleFlag, "")) } // no --proposal, only flags - fs.Set(FlagProposal, "") + require.NoError(t, fs.Set(FlagProposal, "")) flagTestCases := map[string]struct { pTitle string pDescription string @@ -102,10 +102,10 @@ func TestParseSubmitLegacyProposal(t *testing.T) { } for name, tc := range flagTestCases { t.Run(name, func(t *testing.T) { - fs.Set(FlagTitle, tc.pTitle) - fs.Set(FlagDescription, tc.pDescription) - fs.Set(FlagProposalType, tc.pType) - fs.Set(FlagDeposit, proposal1.Deposit) + require.NoError(t, fs.Set(FlagTitle, tc.pTitle)) + require.NoError(t, fs.Set(FlagDescription, tc.pDescription)) + require.NoError(t, fs.Set(FlagProposalType, tc.pType)) + require.NoError(t, fs.Set(FlagDeposit, proposal1.Deposit)) proposal2, err := parseSubmitLegacyProposal(fs) if tc.expErr { @@ -214,6 +214,8 @@ func TestParseSubmitProposal(t *testing.T) { } func getCommandHelp(t *testing.T, cmd *cobra.Command) string { + t.Helper() + // Create a pipe, so we can capture the help sent to stdout. reader, writer, err := os.Pipe() require.NoError(t, err, "creating os.Pipe()") diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index abfb48daa6..994c363983 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -140,7 +140,6 @@ func TestGetPaginatedVotes(t *testing.T) { }, }, } { - t.Run(tc.description, func(t *testing.T) { marshaled := make([]cmttypes.Tx, len(tc.msgs)) cli := TxSearchMock{txs: marshaled, txConfig: encCfg.TxConfig} diff --git a/x/gov/common_test.go b/x/gov/common_test.go index 6d32bf4a53..bb07448fc5 100644 --- a/x/gov/common_test.go +++ b/x/gov/common_test.go @@ -45,6 +45,8 @@ var ( // mkTestLegacyContent creates a MsgExecLegacyContent for testing purposes. func mkTestLegacyContent(t *testing.T) *v1.MsgExecLegacyContent { + t.Helper() + msgContent, err := v1.NewLegacyContent(TestProposal, authtypes.NewModuleAddress(types.ModuleName).String()) require.NoError(t, err) @@ -113,6 +115,8 @@ type suite struct { } func createTestSuite(t *testing.T) suite { + t.Helper() + res := suite{} app, err := simtestutil.SetupWithConfiguration( diff --git a/x/gov/keeper/common_test.go b/x/gov/keeper/common_test.go index fc90a8f257..14e56ed483 100644 --- a/x/gov/keeper/common_test.go +++ b/x/gov/keeper/common_test.go @@ -60,6 +60,8 @@ func setupGovKeeper(t *testing.T) ( moduletestutil.TestEncodingConfig, sdk.Context, ) { + t.Helper() + key := storetypes.NewKVStoreKey(types.StoreKey) storeService := runtime.NewKVStoreService(key) testCtx := testutil.DefaultContextWithDB(t, key, storetypes.NewTransientStoreKey("transient_test")) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index 4438bc494d..077d8da440 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -136,7 +136,7 @@ func TestDeposits(t *testing.T) { deposit, err = govKeeper.Deposits.Get(ctx, collections.Join(proposalID, TestAddrs[1])) require.Nil(t, err) require.Equal(t, fourStake, sdk.NewCoins(deposit.Amount...)) - govKeeper.RefundAndDeleteDeposits(ctx, proposalID) + require.NoError(t, govKeeper.RefundAndDeleteDeposits(ctx, proposalID)) deposit, err = govKeeper.Deposits.Get(ctx, collections.Join(proposalID, TestAddrs[1])) require.ErrorIs(t, err, collections.ErrNotFound) require.Equal(t, addr0Initial, bankKeeper.GetAllBalances(ctx, TestAddrs[0])) @@ -148,7 +148,7 @@ func TestDeposits(t *testing.T) { proposalID = proposal.Id _, err = govKeeper.AddDeposit(ctx, proposalID, TestAddrs[0], fourStake) require.NoError(t, err) - govKeeper.DeleteAndBurnDeposits(ctx, proposalID) + require.NoError(t, govKeeper.DeleteAndBurnDeposits(ctx, proposalID)) deposits, _ = govKeeper.GetDeposits(ctx, proposalID) require.Len(t, deposits, 0) require.Equal(t, addr0Initial.Sub(fourStake...), bankKeeper.GetAllBalances(ctx, TestAddrs[0])) @@ -334,7 +334,7 @@ func TestValidateInitialDeposit(t *testing.T) { } params.MinInitialDepositRatio = sdkmath.LegacyNewDec(tc.minInitialDepositPercent).Quo(sdkmath.LegacyNewDec(100)).String() - govKeeper.Params.Set(ctx, params) + require.NoError(t, govKeeper.Params.Set(ctx, params)) err := govKeeper.ValidateInitialDeposit(ctx, tc.initialDeposit, tc.expedited) diff --git a/x/gov/keeper/grpc_query_test.go b/x/gov/keeper/grpc_query_test.go index bba32ad3d4..3bceea9951 100644 --- a/x/gov/keeper/grpc_query_test.go +++ b/x/gov/keeper/grpc_query_test.go @@ -276,7 +276,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryProposals() { func() { depositCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 20))) deposit := v1.NewDeposit(testProposals[0].Id, addrs[0], depositCoins) - suite.govKeeper.SetDeposit(ctx, deposit) + suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, deposit)) req = &v1.QueryProposalsRequest{ Depositor: addrs[0].String(), @@ -292,7 +292,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryProposals() { "request with filter of deposit address", func() { testProposals[1].Status = v1.StatusVotingPeriod - suite.govKeeper.SetProposal(ctx, *testProposals[1]) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, *testProposals[1])) suite.Require().NoError(suite.govKeeper.AddVote(ctx, testProposals[1].Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) req = &v1.QueryProposalsRequest{ @@ -510,7 +510,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryVote() { "valid request", func() { proposal.Status = v1.StatusVotingPeriod - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) suite.Require().NoError(suite.govKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) req = &v1.QueryVoteRequest{ @@ -624,7 +624,7 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryVote() { "valid request", func() { proposal.Status = v1.StatusVotingPeriod - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) suite.Require().NoError(suite.govKeeper.AddVote(ctx, proposal.Id, addrs[0], v1.NewNonSplitVoteOption(v1.OptionAbstain), "")) req = &v1beta1.QueryVoteRequest{ @@ -727,7 +727,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryVotes() { "request after adding 2 votes", func() { proposal.Status = v1.StatusVotingPeriod - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) votes = []*v1.Vote{ {ProposalId: proposal.Id, Voter: addrs[0].String(), Options: v1.NewNonSplitVoteOption(v1.OptionAbstain)}, @@ -831,7 +831,7 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryVotes() { "request after adding 2 votes", func() { proposal.Status = v1.StatusVotingPeriod - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) votes = []v1beta1.Vote{ {ProposalId: proposal.Id, Voter: addrs[0].String(), Options: v1beta1.NewNonSplitVoteOption(v1beta1.OptionAbstain)}, @@ -1121,7 +1121,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryDeposit() { func() { depositCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 20))) deposit := v1.NewDeposit(proposal.Id, addrs[0], depositCoins) - suite.govKeeper.SetDeposit(ctx, deposit) + suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, deposit)) req = &v1.QueryDepositRequest{ ProposalId: proposal.Id, @@ -1223,7 +1223,7 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryDeposit() { depositCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 20))) deposit := v1beta1.NewDeposit(proposal.Id, addrs[0], depositCoins) v1deposit := v1.NewDeposit(proposal.Id, addrs[0], depositCoins) - suite.govKeeper.SetDeposit(ctx, v1deposit) + suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, v1deposit)) req = &v1beta1.QueryDepositRequest{ ProposalId: proposal.Id, @@ -1310,11 +1310,11 @@ func (suite *KeeperTestSuite) TestGRPCQueryDeposits() { func() { depositAmount1 := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 20))) deposit1 := v1.NewDeposit(proposal.Id, addrs[0], depositAmount1) - suite.govKeeper.SetDeposit(ctx, deposit1) + suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, deposit1)) depositAmount2 := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 30))) deposit2 := v1.NewDeposit(proposal.Id, addrs[1], depositAmount2) - suite.govKeeper.SetDeposit(ctx, deposit2) + suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, deposit2)) deposits := v1.Deposits{&deposit1, &deposit2} @@ -1406,12 +1406,12 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryDeposits() { depositAmount1 := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 20))) deposit1 := v1beta1.NewDeposit(proposal.Id, addrs[0], depositAmount1) v1deposit1 := v1.NewDeposit(proposal.Id, addrs[0], depositAmount1) - suite.govKeeper.SetDeposit(ctx, v1deposit1) + suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, v1deposit1)) depositAmount2 := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, suite.stakingKeeper.TokensFromConsensusPower(ctx, 30))) deposit2 := v1beta1.NewDeposit(proposal.Id, addrs[1], depositAmount2) v1deposit2 := v1.NewDeposit(proposal.Id, addrs[1], depositAmount2) - suite.govKeeper.SetDeposit(ctx, v1deposit2) + suite.Require().NoError(suite.govKeeper.SetDeposit(ctx, v1deposit2)) deposits := v1beta1.Deposits{deposit1, deposit2} @@ -1497,7 +1497,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryTallyResult() { VotingEndTime: &propTime, Metadata: "proposal metadata", } - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) req = &v1.QueryTallyResultRequest{ProposalId: proposal.Id} @@ -1522,7 +1522,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryTallyResult() { VotingEndTime: &propTime, Metadata: "proposal metadata", } - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) req = &v1.QueryTallyResultRequest{ProposalId: proposal.Id} @@ -1547,7 +1547,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryTallyResult() { VotingEndTime: &propTime, Metadata: "proposal metadata", } - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) req = &v1.QueryTallyResultRequest{ProposalId: proposal.Id} @@ -1665,7 +1665,7 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryTallyResult() { VotingEndTime: &propTime, Metadata: "proposal metadata", } - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} @@ -1690,7 +1690,7 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryTallyResult() { VotingEndTime: &propTime, Metadata: "proposal metadata", } - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} @@ -1715,7 +1715,7 @@ func (suite *KeeperTestSuite) TestLegacyGRPCQueryTallyResult() { VotingEndTime: &propTime, Metadata: "proposal metadata", } - suite.govKeeper.SetProposal(ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(ctx, proposal)) req = &v1beta1.QueryTallyResultRequest{ProposalId: proposal.Id} diff --git a/x/gov/keeper/hooks_test.go b/x/gov/keeper/hooks_test.go index f859f923a8..4a746ad7c6 100644 --- a/x/gov/keeper/hooks_test.go +++ b/x/gov/keeper/hooks_test.go @@ -81,7 +81,7 @@ func TestHooks(t *testing.T) { newHeader := ctx.BlockHeader() newHeader.Time = ctx.BlockHeader().Time.Add(*params.MaxDepositPeriod).Add(time.Duration(1) * time.Second) ctx = ctx.WithBlockHeader(newHeader) - gov.EndBlocker(ctx, govKeeper) + require.NoError(t, gov.EndBlocker(ctx, govKeeper)) require.True(t, govHooksReceiver.AfterProposalFailedMinDepositValid) @@ -100,6 +100,6 @@ func TestHooks(t *testing.T) { newHeader = ctx.BlockHeader() newHeader.Time = ctx.BlockHeader().Time.Add(*params.VotingPeriod).Add(time.Duration(1) * time.Second) ctx = ctx.WithBlockHeader(newHeader) - gov.EndBlocker(ctx, govKeeper) + require.NoError(t, gov.EndBlocker(ctx, govKeeper)) require.True(t, govHooksReceiver.AfterProposalVotingPeriodEndedValid) } diff --git a/x/gov/keeper/msg_server_test.go b/x/gov/keeper/msg_server_test.go index f95a110100..0b873814cb 100644 --- a/x/gov/keeper/msg_server_test.go +++ b/x/gov/keeper/msg_server_test.go @@ -1761,7 +1761,7 @@ func (suite *KeeperTestSuite) TestSubmitProposal_InitialDeposit() { params := v1.DefaultParams() params.MinDeposit = tc.minDeposit params.MinInitialDepositRatio = tc.minInitialDepositRatio.String() - govKeeper.Params.Set(ctx, params) + suite.Require().NoError(govKeeper.Params.Set(ctx, params)) msg, err := v1.NewMsgSubmitProposal(TestProposal, tc.initialDeposit, address.String(), "test", "Proposal", "description of proposal", false) suite.Require().NoError(err) diff --git a/x/gov/keeper/proposal.go b/x/gov/keeper/proposal.go index a461c369ea..6499d36f11 100644 --- a/x/gov/keeper/proposal.go +++ b/x/gov/keeper/proposal.go @@ -77,7 +77,7 @@ func (keeper Keeper) SubmitProposal(ctx context.Context, messages []sdk.Msg, met if msg, ok := msg.(*v1.MsgExecLegacyContent); ok { cacheCtx, _ := sdkCtx.CacheContext() if _, err := handler(cacheCtx, msg); err != nil { - if errors.Is(types.ErrNoProposalHandlerExists, err) { + if errors.Is(err, types.ErrNoProposalHandlerExists) { return v1.Proposal{}, err } return v1.Proposal{}, errorsmod.Wrap(types.ErrInvalidProposalContent, err.Error()) diff --git a/x/gov/keeper/proposal_test.go b/x/gov/keeper/proposal_test.go index 76152a923d..1d9b358c40 100644 --- a/x/gov/keeper/proposal_test.go +++ b/x/gov/keeper/proposal_test.go @@ -32,7 +32,7 @@ func (suite *KeeperTestSuite) TestGetSetProposal() { proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", suite.addrs[0], tc.expedited) suite.Require().NoError(err) proposalID := proposal.Id - suite.govKeeper.SetProposal(suite.ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(suite.ctx, proposal)) gotProposal, err := suite.govKeeper.Proposals.Get(suite.ctx, proposalID) suite.Require().Nil(err) @@ -59,9 +59,9 @@ func (suite *KeeperTestSuite) TestDeleteProposal() { proposal, err := suite.govKeeper.SubmitProposal(suite.ctx, tp, "", "test", "summary", suite.addrs[0], tc.expedited) suite.Require().NoError(err) proposalID := proposal.Id - suite.govKeeper.SetProposal(suite.ctx, proposal) + suite.Require().NoError(suite.govKeeper.SetProposal(suite.ctx, proposal)) suite.Require().NotPanics(func() { - suite.govKeeper.DeleteProposal(suite.ctx, proposalID) + suite.Require().NoError(suite.govKeeper.DeleteProposal(suite.ctx, proposalID)) }, "") } } @@ -82,7 +82,7 @@ func (suite *KeeperTestSuite) TestActivateVotingPeriod() { suite.Require().Nil(proposal.VotingStartTime) - suite.govKeeper.ActivateVotingPeriod(suite.ctx, proposal) + suite.Require().NoError(suite.govKeeper.ActivateVotingPeriod(suite.ctx, proposal)) proposal, err = suite.govKeeper.Proposals.Get(suite.ctx, proposal.Id) suite.Require().Nil(err) @@ -238,7 +238,7 @@ func (suite *KeeperTestSuite) TestCancelProposal() { suite.Require().Nil(err) proposal2.Status = v1.ProposalStatus_PROPOSAL_STATUS_PASSED - suite.govKeeper.SetProposal(suite.ctx, proposal2) + suite.Require().NoError(suite.govKeeper.SetProposal(suite.ctx, proposal2)) return proposal2ID, suite.addrs[1].String() }, diff --git a/x/gov/keeper/tally.go b/x/gov/keeper/tally.go index fa69ca381f..972911d5ca 100644 --- a/x/gov/keeper/tally.go +++ b/x/gov/keeper/tally.go @@ -91,7 +91,6 @@ func (keeper Keeper) Tally(ctx context.Context, proposal v1.Proposal) (passes, b return false, keeper.Votes.Remove(ctx, collections.Join(vote.ProposalId, sdk.AccAddress(voter))) }) - if err != nil { return false, false, tallyResults, err } diff --git a/x/gov/keeper/vote_test.go b/x/gov/keeper/vote_test.go index aa93118ad4..21186dd679 100644 --- a/x/gov/keeper/vote_test.go +++ b/x/gov/keeper/vote_test.go @@ -31,7 +31,7 @@ func TestVotes(t *testing.T) { require.Error(t, govKeeper.AddVote(ctx, 10, addrs[0], v1.NewNonSplitVoteOption(v1.OptionYes), ""), "invalid proposal ID") proposal.Status = v1.StatusVotingPeriod - govKeeper.SetProposal(ctx, proposal) + require.NoError(t, govKeeper.SetProposal(ctx, proposal)) require.Error(t, govKeeper.AddVote(ctx, proposalID, addrs[0], v1.NewNonSplitVoteOption(invalidOption), ""), "invalid option") diff --git a/x/gov/migrations/v2/store_test.go b/x/gov/migrations/v2/store_test.go index a5c8cf9dc0..5033f1e3ec 100644 --- a/x/gov/migrations/v2/store_test.go +++ b/x/gov/migrations/v2/store_test.go @@ -80,14 +80,13 @@ func TestMigrateStore(t *testing.T) { store.Set(tc.oldKey, tc.oldValue) } - // Run migratio + // Run migration storeService := runtime.NewKVStoreService(govKey) err := v2.MigrateStore(ctx, storeService, cdc) require.NoError(t, err) // Make sure the new keys are set and old keys are deleted. for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { if !bytes.Equal(tc.oldKey, tc.newKey) { require.Nil(t, store.Get(tc.oldKey)) diff --git a/x/gov/migrations/v3/store_test.go b/x/gov/migrations/v3/store_test.go index 0808246127..3296f82736 100644 --- a/x/gov/migrations/v3/store_test.go +++ b/x/gov/migrations/v3/store_test.go @@ -76,6 +76,8 @@ func TestMigrateStore(t *testing.T) { } func compareProps(t *testing.T, oldProp v1beta1.Proposal, newProp v1.Proposal) { + t.Helper() + require.Equal(t, oldProp.ProposalId, newProp.Id) require.Equal(t, oldProp.TotalDeposit.String(), sdk.Coins(newProp.TotalDeposit).String()) require.Equal(t, oldProp.Status.String(), newProp.Status.String()) diff --git a/x/gov/module.go b/x/gov/module.go index f48d5e060e..865e114da6 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -43,7 +43,6 @@ var ( _ module.AppModuleSimulation = AppModule{} _ module.HasGenesis = AppModule{} _ module.HasServices = AppModule{} - _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasEndBlocker = AppModule{} @@ -261,9 +260,6 @@ func InvokeSetHooks(keeper *keeper.Keeper, govHooks map[string]govtypes.GovHooks return nil } -// RegisterInvariants is deprecated and will be removed in the next version of the Cosmos SDK. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { msgServer := keeper.NewMsgServerImpl(am.keeper) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 9e173f6224..b99d6179ed 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -108,7 +108,6 @@ func WeightedOperations( // generate the weighted operations for the proposal msgs var wProposalOps simulation.WeightedOperations for _, wMsg := range wMsgs { - wMsg := wMsg // pin variable var weight int appParams.GetOrGenerate(wMsg.AppParamsKey(), &weight, nil, func(_ *rand.Rand) { weight = wMsg.DefaultWeight() }, @@ -126,7 +125,6 @@ func WeightedOperations( // generate the weighted operations for the proposal contents var wLegacyProposalOps simulation.WeightedOperations for _, wContent := range wContents { - wContent := wContent // pin variable var weight int appParams.GetOrGenerate(wContent.AppParamsKey(), &weight, nil, func(_ *rand.Rand) { weight = wContent.DefaultWeight() }, diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index f39b2490fe..c6dfb7a66d 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -40,8 +40,9 @@ import ( ) var ( - _ simtypes.WeightedProposalMsg = MockWeightedProposals{} - _ simtypes.WeightedProposalContent = MockWeightedProposals{} //nolint:staticcheck // testing legacy code path + _ simtypes.WeightedProposalMsg = MockWeightedProposals{} + //nolint:staticcheck // keeping around for legacy testing + _ simtypes.WeightedProposalContent = MockWeightedProposals{} ) type MockWeightedProposals struct { @@ -62,8 +63,9 @@ func (m MockWeightedProposals) MsgSimulatorFn() simtypes.MsgSimulatorFn { } } -func (m MockWeightedProposals) ContentSimulatorFn() simtypes.ContentSimulatorFn { //nolint:staticcheck // testing legacy code path - return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) simtypes.Content { //nolint:staticcheck // testing legacy code path +//nolint:staticcheck // retaining legacy content to maintain gov functionality +func (m MockWeightedProposals) ContentSimulatorFn() simtypes.ContentSimulatorFn { + return func(r *rand.Rand, _ sdk.Context, _ []simtypes.Account) simtypes.Content { return v1beta1.NewTextProposal( fmt.Sprintf("title-%d: %s", m.n, simtypes.RandStringOfLength(r, 100)), fmt.Sprintf("description-%d: %s", m.n, simtypes.RandStringOfLength(r, 4000)), @@ -79,8 +81,9 @@ func mockWeightedProposalMsg(n int) []simtypes.WeightedProposalMsg { return wpc } -func mockWeightedLegacyProposalContent(n int) []simtypes.WeightedProposalContent { //nolint:staticcheck // testing legacy code path - wpc := make([]simtypes.WeightedProposalContent, n) //nolint:staticcheck // testing legacy code path +// nolint // keeping this legacy proposal for testing +func mockWeightedLegacyProposalContent(n int) []simtypes.WeightedProposalContent { + wpc := make([]simtypes.WeightedProposalContent, n) for i := 0; i < n; i++ { wpc[i] = MockWeightedProposals{i} } @@ -143,10 +146,11 @@ func TestSimulateMsgSubmitProposal(t *testing.T) { r := rand.New(s) accounts := getTestingAccounts(t, r, suite.AccountKeeper, suite.BankKeeper, suite.StakingKeeper, ctx, 3) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) // execute operation op := simulation.SimulateMsgSubmitProposal(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, MockWeightedProposals{3}.MsgSimulatorFn()) @@ -174,10 +178,11 @@ func TestSimulateMsgSubmitLegacyProposal(t *testing.T) { r := rand.New(s) accounts := getTestingAccounts(t, r, suite.AccountKeeper, suite.BankKeeper, suite.StakingKeeper, ctx, 3) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) // execute operation op := simulation.SimulateMsgSubmitLegacyProposal(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper, MockWeightedProposals{3}.ContentSimulatorFn()) @@ -230,12 +235,13 @@ func TestSimulateMsgCancelProposal(t *testing.T) { proposal, err := v1.NewProposal([]sdk.Msg{contentMsg}, 1, submitTime, submitTime.Add(*depositPeriod), "", "title", "summary", proposer, false) require.NoError(t, err) - suite.GovKeeper.SetProposal(ctx, proposal) + require.NoError(t, suite.GovKeeper.SetProposal(ctx, proposal)) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) // execute operation op := simulation.SimulateMsgCancelProposal(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) @@ -277,12 +283,13 @@ func TestSimulateMsgDeposit(t *testing.T) { proposal, err := v1.NewProposal([]sdk.Msg{contentMsg}, 1, submitTime, submitTime.Add(*depositPeriod), "", "text proposal", "description", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) require.NoError(t, err) - suite.GovKeeper.SetProposal(ctx, proposal) + require.NoError(t, suite.GovKeeper.SetProposal(ctx, proposal)) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) // execute operation op := simulation.SimulateMsgDeposit(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) @@ -332,6 +339,7 @@ func TestSimulateMsgVote(t *testing.T) { Hash: app.LastCommitID().Hash, }) require.NoError(t, err) + // execute operation op := simulation.SimulateMsgVote(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) operationMsg, _, err := op(r, app.BaseApp, ctx, accounts, "") @@ -371,12 +379,13 @@ func TestSimulateMsgVoteWeighted(t *testing.T) { proposal, err := v1.NewProposal([]sdk.Msg{contentMsg}, 1, submitTime, submitTime.Add(*depositPeriod), "", "text proposal", "test", sdk.AccAddress("cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r"), false) require.NoError(t, err) - suite.GovKeeper.ActivateVotingPeriod(ctx, proposal) + require.NoError(t, suite.GovKeeper.ActivateVotingPeriod(ctx, proposal)) - app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: app.LastBlockHeight() + 1, Hash: app.LastCommitID().Hash, }) + require.NoError(t, err) // execute operation op := simulation.SimulateMsgVoteWeighted(suite.TxConfig, suite.AccountKeeper, suite.BankKeeper, suite.GovKeeper) @@ -405,6 +414,8 @@ type suite struct { // returns context and an app with updated mint keeper func createTestSuite(t *testing.T, isCheckTx bool) (suite, sdk.Context) { + t.Helper() + res := suite{} app, err := simtestutil.Setup( @@ -431,10 +442,16 @@ func createTestSuite(t *testing.T, isCheckTx bool) (suite, sdk.Context) { } func getTestingAccounts( - t *testing.T, r *rand.Rand, - accountKeeper authkeeper.AccountKeeper, bankKeeper bankkeeper.Keeper, stakingKeeper *stakingkeeper.Keeper, - ctx sdk.Context, n int, + t *testing.T, + r *rand.Rand, + accountKeeper authkeeper.AccountKeeper, + bankKeeper bankkeeper.Keeper, + stakingKeeper *stakingkeeper.Keeper, + ctx sdk.Context, + n int, ) []simtypes.Account { + t.Helper() + accounts := simtypes.RandomAccounts(r, n) initAmt := stakingKeeper.TokensFromConsensusPower(ctx, 200) diff --git a/x/gov/types/metadata.go b/x/gov/types/metadata.go index 504ed72a1b..fd52da4a28 100644 --- a/x/gov/types/metadata.go +++ b/x/gov/types/metadata.go @@ -7,6 +7,6 @@ type ProposalMetadata struct { Authors []string `json:"authors"` Summary string `json:"summary"` Details string `json:"details"` - ProposalForumUrl string `json:"proposal_forum_url"` //nolint:revive // named 'Url' instead of 'URL' for avoiding the camel case split + ProposalForumUrl string `json:"proposal_forum_url"` VoteOptionContext string `json:"vote_option_context"` } diff --git a/x/gov/types/v1/genesis.go b/x/gov/types/v1/genesis.go index 71352bb778..0065eb9ea9 100644 --- a/x/gov/types/v1/genesis.go +++ b/x/gov/types/v1/genesis.go @@ -54,7 +54,7 @@ func ValidateGenesis(data *GenesisState) error { // weed out duplicate deposits errGroup.Go(func() error { type depositKey struct { - ProposalId uint64 //nolint:revive // staying consistent with main and v0.47 + ProposalId uint64 Depositor string } depositIds := make(map[depositKey]struct{}) @@ -77,7 +77,7 @@ func ValidateGenesis(data *GenesisState) error { // weed out duplicate votes errGroup.Go(func() error { type voteKey struct { - ProposalId uint64 //nolint:revive // staying consistent with main and v0.47 + ProposalId uint64 Voter string } voteIds := make(map[voteKey]struct{}) diff --git a/x/gov/types/v1/proposal.go b/x/gov/types/v1/proposal.go index 79bc095b56..1965824e51 100644 --- a/x/gov/types/v1/proposal.go +++ b/x/gov/types/v1/proposal.go @@ -112,10 +112,10 @@ func ProposalStatusFromString(str string) (ProposalStatus, error) { func (status ProposalStatus) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(status.String())) + _, _ = s.Write([]byte(status.String())) default: // TODO: Do this conversion more directly - s.Write([]byte(fmt.Sprintf("%v", byte(status)))) + _, _ = s.Write([]byte(fmt.Sprintf("%v", byte(status)))) } } diff --git a/x/gov/types/v1/vote.go b/x/gov/types/v1/vote.go index edadc77075..e5bc445966 100644 --- a/x/gov/types/v1/vote.go +++ b/x/gov/types/v1/vote.go @@ -145,8 +145,8 @@ func ValidVoteOption(option VoteOption) bool { func (vo VoteOption) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(vo.String())) + _, _ = s.Write([]byte(vo.String())) default: - s.Write([]byte(fmt.Sprintf("%v", byte(vo)))) + _, _ = s.Write([]byte(fmt.Sprintf("%v", byte(vo)))) } } diff --git a/x/gov/types/v1beta1/proposal.go b/x/gov/types/v1beta1/proposal.go index e603ee1676..8c90b910fb 100644 --- a/x/gov/types/v1beta1/proposal.go +++ b/x/gov/types/v1beta1/proposal.go @@ -140,10 +140,9 @@ func ProposalStatusFromString(str string) (ProposalStatus, error) { func (status ProposalStatus) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(status.String())) + _, _ = s.Write([]byte(status.String())) default: - // TODO: Do this conversion more directly - s.Write([]byte(fmt.Sprintf("%v", byte(status)))) + _, _ = s.Write([]byte(fmt.Sprintf("%v", byte(status)))) } } diff --git a/x/gov/types/v1beta1/vote.go b/x/gov/types/v1beta1/vote.go index b3d47be310..e681014f39 100644 --- a/x/gov/types/v1beta1/vote.go +++ b/x/gov/types/v1beta1/vote.go @@ -120,8 +120,8 @@ func ValidVoteOption(option VoteOption) bool { func (vo VoteOption) Format(s fmt.State, verb rune) { switch verb { case 's': - s.Write([]byte(vo.String())) + _, _ = s.Write([]byte(vo.String())) default: - s.Write([]byte(fmt.Sprintf("%v", byte(vo)))) + _, _ = s.Write([]byte(fmt.Sprintf("%v", byte(vo)))) } } diff --git a/x/group/client/cli/tx.go b/x/group/client/cli/tx.go index 59c71073f6..ed0af47bfd 100644 --- a/x/group/client/cli/tx.go +++ b/x/group/client/cli/tx.go @@ -618,11 +618,13 @@ metadata example: // Since the --from flag is not required on this CLI command, we // ignore it, and just use the 1st proposer in the JSON file. - if prop.Proposers == nil || len(prop.Proposers) == 0 { + if len(prop.Proposers) == 0 { return errors.New("no proposers specified in proposal") } - cmd.Flags().Set(flags.FlagFrom, prop.Proposers[0]) - + err = cmd.Flags().Set(flags.FlagFrom, prop.Proposers[0]) + if err != nil { + return err + } clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err @@ -808,7 +810,10 @@ Parameters: `, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cmd.Flags().Set(flags.FlagFrom, args[0]) + err := cmd.Flags().Set(flags.FlagFrom, args[0]) + if err != nil { + return err + } clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err diff --git a/x/group/client/cli/tx_test.go b/x/group/client/cli/tx_test.go index 926b1a49cf..9def6aa675 100644 --- a/x/group/client/cli/tx_test.go +++ b/x/group/client/cli/tx_test.go @@ -130,7 +130,7 @@ func (s *CLITestSuite) TestTxCreateGroup() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) cmd := groupcli.MsgCreateGroupCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", @@ -207,7 +207,6 @@ func (s *CLITestSuite) TestTxCreateGroup() { } for _, tc := range testCases { - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) @@ -235,7 +234,7 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 2) cmd := groupcli.MsgUpdateGroupAdminCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) ctx := svrcmd.CreateExecuteContext(context.Background()) cmd.SetContext(ctx) @@ -334,7 +333,6 @@ func (s *CLITestSuite) TestTxUpdateGroupAdmin() { } for _, tc := range testCases { - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -364,7 +362,7 @@ func (s *CLITestSuite) TestTxUpdateGroupMetadata() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) cmd := groupcli.MsgUpdateGroupMetadataCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) testCases := []struct { name string @@ -428,7 +426,6 @@ func (s *CLITestSuite) TestTxUpdateGroupMetadata() { } for _, tc := range testCases { - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -459,7 +456,7 @@ func (s *CLITestSuite) TestTxUpdateGroupMembers() { groupPolicyAddress := accounts[2] cmd := groupcli.MsgUpdateGroupMembersCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) groupID := "1" @@ -542,7 +539,6 @@ func (s *CLITestSuite) TestTxUpdateGroupMembers() { } for _, tc := range testCases { - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -572,7 +568,7 @@ func (s *CLITestSuite) TestTxCreateGroupWithPolicy() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) cmd := groupcli.MsgCreateGroupWithPolicyCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", @@ -662,8 +658,6 @@ func (s *CLITestSuite) TestTxCreateGroupWithPolicy() { }, } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -702,7 +696,7 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { invalidPercentageDecisionPolicyFile := testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"2", "windows":{"voting_period":"1s"}}`) cmd := groupcli.MsgCreateGroupPolicyCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) testCases := []struct { name string @@ -798,8 +792,6 @@ func (s *CLITestSuite) TestTxCreateGroupPolicy() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -835,7 +827,7 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyAdmin() { commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) cmd := groupcli.MsgUpdateGroupPolicyAdminCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) testCases := []struct { name string @@ -899,8 +891,6 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyAdmin() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -939,7 +929,7 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { percentageDecisionPolicy := testutil.WriteToNewTempFile(s.T(), `{"@type":"/cosmos.group.v1.PercentageDecisionPolicy", "percentage":"0.5", "windows":{"voting_period":"40000s"}}`) cmd := groupcli.MsgUpdateGroupPolicyDecisionPolicyCmd(address.NewBech32Codec("cosmos")) - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) testCases := []struct { name string @@ -1003,8 +993,6 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -1039,7 +1027,7 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyMetadata() { commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) cmd := groupcli.MsgUpdateGroupPolicyMetadataCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) testCases := []struct { name string @@ -1090,8 +1078,6 @@ func (s *CLITestSuite) TestTxUpdateGroupPolicyMetadata() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -1132,7 +1118,7 @@ func (s *CLITestSuite) TestTxSubmitProposal() { proposalFile := testutil.WriteToNewTempFile(s.T(), string(bz)) cmd := groupcli.MsgSubmitProposalCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) testCases := []struct { name string @@ -1190,8 +1176,6 @@ func (s *CLITestSuite) TestTxSubmitProposal() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -1221,7 +1205,7 @@ func (s *CLITestSuite) TestTxVote() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 4) cmd := groupcli.MsgVoteCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) ids := make([]string, 4) for i := 0; i < len(ids); i++ { @@ -1295,8 +1279,6 @@ func (s *CLITestSuite) TestTxVote() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) @@ -1326,7 +1308,7 @@ func (s *CLITestSuite) TestTxWithdrawProposal() { accounts := testutil.CreateKeyringAccounts(s.T(), s.kr, 1) cmd := groupcli.MsgWithdrawProposalCmd() - cmd.SetOutput(io.Discard) + cmd.SetOut(io.Discard) ids := make([]string, 2) ids[0] = "1" @@ -1377,8 +1359,6 @@ func (s *CLITestSuite) TestTxWithdrawProposal() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { ctx := svrcmd.CreateExecuteContext(context.Background()) diff --git a/x/group/internal/orm/auto_uint64_test.go b/x/group/internal/orm/auto_uint64_test.go index 8f4108e6a5..d5656b0d19 100644 --- a/x/group/internal/orm/auto_uint64_test.go +++ b/x/group/internal/orm/auto_uint64_test.go @@ -43,7 +43,6 @@ func TestAutoUInt64PrefixScan(t *testing.T) { Metadata: metadata, } for _, g := range []testdata.TableModel{t1, t2, t3} { - g := g _, err := tb.Create(store, &g) require.NoError(t, err) } diff --git a/x/group/internal/orm/index_test.go b/x/group/internal/orm/index_test.go index a965190b64..9b239c6acf 100644 --- a/x/group/internal/orm/index_test.go +++ b/x/group/internal/orm/index_test.go @@ -120,7 +120,6 @@ func TestIndexPrefixScan(t *testing.T) { Metadata: []byte("metadata-b"), } for _, g := range []testdata.TableModel{g1, g2, g3} { - g := g _, err := tb.Create(store, &g) require.NoError(t, err) } diff --git a/x/group/internal/orm/iterator.go b/x/group/internal/orm/iterator.go index 6b3927b094..0d78667d41 100644 --- a/x/group/internal/orm/iterator.go +++ b/x/group/internal/orm/iterator.go @@ -298,7 +298,7 @@ func assertDest(dest ModelSlicePtr, destRef, tmpSlice *reflect.Value) (reflect.T protoMarshaler := reflect.TypeOf((*proto.Message)(nil)).Elem() if !elemType.Implements(protoMarshaler) && - !reflect.PtrTo(elemType).Implements(protoMarshaler) { + !reflect.PointerTo(elemType).Implements(protoMarshaler) { return nil, errorsmod.Wrapf(errors.ErrORMInvalidArgument, "unsupported type :%s", elemType) } diff --git a/x/group/internal/orm/iterator_property_test.go b/x/group/internal/orm/iterator_property_test.go index 8a1b473fea..25ba5343d0 100644 --- a/x/group/internal/orm/iterator_property_test.go +++ b/x/group/internal/orm/iterator_property_test.go @@ -42,7 +42,8 @@ func TestPaginationProperty(t *testing.T) { } dest := reconstructedTableModels[offset:end] tableModelsIt := testTableModelIterator(tableModels, nil) - Paginate(tableModelsIt, pageRequest, &dest) + _, err := Paginate(tableModelsIt, pageRequest, &dest) + require.NoError(t, err) reconstructedTableModels = append(reconstructedTableModels, dest...) } diff --git a/x/group/internal/orm/iterator_test.go b/x/group/internal/orm/iterator_test.go index a7b4854dd1..0ef2d9333f 100644 --- a/x/group/internal/orm/iterator_test.go +++ b/x/group/internal/orm/iterator_test.go @@ -240,7 +240,6 @@ func TestPaginate(t *testing.T) { } for _, g := range []testdata.TableModel{t1, t2, t3, t4, t5} { - g := g _, err := tb.Create(store, &g) require.NoError(t, err) } diff --git a/x/group/internal/orm/orm_scenario_test.go b/x/group/internal/orm/orm_scenario_test.go index f93fd76775..7b2391e2d8 100644 --- a/x/group/internal/orm/orm_scenario_test.go +++ b/x/group/internal/orm/orm_scenario_test.go @@ -274,7 +274,6 @@ func TestGasCostsPrimaryKeyTable(t *testing.T) { for i, m := range tms { gCtx.ResetGasMeter() - m := m err = k.primaryKeyTable.Delete(gCtx.KVStore(store), &m) require.NoError(t, err) @@ -335,7 +334,8 @@ func TestExportImportStateAutoUInt64Table(t *testing.T) { it, err := k.autoUInt64TableModelByMetadataIndex.Get(store, exp) require.NoError(t, err) var all []testdata.TableModel - ReadAll(it, &all) + _, err = ReadAll(it, &all) + require.NoError(t, err) require.Len(t, all, 1) assert.Equal(t, loaded, all[0]) } @@ -396,6 +396,8 @@ func TestExportImportStatePrimaryKeyTable(t *testing.T) { } func assertIndex(t *testing.T, store storetypes.KVStore, index Index, v testdata.TableModel, searchKey interface{}) { + t.Helper() + it, err := index.Get(store, searchKey) require.NoError(t, err) @@ -407,6 +409,8 @@ func assertIndex(t *testing.T, store storetypes.KVStore, index Index, v testdata } func first(t *testing.T, it Iterator) ([]byte, testdata.TableModel) { + t.Helper() + var loaded testdata.TableModel key, err := First(it, &loaded) require.NoError(t, err) diff --git a/x/group/internal/orm/primary_key_test.go b/x/group/internal/orm/primary_key_test.go index d53a17c8cd..d83d04b094 100644 --- a/x/group/internal/orm/primary_key_test.go +++ b/x/group/internal/orm/primary_key_test.go @@ -42,7 +42,6 @@ func TestPrimaryKeyTablePrefixScan(t *testing.T) { Metadata: metadata, } for _, g := range []testdata.TableModel{t1, t2, t3} { - g := g require.NoError(t, tb.Create(store, &g)) } diff --git a/x/group/internal/orm/table.go b/x/group/internal/orm/table.go index b2024fad01..f15d9f7639 100644 --- a/x/group/internal/orm/table.go +++ b/x/group/internal/orm/table.go @@ -117,7 +117,7 @@ func (a table) Set(store types.KVStore, rowID RowID, newValue proto.Message) err var oldValue proto.Message if a.Has(store, rowID) { oldValue = reflect.New(a.model).Interface().(proto.Message) - a.GetOne(store, rowID, oldValue) + _ = a.GetOne(store, rowID, oldValue) } newValueEncoded, err := a.cdc.Marshal(newValue) diff --git a/x/group/keeper/keeper.go b/x/group/keeper/keeper.go index 4a79e73033..8c8f54e094 100644 --- a/x/group/keeper/keeper.go +++ b/x/group/keeper/keeper.go @@ -285,7 +285,6 @@ func (k Keeper) abortProposals(ctx sdk.Context, groupPolicyAddr sdk.AccAddress) return err } - //nolint:gosec // "implicit memory aliasing in the for loop (because of the pointer on &proposalInfo)" for _, proposalInfo := range proposals { // Mark all proposals still in the voting phase as aborted. if proposalInfo.Status == group.PROPOSAL_STATUS_SUBMITTED { @@ -330,7 +329,6 @@ func (k Keeper) pruneVotes(ctx sdk.Context, proposalID uint64) error { return err } - //nolint:gosec // "implicit memory aliasing in the for loop (because of the pointer on &v)" for _, v := range votes { err = k.voteTable.Delete(ctx.KVStore(k.key), &v) if err != nil { @@ -399,7 +397,6 @@ func (k Keeper) TallyProposalsAtVPEnd(ctx sdk.Context) error { if err != nil { return nil } - //nolint:gosec // "implicit memory aliasing in the for loop (because of the pointers in the loop)" for _, proposal := range proposals { policyInfo, err := k.getGroupPolicyInfo(ctx, proposal.GroupPolicyAddress) if err != nil { diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index f12d1d7186..c7d42bc00f 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -117,9 +117,9 @@ func (s *TestSuite) SetupTest() { s.groupPolicyAddr = addrbz s.bankKeeper.EXPECT().MintCoins(s.sdkCtx, minttypes.ModuleName, sdk.Coins{sdk.NewInt64Coin("test", 100000)}).Return(nil).AnyTimes() - s.bankKeeper.MintCoins(s.sdkCtx, minttypes.ModuleName, sdk.Coins{sdk.NewInt64Coin("test", 100000)}) + s.Require().NoError(s.bankKeeper.MintCoins(s.sdkCtx, minttypes.ModuleName, sdk.Coins{sdk.NewInt64Coin("test", 100000)})) s.bankKeeper.EXPECT().SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, s.groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)}).Return(nil).AnyTimes() - s.bankKeeper.SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, s.groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)}) + s.Require().NoError(s.bankKeeper.SendCoinsFromModuleToAccount(s.sdkCtx, minttypes.ModuleName, s.groupPolicyAddr, sdk.Coins{sdk.NewInt64Coin("test", 10000)})) } func (s *TestSuite) setNextAccount() { @@ -135,7 +135,7 @@ func (s *TestSuite) setNextAccount() { groupPolicyAccBumpAccountNumber, err := authtypes.NewBaseAccountWithPubKey(ac) s.Require().NoError(err) - groupPolicyAccBumpAccountNumber.SetAccountNumber(nextAccVal) + s.Require().NoError(groupPolicyAccBumpAccountNumber.SetAccountNumber(nextAccVal)) s.Require().NoError(err) @@ -264,11 +264,10 @@ func (s *TestSuite) TestProposalsByVPEnd() { } for msg, spec := range specs { - spec := spec s.Run(msg, func() { pID := spec.preRun(s.sdkCtx) - module.EndBlocker(spec.newCtx, s.groupKeeper) + s.Require().NoError(module.EndBlocker(spec.newCtx, s.groupKeeper)) resp, err := s.groupKeeper.Proposal(spec.newCtx, &group.QueryProposalRequest{ ProposalId: pID, }) @@ -452,7 +451,7 @@ func (s *TestSuite) TestTallyProposalsAtVPEnd() { s.Require().NoError(err) s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctx)) - s.NotPanics(func() { module.EndBlocker(ctx, s.groupKeeper) }) + s.NotPanics(func() { _ = module.EndBlocker(ctx, s.groupKeeper) }) } // TestTallyProposalsAtVPEnd_GroupMemberLeaving test that the node doesn't @@ -514,7 +513,7 @@ func (s *TestSuite) TestTallyProposalsAtVPEnd_GroupMemberLeaving() { // Tally the result. This saves the tally result to state. s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctx)) - s.NotPanics(func() { module.EndBlocker(ctx, s.groupKeeper) }) + s.NotPanics(func() { _ = module.EndBlocker(ctx, s.groupKeeper) }) // member 2 (high weight) leaves group. _, err = s.groupKeeper.LeaveGroup(ctx, &group.MsgLeaveGroup{ @@ -524,5 +523,5 @@ func (s *TestSuite) TestTallyProposalsAtVPEnd_GroupMemberLeaving() { s.Require().NoError(err) s.Require().NoError(s.groupKeeper.TallyProposalsAtVPEnd(ctx)) - s.NotPanics(func() { module.EndBlocker(ctx, s.groupKeeper) }) + s.NotPanics(func() { _ = module.EndBlocker(ctx, s.groupKeeper) }) } diff --git a/x/group/keeper/msg_server_test.go b/x/group/keeper/msg_server_test.go index bd50530688..cc1039bd82 100644 --- a/x/group/keeper/msg_server_test.go +++ b/x/group/keeper/msg_server_test.go @@ -172,7 +172,6 @@ func (s *TestSuite) TestCreateGroup() { var seq uint32 = 1 for msg, spec := range specs { - spec := spec s.Run(msg, func() { blockTime := sdk.UnwrapSDKContext(s.ctx).BlockTime() res, err := s.groupKeeper.CreateGroup(s.ctx, spec.req) @@ -405,7 +404,8 @@ func (s *TestSuite) TestUpdateGroupMembers() { { Member: &group.Member{Address: member2, Weight: "2", AddedAt: s.blockTime}, GroupId: groupID, - }}, + }, + }, }, "remove existing member": { req: &group.MsgUpdateGroupMembers{ @@ -424,7 +424,8 @@ func (s *TestSuite) TestUpdateGroupMembers() { { Member: &group.Member{Address: member2, Weight: "2", AddedAt: s.blockTime}, GroupId: groupID, - }}, + }, + }, }, "remove unknown member": { req: &group.MsgUpdateGroupMembers{ @@ -447,7 +448,8 @@ func (s *TestSuite) TestUpdateGroupMembers() { }, { Member: &group.Member{Address: member2, Weight: "2", AddedAt: s.blockTime}, GroupId: groupID, - }}, + }, + }, }, "with wrong admin": { req: &group.MsgUpdateGroupMembers{ @@ -509,7 +511,6 @@ func (s *TestSuite) TestUpdateGroupMembers() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { sdkCtx, _ := s.sdkCtx.CacheContext() _, err := s.groupKeeper.UpdateGroupMembers(sdkCtx, spec.req) @@ -652,7 +653,6 @@ func (s *TestSuite) TestUpdateGroupAdmin() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { _, err := s.groupKeeper.UpdateGroupAdmin(s.ctx, spec.req) if spec.expErr { @@ -726,7 +726,6 @@ func (s *TestSuite) TestUpdateGroupMetadata() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { sdkCtx, _ := s.sdkCtx.CacheContext() _, err := s.groupKeeper.UpdateGroupMetadata(sdkCtx, spec.req) @@ -902,7 +901,6 @@ func (s *TestSuite) TestCreateGroupWithPolicy() { } for msg, spec := range specs { - spec := spec s.Run(msg, func() { s.setNextAccount() err := spec.req.SetDecisionPolicy(spec.policy) @@ -1093,7 +1091,6 @@ func (s *TestSuite) TestCreateGroupPolicy() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { err := spec.req.SetDecisionPolicy(spec.policy) s.Require().NoError(err) @@ -1223,7 +1220,6 @@ func (s *TestSuite) TestUpdateGroupPolicyAdmin() { }, } for msg, spec := range specs { - spec := spec err := spec.expGroupPolicy.SetDecisionPolicy(policy) s.Require().NoError(err) @@ -1373,7 +1369,6 @@ func (s *TestSuite) TestUpdateGroupPolicyDecisionPolicy() { }, } for msg, spec := range specs { - spec := spec policyAddr := groupPolicyAddr err := spec.expGroupPolicy.SetDecisionPolicy(spec.policy) s.Require().NoError(err) @@ -1475,7 +1470,6 @@ func (s *TestSuite) TestUpdateGroupPolicyMetadata() { }, } for msg, spec := range specs { - spec := spec err := spec.expGroupPolicy.SetDecisionPolicy(policy) s.Require().NoError(err) @@ -1884,7 +1878,6 @@ func (s *TestSuite) TestSubmitProposal() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { err := spec.req.SetMsgs(spec.msgs) s.Require().NoError(err) @@ -2013,7 +2006,6 @@ func (s *TestSuite) TestWithdrawProposal() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { pID := spec.preRun(s.sdkCtx) @@ -2401,7 +2393,6 @@ func (s *TestSuite) TestVote() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { sdkCtx := s.sdkCtx if !spec.srcCtx.IsZero() { @@ -2755,7 +2746,6 @@ func (s *TestSuite) TestExecProposal() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { sdkCtx, _ := s.sdkCtx.CacheContext() proposalID := spec.setupProposal(sdkCtx) @@ -2799,7 +2789,6 @@ func (s *TestSuite) TestExecProposal() { } spec.postRun(sdkCtx) }) - } } @@ -2956,7 +2945,6 @@ func (s *TestSuite) TestExecPrunedProposalsAndVotes() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { sdkCtx, _ := s.sdkCtx.CacheContext() proposalID := spec.setupProposal(sdkCtx) @@ -3349,7 +3337,7 @@ func (s *TestSuite) TestExecProposalsWhenMemberLeavesOrIsUpdated() { Admin: s.addrs[0].String(), GroupPolicyAddress: groupPolicyAddr, } - newGroupPolicy.SetDecisionPolicy(group.NewThresholdDecisionPolicy("10", time.Second, minExecutionPeriod)) + s.Require().NoError(newGroupPolicy.SetDecisionPolicy(group.NewThresholdDecisionPolicy("10", time.Second, minExecutionPeriod))) _, err := k.UpdateGroupPolicyDecisionPolicy(ctx, newGroupPolicy) return err @@ -3358,7 +3346,6 @@ func (s *TestSuite) TestExecProposalsWhenMemberLeavesOrIsUpdated() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { sdkCtx, _ := s.sdkCtx.CacheContext() diff --git a/x/group/keeper/tally_test.go b/x/group/keeper/tally_test.go index 3ca56dedc1..a6b47fc570 100644 --- a/x/group/keeper/tally_test.go +++ b/x/group/keeper/tally_test.go @@ -68,7 +68,6 @@ func (s *TestSuite) TestTally() { } for msg, spec := range specs { - spec := spec s.Run(msg, func() { sdkCtx, _ := s.sdkCtx.CacheContext() pID := spec.setupProposal(sdkCtx) diff --git a/x/group/module/abci_test.go b/x/group/module/abci_test.go index 06cd5c883b..0afbea0173 100644 --- a/x/group/module/abci_test.go +++ b/x/group/module/abci_test.go @@ -16,7 +16,6 @@ import ( codecaddress "github.com/cosmos/cosmos-sdk/codec/address" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/runtime" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" @@ -32,7 +31,6 @@ import ( type IntegrationTestSuite struct { suite.Suite - app *runtime.App ctx sdk.Context addrs []sdk.AccAddress groupKeeper keeper.Keeper @@ -165,7 +163,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { "proposal pruned after executor result success": { setupProposal: func(ctx sdk.Context) uint64 { msgs := []sdk.Msg{msgSend1} - pID, err := submitProposalAndVote(s, s.app, ctx, msgs, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) + pID, err := submitProposalAndVote(s, ctx, msgs, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) s.Require().NoError(err) _, err = s.groupKeeper.Exec(ctx, &group.MsgExec{Executor: addr3.String(), ProposalId: pID}) s.Require().NoError(err) @@ -181,7 +179,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { "proposal with multiple messages pruned when executed with result success": { setupProposal: func(ctx sdk.Context) uint64 { msgs := []sdk.Msg{msgSend1, msgSend1} - pID, err := submitProposalAndVote(s, s.app, ctx, msgs, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) + pID, err := submitProposalAndVote(s, ctx, msgs, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) s.Require().NoError(err) _, err = s.groupKeeper.Exec(ctx, &group.MsgExec{Executor: addr3.String(), ProposalId: pID}) s.Require().NoError(err) @@ -197,7 +195,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { "proposal not pruned when not executed and rejected": { setupProposal: func(ctx sdk.Context) uint64 { msgs := []sdk.Msg{msgSend1} - pID, err := submitProposalAndVote(s, s.app, ctx, msgs, proposers, groupPolicyAddr, group.VOTE_OPTION_NO) + pID, err := submitProposalAndVote(s, ctx, msgs, proposers, groupPolicyAddr, group.VOTE_OPTION_NO) s.Require().NoError(err) _, err = s.groupKeeper.Exec(ctx, &group.MsgExec{Executor: addr3.String(), ProposalId: pID}) s.Require().NoError(err) @@ -212,7 +210,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { }, "open proposal is not pruned which must not fail ": { setupProposal: func(ctx sdk.Context) uint64 { - pID, err := submitProposal(s, s.app, ctx, []sdk.Msg{msgSend1}, proposers, groupPolicyAddr) + pID, err := submitProposal(s, ctx, []sdk.Msg{msgSend1}, proposers, groupPolicyAddr) s.Require().NoError(err) _, err = s.groupKeeper.Exec(ctx, &group.MsgExec{Executor: addr3.String(), ProposalId: pID}) s.Require().NoError(err) @@ -227,7 +225,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { }, "proposal not pruned with group policy modified before tally": { setupProposal: func(ctx sdk.Context) uint64 { - pID, err := submitProposal(s, s.app, ctx, []sdk.Msg{msgSend1}, proposers, groupPolicyAddr) + pID, err := submitProposal(s, ctx, []sdk.Msg{msgSend1}, proposers, groupPolicyAddr) s.Require().NoError(err) _, err = s.groupKeeper.UpdateGroupPolicyMetadata(ctx, &group.MsgUpdateGroupPolicyMetadata{ Admin: addr1.String(), @@ -248,7 +246,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { "pruned when proposal is executable when failed before": { setupProposal: func(ctx sdk.Context) uint64 { msgs := []sdk.Msg{msgSend1} - pID, err := submitProposalAndVote(s, s.app, ctx, msgs, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) + pID, err := submitProposalAndVote(s, ctx, msgs, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) s.Require().NoError(err) _, err = s.groupKeeper.Exec(ctx, &group.MsgExec{Executor: s.addrs[2].String(), ProposalId: pID}) s.Require().NoError(err) @@ -260,7 +258,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { }, "proposal with status withdrawn is pruned after voting period end": { setupProposal: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposal(s, s.app, sdkCtx, []sdk.Msg{msgSend1}, proposers, groupPolicyAddr) + pID, err := submitProposal(s, sdkCtx, []sdk.Msg{msgSend1}, proposers, groupPolicyAddr) s.Require().NoError(err) _, err = s.groupKeeper.WithdrawProposal(ctx, &group.MsgWithdrawProposal{ ProposalId: pID, @@ -275,7 +273,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { }, "proposal with status withdrawn is not pruned (before voting period)": { setupProposal: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposal(s, s.app, sdkCtx, []sdk.Msg{msgSend1}, proposers, groupPolicyAddr) + pID, err := submitProposal(s, sdkCtx, []sdk.Msg{msgSend1}, proposers, groupPolicyAddr) s.Require().NoError(err) _, err = s.groupKeeper.WithdrawProposal(ctx, &group.MsgWithdrawProposal{ ProposalId: pID, @@ -291,7 +289,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { }, "proposal with status aborted is pruned after voting period end (due to updated group policy decision policy)": { setupProposal: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposal(s, s.app, sdkCtx, []sdk.Msg{msgSend2}, proposers, groupPolicyAddr2) + pID, err := submitProposal(s, sdkCtx, []sdk.Msg{msgSend2}, proposers, groupPolicyAddr2) s.Require().NoError(err) policy := group.NewThresholdDecisionPolicy("3", time.Second, 0) @@ -313,7 +311,7 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { }, "proposal with status aborted is not pruned before voting period end (due to updated group policy)": { setupProposal: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposal(s, s.app, sdkCtx, []sdk.Msg{msgSend2}, proposers, groupPolicyAddr2) + pID, err := submitProposal(s, sdkCtx, []sdk.Msg{msgSend2}, proposers, groupPolicyAddr2) s.Require().NoError(err) policy := group.NewThresholdDecisionPolicy("3", time.Second, 0) @@ -335,11 +333,10 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { }, } for msg, spec := range specs { - spec := spec s.Run(msg, func() { proposalID := spec.setupProposal(ctx) - module.EndBlocker(spec.newCtx, s.groupKeeper) + s.Require().NoError(module.EndBlocker(spec.newCtx, s.groupKeeper)) if spec.expErrMsg != "" && spec.expExecutorResult != group.PROPOSAL_EXECUTOR_RESULT_SUCCESS { _, err = s.groupKeeper.Proposal(spec.newCtx, &group.QueryProposalRequest{ProposalId: proposalID}) @@ -373,7 +370,6 @@ func (s *IntegrationTestSuite) TestEndBlockerPruning() { } func (s *IntegrationTestSuite) TestEndBlockerTallying() { - app := s.app ctx := s.ctx addrs := s.addrs @@ -430,7 +426,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { }{ "tally updated after voting period end": { preRun: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposal(s, app, sdkCtx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr) + pID, err := submitProposal(s, sdkCtx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr) s.Require().NoError(err) return pID }, @@ -441,7 +437,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { }, "tally within voting period": { preRun: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposal(s, app, sdkCtx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr) + pID, err := submitProposal(s, sdkCtx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr) s.Require().NoError(err) return pID @@ -453,7 +449,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { }, "tally within voting period(with votes)": { preRun: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposalAndVote(s, app, ctx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) + pID, err := submitProposalAndVote(s, ctx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) s.Require().NoError(err) return pID @@ -466,7 +462,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { "tally after voting period (not passing)": { preRun: func(sdkCtx sdk.Context) uint64 { // `addrs[1]` has weight 1 - pID, err := submitProposalAndVote(s, app, ctx, []sdk.Msg{msgSend}, []string{addrs[1].String()}, groupPolicyAddr, group.VOTE_OPTION_YES) + pID, err := submitProposalAndVote(s, ctx, []sdk.Msg{msgSend}, []string{addrs[1].String()}, groupPolicyAddr, group.VOTE_OPTION_YES) s.Require().NoError(err) return pID @@ -483,7 +479,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { }, "tally after voting period(with votes)": { preRun: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposalAndVote(s, app, ctx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) + pID, err := submitProposalAndVote(s, ctx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) s.Require().NoError(err) return pID @@ -500,7 +496,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { }, "tally of withdrawn proposal": { preRun: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposal(s, app, sdkCtx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr) + pID, err := submitProposal(s, sdkCtx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr) s.Require().NoError(err) _, err = s.groupKeeper.WithdrawProposal(ctx, &group.MsgWithdrawProposal{ @@ -518,7 +514,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { }, "tally of withdrawn proposal (with votes)": { preRun: func(sdkCtx sdk.Context) uint64 { - pID, err := submitProposalAndVote(s, app, ctx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) + pID, err := submitProposalAndVote(s, ctx, []sdk.Msg{msgSend}, proposers, groupPolicyAddr, group.VOTE_OPTION_YES) s.Require().NoError(err) _, err = s.groupKeeper.WithdrawProposal(ctx, &group.MsgWithdrawProposal{ @@ -538,10 +534,9 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { for msg, spec := range specs { s.Run(msg, func() { - spec := spec pID := spec.preRun(ctx) - module.EndBlocker(spec.newCtx, s.groupKeeper) + s.Require().NoError(module.EndBlocker(spec.newCtx, s.groupKeeper)) resp, err := s.groupKeeper.Proposal(spec.newCtx, &group.QueryProposalRequest{ ProposalId: pID, }) @@ -559,7 +554,7 @@ func (s *IntegrationTestSuite) TestEndBlockerTallying() { } } -func submitProposal(s *IntegrationTestSuite, app *runtime.App, ctx context.Context, msgs []sdk.Msg, proposers []string, groupPolicyAddr sdk.AccAddress) (uint64, error) { //nolint:revive // context-as-argument: context.Context should be the first parameter of a function +func submitProposal(s *IntegrationTestSuite, ctx context.Context, msgs []sdk.Msg, proposers []string, groupPolicyAddr sdk.AccAddress) (uint64, error) { proposalReq := &group.MsgSubmitProposal{ GroupPolicyAddress: groupPolicyAddr.String(), Proposers: proposers, @@ -578,10 +573,14 @@ func submitProposal(s *IntegrationTestSuite, app *runtime.App, ctx context.Conte } func submitProposalAndVote( - s *IntegrationTestSuite, app *runtime.App, ctx context.Context, msgs []sdk.Msg, //nolint:revive // context-as-argument: context.Context should be the first parameter of a function - proposers []string, groupPolicyAddr sdk.AccAddress, voteOption group.VoteOption, + s *IntegrationTestSuite, + ctx context.Context, + msgs []sdk.Msg, + proposers []string, + groupPolicyAddr sdk.AccAddress, + voteOption group.VoteOption, ) (uint64, error) { - myProposalID, err := submitProposal(s, app, ctx, msgs, proposers, groupPolicyAddr) + myProposalID, err := submitProposal(s, ctx, msgs, proposers, groupPolicyAddr) if err != nil { return 0, err } diff --git a/x/group/module/module.go b/x/group/module/module.go index ec84e762b3..ff9aeb7deb 100644 --- a/x/group/module/module.go +++ b/x/group/module/module.go @@ -35,7 +35,6 @@ var ( _ module.AppModuleSimulation = AppModule{} _ module.HasGenesis = AppModule{} _ module.HasServices = AppModule{} - _ module.HasInvariants = AppModule{} _ appmodule.AppModule = AppModule{} _ appmodule.HasEndBlocker = AppModule{} @@ -113,9 +112,6 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { group.RegisterLegacyAminoCodec(cdc) } -// RegisterInvariants is a no op and will be removed in the next Cosmos SDK release. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - // InitGenesis performs genesis initialization for the group module. It returns // no validator updates. func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) { diff --git a/x/group/simulation/decoder_test.go b/x/group/simulation/decoder_test.go index 12c9bb3055..298fef4d8c 100644 --- a/x/group/simulation/decoder_test.go +++ b/x/group/simulation/decoder_test.go @@ -70,7 +70,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { if tt.expectErr { require.Panics(t, func() { dec(kvPairs.Pairs[i], kvPairs.Pairs[i]) }, tt.name) diff --git a/x/group/simulation/operations_test.go b/x/group/simulation/operations_test.go index 09377bbce5..1a5f3ce18a 100644 --- a/x/group/simulation/operations_test.go +++ b/x/group/simulation/operations_test.go @@ -130,10 +130,11 @@ func (suite *SimTestSuite) TestSimulateCreateGroup() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 1) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) acc := accounts[0] @@ -156,10 +157,11 @@ func (suite *SimTestSuite) TestSimulateCreateGroupWithPolicy() { r := rand.New(s) accounts := suite.getTestingAccounts(r, 1) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) acc := accounts[0] @@ -197,10 +199,11 @@ func (suite *SimTestSuite) TestSimulateCreateGroupPolicy() { ) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgCreateGroupPolicy(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -247,10 +250,11 @@ func (suite *SimTestSuite) TestSimulateSubmitProposal() { groupPolicyRes, err := suite.groupKeeper.CreateGroupPolicy(ctx, accountReq) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgSubmitProposal(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -310,10 +314,11 @@ func (suite *SimTestSuite) TestWithdrawProposal() { _, err = suite.groupKeeper.SubmitProposal(ctx, proposalReq) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgWithdrawProposal(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -374,10 +379,11 @@ func (suite *SimTestSuite) TestSimulateVote() { _, err = suite.groupKeeper.SubmitProposal(ctx, proposalReq) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgVote(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -446,10 +452,11 @@ func (suite *SimTestSuite) TestSimulateExec() { }) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgExec(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -485,10 +492,11 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupAdmin() { ) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgUpdateGroupAdmin(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -524,10 +532,11 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupMetadata() { ) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgUpdateGroupMetadata(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -563,10 +572,11 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupMembers() { ) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgUpdateGroupMembers(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -613,10 +623,11 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupPolicyAdmin() { groupPolicyRes, err := suite.groupKeeper.CreateGroupPolicy(ctx, accountReq) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgUpdateGroupPolicyAdmin(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -663,10 +674,11 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupPolicyDecisionPolicy() { groupPolicyRes, err := suite.groupKeeper.CreateGroupPolicy(ctx, accountReq) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgUpdateGroupPolicyDecisionPolicy(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -713,10 +725,11 @@ func (suite *SimTestSuite) TestSimulateUpdateGroupPolicyMetadata() { groupPolicyRes, err := suite.groupKeeper.CreateGroupPolicy(ctx, accountReq) suite.Require().NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgUpdateGroupPolicyMetadata(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.groupKeeper) @@ -776,10 +789,11 @@ func (suite *SimTestSuite) TestSimulateLeaveGroup() { _, err = suite.groupKeeper.CreateGroupPolicy(ctx, accountReq) require.NoError(err) - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgLeaveGroup(nil, suite.txConfig, suite.groupKeeper, suite.accountKeeper, suite.bankKeeper) diff --git a/x/nft/internal/conv/doc.go b/x/nft/internal/conv/doc.go index 1c86f5c144..4b45d1ab53 100644 --- a/x/nft/internal/conv/doc.go +++ b/x/nft/internal/conv/doc.go @@ -1,2 +1,2 @@ -// Package conv provides internal functions for convertions and data manipulation +// Package conv provides internal functions for conversions and data manipulation package conv diff --git a/x/nft/internal/conv/string.go b/x/nft/internal/conv/string.go index ab2b7f44b3..fa9e507be0 100644 --- a/x/nft/internal/conv/string.go +++ b/x/nft/internal/conv/string.go @@ -1,20 +1,13 @@ package conv import ( - "reflect" "unsafe" ) // UnsafeStrToBytes uses unsafe to convert string into byte array. Returned bytes // must not be altered after this function is called as it will cause a segmentation fault. func UnsafeStrToBytes(s string) []byte { - var buf []byte - sHdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) - bufHdr := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) - bufHdr.Data = sHdr.Data - bufHdr.Cap = sHdr.Len - bufHdr.Len = sHdr.Len - return buf + return unsafe.Slice(unsafe.StringData(s), len(s)) // ref https://github.com/golang/go/issues/53003#issuecomment-1140276077 } // UnsafeBytesToStr is meant to make a zero allocation conversion @@ -22,5 +15,5 @@ func UnsafeStrToBytes(s string) []byte { // to be used generally, but for a specific pattern to delete keys // from a map. func UnsafeBytesToStr(b []byte) string { - return *(*string)(unsafe.Pointer(&b)) + return unsafe.String(unsafe.SliceData(b), len(b)) } diff --git a/x/nft/keeper/msg_server.go b/x/nft/keeper/msg_server.go index 2f48298714..a33fa7e791 100644 --- a/x/nft/keeper/msg_server.go +++ b/x/nft/keeper/msg_server.go @@ -43,11 +43,11 @@ func (k Keeper) Send(goCtx context.Context, msg *nft.MsgSend) (*nft.MsgSendRespo return nil, err } - ctx.EventManager().EmitTypedEvent(&nft.EventSend{ + err = ctx.EventManager().EmitTypedEvent(&nft.EventSend{ ClassId: msg.ClassId, Id: msg.Id, Sender: msg.Sender, Receiver: msg.Receiver, }) - return &nft.MsgSendResponse{}, nil + return &nft.MsgSendResponse{}, err } diff --git a/x/nft/keeper/nft.go b/x/nft/keeper/nft.go index d99af1322c..f6c206dbb2 100644 --- a/x/nft/keeper/nft.go +++ b/x/nft/keeper/nft.go @@ -54,8 +54,7 @@ func (k Keeper) Burn(ctx context.Context, classID, nftID string) error { return errors.Wrap(nft.ErrNFTNotExists, nftID) } - k.burnWithNoCheck(ctx, classID, nftID) - return nil + return k.burnWithNoCheck(ctx, classID, nftID) } // burnWithNoCheck defines a method for burning a nft from a specific account. @@ -116,8 +115,7 @@ func (k Keeper) Transfer(ctx context.Context, return errors.Wrap(nft.ErrNFTNotExists, nftID) } - k.transferWithNoCheck(ctx, classID, nftID, receiver) - return nil + return k.transferWithNoCheck(ctx, classID, nftID, receiver) } // Transfer defines a method for sending a nft from one account to another account. @@ -213,7 +211,7 @@ func (k Keeper) setNFT(ctx context.Context, token nft.NFT) { func (k Keeper) setOwner(ctx context.Context, classID, nftID string, owner sdk.AccAddress) { store := k.storeService.OpenKVStore(ctx) - store.Set(ownerStoreKey(classID, nftID), owner.Bytes()) + _ = store.Set(ownerStoreKey(classID, nftID), owner.Bytes()) ownerStore := k.getClassStoreByOwner(ctx, owner, classID) ownerStore.Set([]byte(nftID), Placeholder) @@ -221,7 +219,7 @@ func (k Keeper) setOwner(ctx context.Context, classID, nftID string, owner sdk.A func (k Keeper) deleteOwner(ctx context.Context, classID, nftID string, owner sdk.AccAddress) { store := k.storeService.OpenKVStore(ctx) - store.Delete(ownerStoreKey(classID, nftID)) + _ = store.Delete(ownerStoreKey(classID, nftID)) ownerStore := k.getClassStoreByOwner(ctx, owner, classID) ownerStore.Delete([]byte(nftID)) diff --git a/x/nft/keeper/nft_batch_test.go b/x/nft/keeper/nft_batch_test.go index 16731da956..18c92b3f2f 100644 --- a/x/nft/keeper/nft_batch_test.go +++ b/x/nft/keeper/nft_batch_test.go @@ -86,7 +86,7 @@ func (s *TestSuite) TestBatchMint() { func(tokens []nft.NFT) { s.saveClass(tokens) idx := rand.Intn(len(tokens)) - s.nftKeeper.Mint(s.ctx, tokens[idx], receiver) + s.Require().NoError(s.nftKeeper.Mint(s.ctx, tokens[idx], receiver)) }, []nft.NFT{ {ClassId: "classID1", Id: "nftID1"}, @@ -156,7 +156,7 @@ func (s *TestSuite) TestBatchBurn() { "success", func() { s.saveClass(tokens) - s.nftKeeper.BatchMint(s.ctx, tokens, receiver) + s.Require().NoError(s.nftKeeper.BatchMint(s.ctx, tokens, receiver)) }, "classID1", []string{"nftID1", "nftID2"}, @@ -216,7 +216,7 @@ func (s *TestSuite) TestBatchUpdate() { "success", func() { s.saveClass(tokens) - s.nftKeeper.BatchMint(s.ctx, tokens, receiver) + s.Require().NoError(s.nftKeeper.BatchMint(s.ctx, tokens, receiver)) }, []nft.NFT{ {ClassId: "classID1", Id: "nftID1", Uri: "nftID1_URI"}, @@ -286,7 +286,7 @@ func (s *TestSuite) TestBatchTransfer() { "success", func() { s.saveClass(tokens) - s.nftKeeper.BatchMint(s.ctx, tokens, owner) + s.Require().NoError(s.nftKeeper.BatchMint(s.ctx, tokens, owner)) }, "classID1", []string{"nftID1", "nftID2"}, @@ -296,7 +296,7 @@ func (s *TestSuite) TestBatchTransfer() { "failed with not exist classID", func() { s.saveClass(tokens) - s.nftKeeper.BatchMint(s.ctx, tokens, receiver) + s.Require().NoError(s.nftKeeper.BatchMint(s.ctx, tokens, receiver)) }, "classID3", []string{"nftID1", "nftID2"}, diff --git a/x/nft/simulation/decoder_test.go b/x/nft/simulation/decoder_test.go index d3fff88a87..2601d42fef 100644 --- a/x/nft/simulation/decoder_test.go +++ b/x/nft/simulation/decoder_test.go @@ -74,7 +74,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { if tt.expectErr { require.Panics(t, func() { dec(kvPairs.Pairs[i], kvPairs.Pairs[i]) }, tt.name) diff --git a/x/nft/simulation/operations_test.go b/x/nft/simulation/operations_test.go index fad8cf9996..1d67ff0288 100644 --- a/x/nft/simulation/operations_test.go +++ b/x/nft/simulation/operations_test.go @@ -124,10 +124,11 @@ func (suite *SimTestSuite) TestSimulateMsgSend() { ctx := suite.ctx.WithBlockTime(blockTime) // begin new block - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ + _, err := suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{ Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, }) + suite.Require().NoError(err) // execute operation registry := suite.interfaceRegistry @@ -136,7 +137,7 @@ func (suite *SimTestSuite) TestSimulateMsgSend() { suite.Require().NoError(err) var msg nft.MsgSend - suite.codec.UnmarshalJSON(operationMsg.Msg, &msg) + _ = suite.codec.UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().True(operationMsg.OK) suite.Require().Len(futureOperations, 0) } diff --git a/x/params/keeper/keeper_test.go b/x/params/keeper/keeper_test.go index eca29c0462..7c916b86a9 100644 --- a/x/params/keeper/keeper_test.go +++ b/x/params/keeper/keeper_test.go @@ -87,13 +87,11 @@ func TestKeeper(t *testing.T) { // Set params for i, kv := range kvs { - kv := kv require.NotPanics(t, func() { space.Set(ctx, []byte(kv.key), kv.param) }, "space.Set panics, tc #%d", i) } // Test space.Get for i, kv := range kvs { - i, kv := i, kv var param int64 require.NotPanics(t, func() { space.Get(ctx, []byte(kv.key), ¶m) }, "space.Get panics, tc #%d", i) require.Equal(t, kv.param, param, "stored param not equal, tc #%d", i) @@ -120,20 +118,17 @@ func TestKeeper(t *testing.T) { // Test invalid space.Get for i, kv := range kvs { - kv := kv var param bool require.Panics(t, func() { space.Get(ctx, []byte(kv.key), ¶m) }, "invalid space.Get not panics, tc #%d", i) } // Test invalid space.Set for i, kv := range kvs { - kv := kv require.Panics(t, func() { space.Set(ctx, []byte(kv.key), true) }, "invalid space.Set not panics, tc #%d", i) } // Test GetSubspace for i, kv := range kvs { - i, kv := i, kv var gparam, param int64 gspace, ok := keeper.GetSubspace("test") require.True(t, ok, "cannot retrieve subspace, tc #%d", i) @@ -218,7 +213,6 @@ func TestSubspace(t *testing.T) { // Test space.Set, space.Modified for i, kv := range kvs { - i, kv := i, kv require.False(t, space.Modified(ctx, []byte(kv.key)), "space.Modified returns true before setting, tc #%d", i) require.NotPanics(t, func() { space.Set(ctx, []byte(kv.key), kv.param) }, "space.Set panics, tc #%d", i) require.True(t, space.Modified(ctx, []byte(kv.key)), "space.Modified returns false after setting, tc #%d", i) @@ -226,7 +220,6 @@ func TestSubspace(t *testing.T) { // Test space.Get, space.GetIfExists for i, kv := range kvs { - i, kv := i, kv require.NotPanics(t, func() { space.GetIfExists(ctx, []byte("invalid"), kv.ptr) }, "space.GetIfExists panics when no value exists, tc #%d", i) require.Equal(t, kv.zero, indirect(kv.ptr), "space.GetIfExists unmarshalls when no value exists, tc #%d", i) require.Panics(t, func() { space.Get(ctx, []byte("invalid"), kv.ptr) }, "invalid space.Get not panics when no value exists, tc #%d", i) diff --git a/x/params/proposal_handler_test.go b/x/params/proposal_handler_test.go index a693c01fcf..01b300ebd7 100644 --- a/x/params/proposal_handler_test.go +++ b/x/params/proposal_handler_test.go @@ -102,7 +102,6 @@ func (suite *HandlerTestSuite) TestProposalHandler() { } for _, tc := range testCases { - tc := tc suite.Run(tc.name, func() { err := suite.govHandler(suite.ctx, tc.proposal) if tc.expErr { diff --git a/x/params/types/subspace.go b/x/params/types/subspace.go index bc57748010..baa95ff2a5 100644 --- a/x/params/types/subspace.go +++ b/x/params/types/subspace.go @@ -93,7 +93,7 @@ func (s Subspace) Validate(ctx sdk.Context, key []byte, value interface{}) error } if err := attr.vfn(value); err != nil { - return fmt.Errorf("invalid parameter value: %s", err) + return fmt.Errorf("invalid parameter value: %w", err) } return nil diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index a9a1e7ebcc..5f0d24d65a 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -235,7 +235,6 @@ func (suite *SubspaceTestSuite) TestSetParamSet() { } for _, tc := range testCases { - tc := tc suite.Run(tc.name, func() { suite.Require().Panics(func() { suite.ss.SetParamSet(suite.ctx, tc.ps) diff --git a/x/simulation/mock_cometbft.go b/x/simulation/mock_cometbft.go index b0c660ae81..23504bc3b4 100644 --- a/x/simulation/mock_cometbft.go +++ b/x/simulation/mock_cometbft.go @@ -85,6 +85,8 @@ func updateValidators( updates []abci.ValidatorUpdate, event func(route, op, evResult string), ) map[string]mockValidator { + tb.Helper() + for _, update := range updates { str := fmt.Sprintf("%X", update.PubKey.GetEd25519()) diff --git a/x/simulation/operation.go b/x/simulation/operation.go index 5594fd3f58..35a8df0e79 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -79,7 +79,6 @@ func queueOperations(queuedOps OperationQueue, queuedTimeOps, futureOps []simula } for _, futureOp := range futureOps { - futureOp := futureOp if futureOp.BlockHeight != 0 { if val, ok := queuedOps[futureOp.BlockHeight]; ok { queuedOps[futureOp.BlockHeight] = append(val, futureOp.Op) diff --git a/x/simulation/util.go b/x/simulation/util.go index 263a7340b0..e9bc2335df 100644 --- a/x/simulation/util.go +++ b/x/simulation/util.go @@ -15,6 +15,7 @@ import ( ) func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) { + tb.Helper() testingMode = false if _t, ok := tb.(*testing.T); ok { diff --git a/x/slashing/abci_test.go b/x/slashing/abci_test.go index 2bdbd90913..477df081fc 100644 --- a/x/slashing/abci_test.go +++ b/x/slashing/abci_test.go @@ -53,7 +53,8 @@ func TestBeginBlocker(t *testing.T) { // bond the validator power := int64(100) amt := tstaking.CreateValidatorWithValPower(addr, pk, power, true) - stakingKeeper.EndBlocker(ctx) + _, err = stakingKeeper.EndBlocker(ctx) + require.NoError(t, err) bondDenom, err := stakingKeeper.BondDenom(ctx) require.NoError(t, err) require.Equal( diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 700840a77a..58922d0060 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -91,7 +91,8 @@ func TestSlashingMsgs(t *testing.T) { require.NoError(t, err) require.True(t, sdk.Coins{genCoin.Sub(bondCoin)}.Equal(bankKeeper.GetAllBalances(ctxCheck, addr1))) - app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: app.LastBlockHeight() + 1}) + _, err = app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: app.LastBlockHeight() + 1}) + require.NoError(t, err) ctxCheck = baseApp.NewContext(true) validator, err := stakingKeeper.GetValidator(ctxCheck, sdk.ValAddress(addr1)) @@ -110,5 +111,5 @@ func TestSlashingMsgs(t *testing.T) { header = cmtproto.Header{Height: app.LastBlockHeight() + 1} _, _, err = sims.SignCheckDeliver(t, txConfig, app.BaseApp, header, []sdk.Msg{unjailMsg}, "", []uint64{0}, []uint64{1}, false, false, priv1) require.Error(t, err) - require.True(t, errors.Is(types.ErrValidatorNotJailed, err)) + require.True(t, errors.Is(err, types.ErrValidatorNotJailed)) } diff --git a/x/slashing/keeper/genesis.go b/x/slashing/keeper/genesis.go index bb83aabbae..a93a8b059c 100644 --- a/x/slashing/keeper/genesis.go +++ b/x/slashing/keeper/genesis.go @@ -9,24 +9,33 @@ import ( // InitGenesis initializes default parameters and the keeper's address to // pubkey map. func (keeper Keeper) InitGenesis(ctx sdk.Context, stakingKeeper types.StakingKeeper, data *types.GenesisState) { - stakingKeeper.IterateValidators(ctx, + err := stakingKeeper.IterateValidators(ctx, func(index int64, validator stakingtypes.ValidatorI) bool { consPk, err := validator.ConsPubKey() if err != nil { panic(err) } - keeper.AddPubkey(ctx, consPk) + err = keeper.AddPubkey(ctx, consPk) + if err != nil { + panic(err) + } return false }, ) + if err != nil { + panic(err) + } for _, info := range data.SigningInfos { address, err := keeper.sk.ConsensusAddressCodec().StringToBytes(info.Address) if err != nil { panic(err) } - keeper.SetValidatorSigningInfo(ctx, address, info.ValidatorSigningInfo) + err = keeper.SetValidatorSigningInfo(ctx, address, info.ValidatorSigningInfo) + if err != nil { + panic(err) + } } for _, array := range data.MissedBlocks { @@ -57,7 +66,7 @@ func (keeper Keeper) ExportGenesis(ctx sdk.Context) (data *types.GenesisState) { } signingInfos := make([]types.SigningInfo, 0) missedBlocks := make([]types.ValidatorMissedBlocks, 0) - keeper.IterateValidatorSigningInfos(ctx, func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool) { + err = keeper.IterateValidatorSigningInfos(ctx, func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool) { bechAddr := address.String() signingInfos = append(signingInfos, types.SigningInfo{ Address: bechAddr, @@ -76,6 +85,9 @@ func (keeper Keeper) ExportGenesis(ctx sdk.Context) (data *types.GenesisState) { return false }) + if err != nil { + panic(err) + } return types.NewGenesisState(params, signingInfos, missedBlocks) } diff --git a/x/slashing/keeper/genesis_test.go b/x/slashing/keeper/genesis_test.go index 1997837aff..09c8fcbdfd 100644 --- a/x/slashing/keeper/genesis_test.go +++ b/x/slashing/keeper/genesis_test.go @@ -14,18 +14,18 @@ func (s *KeeperTestSuite) TestExportAndInitGenesis() { ctx, keeper := s.ctx, s.slashingKeeper require := s.Require() - keeper.SetParams(ctx, testutil.TestParams()) + s.Require().NoError(keeper.SetParams(ctx, testutil.TestParams())) - consAddr1 := sdk.ConsAddress(sdk.AccAddress([]byte("addr1_______________"))) - consAddr2 := sdk.ConsAddress(sdk.AccAddress([]byte("addr2_______________"))) + consAddr1 := sdk.ConsAddress("addr1_______________") + consAddr2 := sdk.ConsAddress("addr2_______________") info1 := types.NewValidatorSigningInfo(consAddr1, int64(4), int64(3), time.Now().UTC().Add(100000000000), false, int64(10)) info2 := types.NewValidatorSigningInfo(consAddr2, int64(5), int64(4), time.Now().UTC().Add(10000000000), false, int64(10)) - keeper.SetValidatorSigningInfo(ctx, consAddr1, info1) - keeper.SetValidatorSigningInfo(ctx, consAddr2, info2) + require.NoError(keeper.SetValidatorSigningInfo(ctx, consAddr1, info1)) + require.NoError(keeper.SetValidatorSigningInfo(ctx, consAddr2, info2)) genesisState := keeper.ExportGenesis(ctx) require.Equal(genesisState.Params, testutil.TestParams()) diff --git a/x/slashing/keeper/grpc_query_test.go b/x/slashing/keeper/grpc_query_test.go index 8048c85bec..a9b9e20aa3 100644 --- a/x/slashing/keeper/grpc_query_test.go +++ b/x/slashing/keeper/grpc_query_test.go @@ -38,7 +38,7 @@ func (s *KeeperTestSuite) TestGRPCSigningInfo() { int64(0), ) - keeper.SetValidatorSigningInfo(ctx, consAddr, signingInfo) + require.NoError(keeper.SetValidatorSigningInfo(ctx, consAddr, signingInfo)) info, err := keeper.GetValidatorSigningInfo(ctx, consAddr) require.NoError(err) @@ -53,8 +53,8 @@ func (s *KeeperTestSuite) TestGRPCSigningInfos() { require := s.Require() // set two validator signing information - consAddr1 := sdk.ConsAddress(sdk.AccAddress([]byte("addr1_______________"))) - consAddr2 := sdk.ConsAddress(sdk.AccAddress([]byte("addr2_______________"))) + consAddr1 := sdk.ConsAddress("addr1_______________") + consAddr2 := sdk.ConsAddress("addr2_______________") signingInfo := slashingtypes.NewValidatorSigningInfo( consAddr1, 0, @@ -64,16 +64,16 @@ func (s *KeeperTestSuite) TestGRPCSigningInfos() { int64(0), ) - keeper.SetValidatorSigningInfo(ctx, consAddr1, signingInfo) + require.NoError(keeper.SetValidatorSigningInfo(ctx, consAddr1, signingInfo)) signingInfo.Address = string(consAddr2) - keeper.SetValidatorSigningInfo(ctx, consAddr2, signingInfo) + require.NoError(keeper.SetValidatorSigningInfo(ctx, consAddr2, signingInfo)) var signingInfos []slashingtypes.ValidatorSigningInfo - keeper.IterateValidatorSigningInfos(ctx, func(consAddr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { + require.NoError(keeper.IterateValidatorSigningInfos(ctx, func(consAddr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { signingInfos = append(signingInfos, info) return false - }) + })) // verify all values are returned without pagination infoResp, err := queryClient.SigningInfos(gocontext.Background(), diff --git a/x/slashing/keeper/hooks_test.go b/x/slashing/keeper/hooks_test.go index 4d4f729a4c..9e4f2a5218 100644 --- a/x/slashing/keeper/hooks_test.go +++ b/x/slashing/keeper/hooks_test.go @@ -11,7 +11,7 @@ func (s *KeeperTestSuite) TestAfterValidatorBonded() { require := s.Require() valAddr := sdk.ValAddress(consAddr.Bytes()) - keeper.Hooks().AfterValidatorBonded(ctx, consAddr, valAddr) + s.Require().NoError(keeper.Hooks().AfterValidatorBonded(ctx, consAddr, valAddr)) _, err := keeper.GetValidatorSigningInfo(ctx, consAddr) require.NoError(err) diff --git a/x/slashing/keeper/infractions.go b/x/slashing/keeper/infractions.go index 003963069f..553f1c1bdd 100644 --- a/x/slashing/keeper/infractions.go +++ b/x/slashing/keeper/infractions.go @@ -144,7 +144,10 @@ func (k Keeper) HandleValidatorSignature(ctx context.Context, addr cryptotypes.A sdk.NewAttribute(types.AttributeKeyBurnedCoins, coinsBurned.String()), ), ) - k.sk.Jail(sdkCtx, consAddr) + + if err := k.sk.Jail(sdkCtx, consAddr); err != nil { + return fmt.Errorf("failed to jail validator: %w", err) + } downtimeJailDur, err := k.DowntimeJailDuration(ctx) if err != nil { diff --git a/x/slashing/keeper/keeper.go b/x/slashing/keeper/keeper.go index b710e78e3f..8d67747941 100644 --- a/x/slashing/keeper/keeper.go +++ b/x/slashing/keeper/keeper.go @@ -113,7 +113,11 @@ func (k Keeper) SlashWithInfractionReason(ctx context.Context, consAddr sdk.Cons // to make the necessary validator changes. func (k Keeper) Jail(ctx context.Context, consAddr sdk.ConsAddress) error { sdkCtx := sdk.UnwrapSDKContext(ctx) - k.sk.Jail(sdkCtx, consAddr) + + if err := k.sk.Jail(sdkCtx, consAddr); err != nil { + return fmt.Errorf("slashing validator jail: %w", err) + } + sdkCtx.EventManager().EmitEvent( sdk.NewEvent( types.EventTypeSlash, diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index 969fdac6f7..af01a4d802 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -60,7 +60,7 @@ func (s *KeeperTestSuite) SetupTest() { authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) // set test params - s.slashingKeeper.SetParams(ctx, slashingtestutil.TestParams()) + s.Require().NoError(s.slashingKeeper.SetParams(ctx, slashingtestutil.TestParams())) slashingtypes.RegisterInterfaces(encCfg.InterfaceRegistry) queryHelper := baseapp.NewQueryServerTestHelper(ctx, encCfg.InterfaceRegistry) @@ -94,16 +94,16 @@ func (s *KeeperTestSuite) TestJailAndSlash() { stakingtypes.Infraction_INFRACTION_UNSPECIFIED, ).Return(sdkmath.NewInt(0), nil) - s.slashingKeeper.Slash( + s.Require().NoError(s.slashingKeeper.Slash( s.ctx, consAddr, slashFractionDoubleSign, sdk.TokensToConsensusPower(sdkmath.NewInt(1), sdk.DefaultPowerReduction), s.ctx.BlockHeight(), - ) + )) s.stakingKeeper.EXPECT().Jail(s.ctx, consAddr).Return(nil) - s.slashingKeeper.Jail(s.ctx, consAddr) + s.Require().NoError(s.slashingKeeper.Jail(s.ctx, consAddr)) } func (s *KeeperTestSuite) TestJailAndSlashWithInfractionReason() { @@ -118,17 +118,17 @@ func (s *KeeperTestSuite) TestJailAndSlashWithInfractionReason() { stakingtypes.Infraction_INFRACTION_DOUBLE_SIGN, ).Return(sdkmath.NewInt(0), nil) - s.slashingKeeper.SlashWithInfractionReason( + s.Require().NoError(s.slashingKeeper.SlashWithInfractionReason( s.ctx, consAddr, slashFractionDoubleSign, sdk.TokensToConsensusPower(sdkmath.NewInt(1), sdk.DefaultPowerReduction), s.ctx.BlockHeight(), stakingtypes.Infraction_INFRACTION_DOUBLE_SIGN, - ) + )) s.stakingKeeper.EXPECT().Jail(s.ctx, consAddr).Return(nil) - s.slashingKeeper.Jail(s.ctx, consAddr) + s.Require().NoError(s.slashingKeeper.Jail(s.ctx, consAddr)) } func TestKeeperTestSuite(t *testing.T) { diff --git a/x/slashing/keeper/msg_server_test.go b/x/slashing/keeper/msg_server_test.go index b9a2181329..fd49a2edc4 100644 --- a/x/slashing/keeper/msg_server_test.go +++ b/x/slashing/keeper/msg_server_test.go @@ -210,7 +210,7 @@ func (s *KeeperTestSuite) TestUnjail() { info := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addr), int64(4), int64(3), time.Unix(2, 0), false, int64(10)) - s.slashingKeeper.SetValidatorSigningInfo(s.ctx, sdk.ConsAddress(addr), info) + s.Require().NoError(s.slashingKeeper.SetValidatorSigningInfo(s.ctx, sdk.ConsAddress(addr), info)) s.stakingKeeper.EXPECT().Validator(s.ctx, valAddr).Return(val, nil) del := types.NewDelegation(addr.String(), valAddr.String(), sdkmath.LegacyNewDec(100)) @@ -240,7 +240,7 @@ func (s *KeeperTestSuite) TestUnjail() { info := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addr), int64(4), int64(3), time.Unix(2, 0), true, int64(10)) - s.slashingKeeper.SetValidatorSigningInfo(s.ctx, sdk.ConsAddress(addr), info) + s.Require().NoError(s.slashingKeeper.SetValidatorSigningInfo(s.ctx, sdk.ConsAddress(addr), info)) s.stakingKeeper.EXPECT().Validator(s.ctx, valAddr).Return(val, nil) del := types.NewDelegation(addr.String(), valAddr.String(), sdkmath.LegacyNewDec(100)) @@ -270,7 +270,7 @@ func (s *KeeperTestSuite) TestUnjail() { info := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addr), int64(4), int64(3), s.ctx.BlockTime().AddDate(0, 0, 1), false, int64(10)) - s.slashingKeeper.SetValidatorSigningInfo(s.ctx, sdk.ConsAddress(addr), info) + s.Require().NoError(s.slashingKeeper.SetValidatorSigningInfo(s.ctx, sdk.ConsAddress(addr), info)) s.stakingKeeper.EXPECT().Validator(s.ctx, valAddr).Return(val, nil) del := types.NewDelegation(addr.String(), valAddr.String(), sdkmath.LegacyNewDec(10000)) @@ -300,7 +300,7 @@ func (s *KeeperTestSuite) TestUnjail() { info := slashingtypes.NewValidatorSigningInfo(sdk.ConsAddress(addr), int64(4), int64(3), time.Unix(2, 0), false, int64(10)) - s.slashingKeeper.SetValidatorSigningInfo(s.ctx, sdk.ConsAddress(addr), info) + s.Require().NoError(s.slashingKeeper.SetValidatorSigningInfo(s.ctx, sdk.ConsAddress(addr), info)) s.stakingKeeper.EXPECT().Validator(s.ctx, valAddr).Return(val, nil) del := types.NewDelegation(addr.String(), valAddr.String(), sdkmath.LegacyNewDec(100)) diff --git a/x/slashing/keeper/signing_info.go b/x/slashing/keeper/signing_info.go index 97e85f4cab..f4e1fe94f3 100644 --- a/x/slashing/keeper/signing_info.go +++ b/x/slashing/keeper/signing_info.go @@ -193,8 +193,7 @@ func (k Keeper) SetMissedBlockBitmapValue(ctx context.Context, addr sdk.ConsAddr return errors.Wrapf(err, "failed to encode bitmap chunk; index: %d", index) } - k.setMissedBlockBitmapChunk(ctx, addr, chunkIndex, updatedChunk) - return nil + return k.setMissedBlockBitmapChunk(ctx, addr, chunkIndex, updatedChunk) } // DeleteMissedBlockBitmap removes a validator's missed block bitmap from state. diff --git a/x/slashing/keeper/signing_info_test.go b/x/slashing/keeper/signing_info_test.go index e6e0af449f..a5795013a7 100644 --- a/x/slashing/keeper/signing_info_test.go +++ b/x/slashing/keeper/signing_info_test.go @@ -22,7 +22,7 @@ func (s *KeeperTestSuite) TestValidatorSigningInfo() { ) // set the validator signing information - keeper.SetValidatorSigningInfo(ctx, consAddr, signingInfo) + require.NoError(keeper.SetValidatorSigningInfo(ctx, consAddr, signingInfo)) require.True(keeper.HasValidatorSigningInfo(ctx, consAddr)) info, err := keeper.GetValidatorSigningInfo(ctx, consAddr) @@ -34,10 +34,10 @@ func (s *KeeperTestSuite) TestValidatorSigningInfo() { var signingInfos []slashingtypes.ValidatorSigningInfo - keeper.IterateValidatorSigningInfos(ctx, func(consAddr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { + require.NoError(keeper.IterateValidatorSigningInfos(ctx, func(consAddr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { signingInfos = append(signingInfos, info) return false - }) + })) require.Equal(signingInfos[0].Address, signingInfo.Address) @@ -48,7 +48,7 @@ func (s *KeeperTestSuite) TestValidatorSigningInfo() { // test JailUntil jailTime := time.Now().Add(time.Hour).UTC() - keeper.JailUntil(ctx, consAddr, jailTime) + require.NoError(keeper.JailUntil(ctx, consAddr, jailTime)) sInfo, _ := keeper.GetValidatorSigningInfo(ctx, consAddr) require.Equal(sInfo.JailedUntil, jailTime) } diff --git a/x/slashing/keeper/slash_redelegation_test.go b/x/slashing/keeper/slash_redelegation_test.go index 7ebbeb1da7..f5ec2cb282 100644 --- a/x/slashing/keeper/slash_redelegation_test.go +++ b/x/slashing/keeper/slash_redelegation_test.go @@ -55,8 +55,8 @@ func TestSlashRedelegation(t *testing.T) { // fund acc 1 and acc 2 testCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, stakingKeeper.TokensFromConsensusPower(ctx, 10))) - banktestutil.FundAccount(ctx, bankKeeper, testAcc1, testCoins) - banktestutil.FundAccount(ctx, bankKeeper, testAcc2, testCoins) + require.NoError(t, banktestutil.FundAccount(ctx, bankKeeper, testAcc1, testCoins)) + require.NoError(t, banktestutil.FundAccount(ctx, bankKeeper, testAcc2, testCoins)) balance1Before := bankKeeper.GetBalance(ctx, testAcc1, bondDenom) balance2Before := bankKeeper.GetBalance(ctx, testAcc2, bondDenom) @@ -67,7 +67,7 @@ func TestSlashRedelegation(t *testing.T) { // creating evil val evilValAddr := sdk.ValAddress(evilValPubKey.Address()) - banktestutil.FundAccount(ctx, bankKeeper, sdk.AccAddress(evilValAddr), testCoins) + require.NoError(t, banktestutil.FundAccount(ctx, bankKeeper, sdk.AccAddress(evilValAddr), testCoins)) createValMsg1, _ := stakingtypes.NewMsgCreateValidator( evilValAddr.String(), evilValPubKey, testCoins[0], stakingtypes.Description{Details: "test"}, stakingtypes.NewCommissionRates(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)), math.OneInt()) _, err = stakingMsgServer.CreateValidator(ctx, createValMsg1) @@ -75,7 +75,7 @@ func TestSlashRedelegation(t *testing.T) { // creating good val goodValAddr := sdk.ValAddress(goodValPubKey.Address()) - banktestutil.FundAccount(ctx, bankKeeper, sdk.AccAddress(goodValAddr), testCoins) + require.NoError(t, banktestutil.FundAccount(ctx, bankKeeper, sdk.AccAddress(goodValAddr), testCoins)) createValMsg2, _ := stakingtypes.NewMsgCreateValidator( goodValAddr.String(), goodValPubKey, testCoins[0], stakingtypes.Description{Details: "test"}, stakingtypes.NewCommissionRates(math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDecWithPrec(5, 1), math.LegacyNewDec(0)), math.OneInt()) _, err = stakingMsgServer.CreateValidator(ctx, createValMsg2) diff --git a/x/slashing/migrations/v2/store_test.go b/x/slashing/migrations/v2/store_test.go index 4b8794c42d..cdba954d02 100644 --- a/x/slashing/migrations/v2/store_test.go +++ b/x/slashing/migrations/v2/store_test.go @@ -62,7 +62,6 @@ func TestStoreMigration(t *testing.T) { // Make sure the new keys are set and old keys are deleted. for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { if !bytes.Equal(tc.oldKey, tc.newKey) { v, err := store.Get(tc.oldKey) diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index c63dcbbd23..877261655f 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -52,7 +52,6 @@ func TestDecodeStore(t *testing.T) { {"other", "", true}, } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { if tt.panics { require.Panics(t, func() { dec(kvPairs.Pairs[i], kvPairs.Pairs[i]) }, tt.name) diff --git a/x/slashing/simulation/operations_test.go b/x/slashing/simulation/operations_test.go index e55e207ae0..8e24baff4d 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -160,15 +160,15 @@ func (suite *SimTestSuite) TestSimulateMsgUnjail() { suite.Require().NoError(err) // setup validator0 by consensus address - suite.stakingKeeper.SetValidatorByConsAddr(ctx, validator0) + suite.Require().NoError(suite.stakingKeeper.SetValidatorByConsAddr(ctx, validator0)) val0ConsAddress, err := validator0.GetConsAddr() suite.Require().NoError(err) info := types.NewValidatorSigningInfo(val0ConsAddress, int64(4), int64(3), time.Unix(2, 0), false, int64(10)) - suite.slashingKeeper.SetValidatorSigningInfo(ctx, val0ConsAddress, info) + suite.Require().NoError(suite.slashingKeeper.SetValidatorSigningInfo(ctx, val0ConsAddress, info)) // put validator0 in jail - suite.stakingKeeper.Jail(ctx, val0ConsAddress) + suite.Require().NoError(suite.stakingKeeper.Jail(ctx, val0ConsAddress)) // setup self delegation delTokens := suite.stakingKeeper.TokensFromConsensusPower(ctx, 2) @@ -181,7 +181,8 @@ func (suite *SimTestSuite) TestSimulateMsgUnjail() { suite.Require().NoError(suite.distrKeeper.SetDelegatorStartingInfo(ctx, val0AccAddress, val0AccAddress.Bytes(), distrtypes.NewDelegatorStartingInfo(2, math.LegacyOneDec(), 200))) // begin a new block - suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, Time: blockTime}) + _, err = suite.app.FinalizeBlock(&abci.RequestFinalizeBlock{Height: suite.app.LastBlockHeight() + 1, Hash: suite.app.LastCommitID().Hash, Time: blockTime}) + suite.Require().NoError(err) // execute operation op := simulation.SimulateMsgUnjail(codec.NewProtoCodec(suite.interfaceRegistry), suite.txConfig, suite.accountKeeper, suite.bankKeeper, suite.slashingKeeper, suite.stakingKeeper) @@ -218,7 +219,10 @@ func getTestingValidator(ctx sdk.Context, stakingKeeper *stakingkeeper.Keeper, a validator.DelegatorShares = math.LegacyNewDec(100) validator.Tokens = math.NewInt(1000000) - stakingKeeper.SetValidator(ctx, validator) + err = stakingKeeper.SetValidator(ctx, validator) + if err != nil { + return stakingtypes.Validator{}, fmt.Errorf("failed to set validator: %w", err) + } return validator, nil } diff --git a/x/staking/bench_test.go b/x/staking/bench_test.go index 6f8461f11c..3d61ee4922 100644 --- a/x/staking/bench_test.go +++ b/x/staking/bench_test.go @@ -25,6 +25,7 @@ func BenchmarkValidateGenesis400Validators(b *testing.B) { } func benchmarkValidateGenesis(b *testing.B, n int) { + b.Helper() b.ReportAllocs() validators := make([]types.Validator, 0, n) diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 86ab1a8158..ce4b57c6fa 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -142,7 +142,7 @@ func NewEditValidatorCmd(ac address.Codec) *cobra.Command { if commissionRate != "" { rate, err := math.LegacyNewDecFromStr(commissionRate) if err != nil { - return fmt.Errorf("invalid new commission rate: %v", err) + return fmt.Errorf("invalid new commission rate: %w", err) } newRate = &rate diff --git a/x/staking/client/cli/tx_test.go b/x/staking/client/cli/tx_test.go index 2afef34a80..9fe6811321 100644 --- a/x/staking/client/cli/tx_test.go +++ b/x/staking/client/cli/tx_test.go @@ -474,8 +474,6 @@ func (s *CLITestSuite) TestNewDelegateCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) if tc.expectErrMsg != "" { @@ -556,8 +554,6 @@ func (s *CLITestSuite) TestNewRedelegateCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) if tc.expectErrMsg != "" { @@ -619,8 +615,6 @@ func (s *CLITestSuite) TestNewUnbondCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) if tc.expectErrMsg != "" { @@ -698,8 +692,6 @@ func (s *CLITestSuite) TestNewCancelUnbondingDelegationCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { out, err := clitestutil.ExecTestCLICmd(s.clientCtx, cmd, tc.args) if tc.expectErrMsg != "" { diff --git a/x/staking/genesis_test.go b/x/staking/genesis_test.go index 93419809d8..7ba628d922 100644 --- a/x/staking/genesis_test.go +++ b/x/staking/genesis_test.go @@ -44,8 +44,6 @@ func TestValidateGenesis(t *testing.T) { } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { genesisState := types.DefaultGenesisState() tt.mutate(genesisState) diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 662d72b815..cead709668 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -634,7 +634,7 @@ func (k Keeper) HasReceivingRedelegation(ctx context.Context, delAddr sdk.AccAdd func (k Keeper) HasMaxRedelegationEntries(ctx context.Context, delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress) (bool, error) { red, err := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr) if err != nil { - if err == types.ErrNoRedelegation { + if errors.Is(err, types.ErrNoRedelegation) { return false, nil } @@ -1072,12 +1072,12 @@ func (k Keeper) getBeginInfo( ) (completionTime time.Time, height int64, completeNow bool, err error) { validator, err := k.GetValidator(ctx, valSrcAddr) if err != nil && errors.Is(err, types.ErrNoValidatorFound) { - return + return time.Time{}, 0, false, err } sdkCtx := sdk.UnwrapSDKContext(ctx) unbondingTime, err := k.UnbondingTime(ctx) if err != nil { - return + return time.Time{}, 0, false, err } // TODO: When would the validator not be found? diff --git a/x/staking/keeper/genesis.go b/x/staking/keeper/genesis.go index 738614ab86..3f476986e4 100644 --- a/x/staking/keeper/genesis.go +++ b/x/staking/keeper/genesis.go @@ -85,7 +85,7 @@ func (k Keeper) InitGenesis(ctx context.Context, data *types.GenesisState) (res for _, delegation := range data.Delegations { delegatorAddress, err := k.authKeeper.AddressCodec().StringToBytes(delegation.DelegatorAddress) if err != nil { - panic(fmt.Errorf("invalid delegator address: %s", err)) + panic(fmt.Errorf("invalid delegator address: %w", err)) } valAddr, err := k.validatorAddressCodec.StringToBytes(delegation.GetValidatorAddr()) diff --git a/x/staking/keeper/historical_info_test.go b/x/staking/keeper/historical_info_test.go index b1ce611919..cb3b932bea 100644 --- a/x/staking/keeper/historical_info_test.go +++ b/x/staking/keeper/historical_info_test.go @@ -151,7 +151,7 @@ func (s *KeeperTestSuite) TestGetAllHistoricalInfo() { expHistInfos := []stakingtypes.HistoricalInfo{hist1, hist2, hist3} for i, hi := range expHistInfos { - require.NoError(keeper.SetHistoricalInfo(ctx, int64(9+i), &hi)) //nolint:gosec // G601: Implicit memory aliasing in for loop. + require.NoError(keeper.SetHistoricalInfo(ctx, int64(9+i), &hi)) } infos, err := keeper.GetAllHistoricalInfo(ctx) diff --git a/x/staking/keeper/query_utils.go b/x/staking/keeper/query_utils.go index 4b089da780..a55cd2769b 100644 --- a/x/staking/keeper/query_utils.go +++ b/x/staking/keeper/query_utils.go @@ -80,7 +80,7 @@ func (k Keeper) GetAllDelegatorDelegations(ctx context.Context, delegator sdk.Ac return nil, err } delegations = append(delegations, delegation) - i++ + _ = i } return delegations, nil @@ -105,7 +105,7 @@ func (k Keeper) GetAllUnbondingDelegations(ctx context.Context, delegator sdk.Ac return nil, err } unbondingDelegations = append(unbondingDelegations, unbondingDelegation) - i++ + _ = i } return unbondingDelegations, nil @@ -127,8 +127,7 @@ func (k Keeper) GetAllRedelegations( srcValFilter := !(srcValAddress.Empty()) dstValFilter := !(dstValAddress.Empty()) - redelegations := []types.Redelegation{} - + var redelegations []types.Redelegation for ; iterator.Valid(); iterator.Next() { redelegation := types.MustUnmarshalRED(k.cdc, iterator.Value()) valSrcAddr, err := k.validatorAddressCodec.StringToBytes(redelegation.ValidatorSrcAddress) diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index 444633983c..48c88e9785 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -173,13 +173,13 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx context.Context) (updates case validator.IsUnbonded(): validator, err = k.unbondedToBonded(ctx, validator) if err != nil { - return + return nil, err } amtFromNotBondedToBonded = amtFromNotBondedToBonded.Add(validator.GetTokens()) case validator.IsUnbonding(): validator, err = k.unbondingToBonded(ctx, validator) if err != nil { - return + return nil, err } amtFromNotBondedToBonded = amtFromNotBondedToBonded.Add(validator.GetTokens()) case validator.IsBonded(): diff --git a/x/staking/migrations/v2/store_test.go b/x/staking/migrations/v2/store_test.go index 6bd1955159..9b9c79ec41 100644 --- a/x/staking/migrations/v2/store_test.go +++ b/x/staking/migrations/v2/store_test.go @@ -130,7 +130,6 @@ func TestStoreMigration(t *testing.T) { // Make sure the new keys are set and old keys are deleted. for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { if !bytes.Equal(tc.oldKey, tc.newKey) { require.Nil(t, store.Get(tc.oldKey)) diff --git a/x/staking/migrations/v4/migrations_test.go b/x/staking/migrations/v4/migrations_test.go index 90fa7f1ec9..8f762cdf4c 100644 --- a/x/staking/migrations/v4/migrations_test.go +++ b/x/staking/migrations/v4/migrations_test.go @@ -99,6 +99,8 @@ func TestMigrate(t *testing.T) { // createOldStateUnbonding will create the ubd entries with duplicate heights // 10 duplicate heights and 10 unique ubd with creation height func createOldStateUnbonding(t *testing.T, creationHeight int64, valAddr sdk.ValAddress, accAddr sdk.AccAddress, cdc codec.BinaryCodec, store storetypes.KVStore) error { + t.Helper() + unbondBalance := math.NewInt(100) completionTime := time.Now() ubdEntries := make([]types.UnbondingDelegationEntry, 0, 10) @@ -131,6 +133,8 @@ func createOldStateUnbonding(t *testing.T, creationHeight int64, valAddr sdk.Val } func getUBD(t *testing.T, accAddr sdk.AccAddress, valAddr sdk.ValAddress, store storetypes.KVStore, cdc codec.BinaryCodec) types.UnbondingDelegation { + t.Helper() + // get the unbonding delegations var ubdRes types.UnbondingDelegation ubdbz := store.Get(getUBDKey(accAddr, valAddr)) diff --git a/x/staking/migrations/v5/store.go b/x/staking/migrations/v5/store.go index 569cc80c64..a572d35d8f 100644 --- a/x/staking/migrations/v5/store.go +++ b/x/staking/migrations/v5/store.go @@ -52,7 +52,7 @@ func migrateHistoricalInfoKeys(store storetypes.KVStore, logger log.Logger) erro intHeight, err := strconv.ParseInt(string(strHeight), 10, 64) if err != nil { - return fmt.Errorf("can't parse height from key %q to int64: %v", strHeight, err) + return fmt.Errorf("can't parse height from key %q to int64: %w", strHeight, err) } newStoreKey := GetHistoricalInfoKey(intHeight) diff --git a/x/staking/module.go b/x/staking/module.go index 5bbbc5b851..206fd867da 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -41,7 +41,6 @@ var ( _ module.AppModuleBasic = AppModuleBasic{} _ module.AppModuleSimulation = AppModule{} _ module.HasServices = AppModule{} - _ module.HasInvariants = AppModule{} _ module.HasABCIGenesis = AppModule{} _ module.HasABCIEndBlock = AppModule{} @@ -133,9 +132,6 @@ func (am AppModule) IsOnePerModuleType() {} // IsAppModule implements the appmodule.AppModule interface. func (am AppModule) IsAppModule() {} -// RegisterInvariants is deprecated and will be removed in the next version of the Cosmos SDK. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) @@ -284,7 +280,7 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // ProposalMsgs returns msgs used for governance proposals for simulations. -func (AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg { +func (AppModule) ProposalMsgs(_ module.SimulationState) []simtypes.WeightedProposalMsg { return simulation.ProposalMsgs() } diff --git a/x/staking/simulation/decoder_test.go b/x/staking/simulation/decoder_test.go index 589d396e68..d0dbe31c3f 100644 --- a/x/staking/simulation/decoder_test.go +++ b/x/staking/simulation/decoder_test.go @@ -60,7 +60,6 @@ func TestDecodeStore(t *testing.T) { {"other", ""}, } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/staking/simulation/operations_test.go b/x/staking/simulation/operations_test.go index f850603197..9d1960a151 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -396,12 +396,14 @@ func (s *SimTestSuite) getTestingValidator(ctx sdk.Context, commission types.Com } func (s *SimTestSuite) setupValidatorRewards(ctx sdk.Context, valAddress sdk.ValAddress) { + s.T().Helper() + decCoins := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, math.LegacyOneDec())} historicalRewards := distrtypes.NewValidatorHistoricalRewards(decCoins, 2) - s.distrKeeper.SetValidatorHistoricalRewards(ctx, valAddress, 2, historicalRewards) + s.Require().NoError(s.distrKeeper.SetValidatorHistoricalRewards(ctx, valAddress, 2, historicalRewards)) // setup current revards currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3) - s.distrKeeper.SetValidatorCurrentRewards(ctx, valAddress, currentRewards) + s.Require().NoError(s.distrKeeper.SetValidatorCurrentRewards(ctx, valAddress, currentRewards)) } func TestSimTestSuite(t *testing.T) { diff --git a/x/staking/testutil/helpers.go b/x/staking/testutil/helpers.go index 515eb36e09..83b85f847c 100644 --- a/x/staking/testutil/helpers.go +++ b/x/staking/testutil/helpers.go @@ -30,6 +30,8 @@ type Helper struct { // NewHelper creates a new instance of Helper. func NewHelper(t *testing.T, ctx sdk.Context, k *keeper.Keeper) *Helper { + t.Helper() + return &Helper{t, keeper.NewMsgServerImpl(k), k, ctx, ZeroCommission(), sdk.DefaultBondDenom} } diff --git a/x/staking/types/historical_info_test.go b/x/staking/types/historical_info_test.go index 064ea4d521..188eadde71 100644 --- a/x/staking/types/historical_info_test.go +++ b/x/staking/types/historical_info_test.go @@ -21,6 +21,8 @@ var header = cmtproto.Header{ } func createValidators(t *testing.T) []types.Validator { + t.Helper() + return []types.Validator{ newValidator(t, valAddr1, pk1), newValidator(t, valAddr2, pk2), diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index 598aa332b3..3cc55825a1 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -61,7 +61,6 @@ var ( // UnbondingType defines the type of unbonding operation type UnbondingType int -//nolint:revive // we want these underscores, they make life easier const ( UnbondingType_Undefined UnbondingType = iota UnbondingType_UnbondingDelegation diff --git a/x/tx/decode/unknown_test.go b/x/tx/decode/unknown_test.go index dddabbb402..7d901a5a29 100644 --- a/x/tx/decode/unknown_test.go +++ b/x/tx/decode/unknown_test.go @@ -233,7 +233,6 @@ func TestRejectUnknownFieldsRepeated(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { protoBlob, err := proto.Marshal(tt.in) if err != nil { @@ -294,7 +293,6 @@ func TestRejectUnknownFields_allowUnknownNonCriticals(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { blob, err := proto.Marshal(tt.in) if err != nil { @@ -491,7 +489,6 @@ func TestRejectUnknownFieldsNested(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { protoBlob, err := proto.Marshal(tt.in) if err != nil { @@ -627,7 +624,6 @@ func TestRejectUnknownFieldsFlat(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { blob, err := proto.Marshal(tt.in) if err != nil { diff --git a/x/tx/signing/aminojson/aminojson_test.go b/x/tx/signing/aminojson/aminojson_test.go index 3ec9de032d..183b66a1d3 100644 --- a/x/tx/signing/aminojson/aminojson_test.go +++ b/x/tx/signing/aminojson/aminojson_test.go @@ -81,6 +81,7 @@ func TestAminoJsonSignMode(t *testing.T) { }) } } + func TestUnorderedTimeoutCompat(t *testing.T) { fee := &txv1beta1.Fee{ Amount: []*basev1beta1.Coin{{Denom: "uatom", Amount: "1000"}}, diff --git a/x/tx/signing/aminojson/options.go b/x/tx/signing/aminojson/options.go index 9a87cd5672..905ec5ed3f 100644 --- a/x/tx/signing/aminojson/options.go +++ b/x/tx/signing/aminojson/options.go @@ -114,7 +114,7 @@ var customTypeExtension = &protoimpl.ExtensionInfo{ } func init() { - protoregistry.GlobalTypes.RegisterExtension(customTypeExtension) + _ = protoregistry.GlobalTypes.RegisterExtension(customTypeExtension) } func (enc Encoder) getFieldEncoder(field protoreflect.FieldDescriptor) FieldEncoder { @@ -128,8 +128,8 @@ func (enc Encoder) getFieldEncoder(field protoreflect.FieldDescriptor) FieldEnco if proto.HasExtension(opts, cosmos_proto.E_Scalar) { scalar := proto.GetExtension(opts, cosmos_proto.E_Scalar).(string) // do not handle encoding of fields tagged only with scalar which are not backed by a - // LegacyDec custom type. This types are handled by the default encoding, as they are - // expected to already be encoded as their human readable string representation + // LegacyDec custom type. These types are handled by the default encoding, as they are + // expected to already be encoded as their human-readable string representation // containing a radix, i.e. "1.2345". // For example: // https://github.com/cosmos/cosmos-sdk/blob/9076487d035e43d39fe54e8498da1ce31b9c845c/x/gov/proto/cosmos/gov/v1/gov.proto#L274 diff --git a/x/upgrade/abci_test.go b/x/upgrade/abci_test.go index fa86829005..9019bd83f0 100644 --- a/x/upgrade/abci_test.go +++ b/x/upgrade/abci_test.go @@ -134,7 +134,7 @@ func TestRequireFutureBlock(t *testing.T) { s := setupTest(t, 10, map[int64]bool{}) err := s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "test", Height: s.ctx.HeaderInfo().Height - 1}) require.Error(t, err) - require.True(t, errors.Is(sdkerrors.ErrInvalidRequest, err), err) + require.True(t, errors.Is(err, sdkerrors.ErrInvalidRequest), err) } func TestDoHeightUpgrade(t *testing.T) { @@ -209,7 +209,7 @@ func TestCantApplySameUpgradeTwice(t *testing.T) { t.Log("Verify an executed upgrade \"test\" can't be rescheduled") err = s.keeper.ScheduleUpgrade(s.ctx, types.Plan{Name: "test", Height: height}) require.Error(t, err) - require.True(t, errors.Is(sdkerrors.ErrInvalidRequest, err), err) + require.True(t, errors.Is(err, sdkerrors.ErrInvalidRequest), err) } func TestNoSpuriousUpgrades(t *testing.T) { @@ -358,11 +358,10 @@ func TestUpgradeWithoutSkip(t *testing.T) { func TestDumpUpgradeInfoToFile(t *testing.T) { s := setupTest(t, 10, map[int64]bool{}) - require := require.New(t) // require no error when the upgrade info file does not exist _, err := s.keeper.ReadUpgradeInfoFromDisk() - require.NoError(err) + require.NoError(t, err) planHeight := s.ctx.HeaderInfo().Height + 1 plan := types.Plan{ @@ -371,20 +370,20 @@ func TestDumpUpgradeInfoToFile(t *testing.T) { } t.Log("verify if upgrade height is dumped to file") err = s.keeper.DumpUpgradeInfoToDisk(planHeight, plan) - require.Nil(err) + require.Nil(t, err) upgradeInfo, err := s.keeper.ReadUpgradeInfoFromDisk() - require.NoError(err) + require.NoError(t, err) t.Log("Verify upgrade height from file matches ") - require.Equal(upgradeInfo.Height, planHeight) - require.Equal(upgradeInfo.Name, plan.Name) + require.Equal(t, upgradeInfo.Height, planHeight) + require.Equal(t, upgradeInfo.Name, plan.Name) // clear the test file upgradeInfoFilePath, err := s.keeper.GetUpgradeInfoPath() - require.Nil(err) + require.Nil(t, err) err = os.Remove(upgradeInfoFilePath) - require.Nil(err) + require.Nil(t, err) } // TODO: add testcase to for `no upgrade handler is present for last applied upgrade`. @@ -415,10 +414,10 @@ func TestBinaryVersion(t *testing.T) { require.NoError(t, err) newCtx := s.ctx.WithHeaderInfo(header.Info{Height: 12}) - s.keeper.ApplyUpgrade(newCtx, types.Plan{ + require.NoError(t, s.keeper.ApplyUpgrade(newCtx, types.Plan{ Name: "test0", Height: 12, - }) + })) return newCtx }, diff --git a/x/upgrade/client/cli/parse_test.go b/x/upgrade/client/cli/parse_test.go index d1869f24c2..d4f9b4bb83 100644 --- a/x/upgrade/client/cli/parse_test.go +++ b/x/upgrade/client/cli/parse_test.go @@ -22,8 +22,8 @@ func TestParsePlan(t *testing.T) { }, } - fs.Set(FlagUpgradeHeight, strconv.FormatInt(proposal.Plan.Height, 10)) - fs.Set(FlagUpgradeInfo, proposal.Plan.Info) + require.NoError(t, fs.Set(FlagUpgradeHeight, strconv.FormatInt(proposal.Plan.Height, 10))) + require.NoError(t, fs.Set(FlagUpgradeInfo, proposal.Plan.Info)) p, err := parsePlan(fs, proposal.Plan.Name) require.NoError(t, err) diff --git a/x/upgrade/client/cli/tx.go b/x/upgrade/client/cli/tx.go index 294538fdc6..d798dd7989 100644 --- a/x/upgrade/client/cli/tx.go +++ b/x/upgrade/client/cli/tx.go @@ -127,7 +127,7 @@ func NewCmdSubmitUpgradeProposal(ac addresscodec.Codec) *cobra.Command { // add common proposal flags flags.AddTxFlagsToCmd(cmd) cli.AddGovPropFlagsToCmd(cmd) - cmd.MarkFlagRequired(cli.FlagTitle) + _ = cmd.MarkFlagRequired(cli.FlagTitle) return cmd } @@ -176,7 +176,7 @@ func NewCmdSubmitCancelUpgradeProposal(ac addresscodec.Codec) *cobra.Command { // add common proposal flags flags.AddTxFlagsToCmd(cmd) cli.AddGovPropFlagsToCmd(cmd) - cmd.MarkFlagRequired(cli.FlagTitle) + _ = cmd.MarkFlagRequired(cli.FlagTitle) return cmd } diff --git a/x/upgrade/internal/conv/string.go b/x/upgrade/internal/conv/string.go index 8cd9e68278..f78334057b 100644 --- a/x/upgrade/internal/conv/string.go +++ b/x/upgrade/internal/conv/string.go @@ -1,18 +1,11 @@ package conv import ( - "reflect" "unsafe" ) // UnsafeStrToBytes uses unsafe to convert string into byte array. Returned bytes // must not be altered after this function is called as it will cause a segmentation fault. func UnsafeStrToBytes(s string) []byte { - var buf []byte - sHdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) - bufHdr := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) - bufHdr.Data = sHdr.Data - bufHdr.Cap = sHdr.Len - bufHdr.Len = sHdr.Len - return buf + return unsafe.Slice(unsafe.StringData(s), len(s)) // ref https://github.com/golang/go/issues/53003#issuecomment-1140276077 } diff --git a/x/upgrade/keeper/grpc_query_test.go b/x/upgrade/keeper/grpc_query_test.go index 3217cce111..276d385fea 100644 --- a/x/upgrade/keeper/grpc_query_test.go +++ b/x/upgrade/keeper/grpc_query_test.go @@ -42,9 +42,9 @@ func (suite *UpgradeTestSuite) SetupTest() { skipUpgradeHeights := make(map[int64]bool) suite.upgradeKeeper = keeper.NewKeeper(skipUpgradeHeights, storeService, suite.encCfg.Codec, suite.T().TempDir(), nil, authtypes.NewModuleAddress(govtypes.ModuleName).String()) - suite.upgradeKeeper.SetModuleVersionMap(suite.ctx, module.VersionMap{ + suite.Require().NoError(suite.upgradeKeeper.SetModuleVersionMap(suite.ctx, module.VersionMap{ "bank": 0, - }) + })) queryHelper := baseapp.NewQueryServerTestHelper(testCtx.Ctx, suite.encCfg.InterfaceRegistry) types.RegisterQueryServer(queryHelper, suite.upgradeKeeper) @@ -74,7 +74,7 @@ func (suite *UpgradeTestSuite) TestQueryCurrentPlan() { "with current upgrade plan", func() { plan := types.Plan{Name: "test-plan", Height: 5} - suite.upgradeKeeper.ScheduleUpgrade(suite.ctx, plan) + suite.Require().NoError(suite.upgradeKeeper.ScheduleUpgrade(suite.ctx, plan)) req = &types.QueryCurrentPlanRequest{} expResponse = types.QueryCurrentPlanResponse{Plan: &plan} @@ -127,13 +127,13 @@ func (suite *UpgradeTestSuite) TestAppliedCurrentPlan() { planName := "test-plan" plan := types.Plan{Name: planName, Height: expHeight} - suite.upgradeKeeper.ScheduleUpgrade(suite.ctx, plan) + suite.Require().NoError(suite.upgradeKeeper.ScheduleUpgrade(suite.ctx, plan)) suite.ctx = suite.ctx.WithHeaderInfo(header.Info{Height: expHeight}) suite.upgradeKeeper.SetUpgradeHandler(planName, func(ctx context.Context, plan types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) - suite.upgradeKeeper.ApplyUpgrade(suite.ctx, plan) + suite.Require().NoError(suite.upgradeKeeper.ApplyUpgrade(suite.ctx, plan)) req = &types.QueryAppliedPlanRequest{Name: planName} }, diff --git a/x/upgrade/keeper/keeper_test.go b/x/upgrade/keeper/keeper_test.go index dbf94fe731..c92e12f0ab 100644 --- a/x/upgrade/keeper/keeper_test.go +++ b/x/upgrade/keeper/keeper_test.go @@ -121,11 +121,11 @@ func (s *KeeperTestSuite) TestScheduleUpgrade() { Height: 123450000, }, setup: func() { - s.upgradeKeeper.ScheduleUpgrade(s.ctx, types.Plan{ + s.Require().NoError(s.upgradeKeeper.ScheduleUpgrade(s.ctx, types.Plan{ Name: "alt-good", Info: "new text here", Height: 543210000, - }) + })) }, expPass: true, }, @@ -158,18 +158,17 @@ func (s *KeeperTestSuite) TestScheduleUpgrade() { s.upgradeKeeper.SetUpgradeHandler("all-good", func(ctx context.Context, plan types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) - s.upgradeKeeper.ApplyUpgrade(s.ctx, types.Plan{ + s.Require().NoError(s.upgradeKeeper.ApplyUpgrade(s.ctx, types.Plan{ Name: "all-good", Info: "some text here", Height: 123450000, - }) + })) }, expPass: false, }, } for _, tc := range cases { - s.Run(tc.name, func() { // reset suite s.SetupTest() @@ -207,7 +206,7 @@ func (s *KeeperTestSuite) TestSetUpgradedClient() { name: "success", height: 10, setup: func() { - s.upgradeKeeper.SetUpgradedClient(s.ctx, 10, cs) + s.Require().NoError(s.upgradeKeeper.SetUpgradedClient(s.ctx, 10, cs)) }, exists: true, }, @@ -274,7 +273,7 @@ func (s *KeeperTestSuite) TestIncrementProtocolVersion() { s.Require().EqualError(err, "ApplyUpgrade should never be called without first checking HasHandler") s.upgradeKeeper.SetUpgradeHandler("dummy", func(_ context.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) { return vm, nil }) - s.upgradeKeeper.ApplyUpgrade(s.ctx, dummyPlan) + s.Require().NoError(s.upgradeKeeper.ApplyUpgrade(s.ctx, dummyPlan)) upgradedProtocolVersion := s.baseApp.AppVersion() s.Require().Equal(oldProtocolVersion+1, upgradedProtocolVersion) @@ -284,7 +283,7 @@ func (s *KeeperTestSuite) TestIncrementProtocolVersion() { // an upgrade. func (s *KeeperTestSuite) TestMigrations() { initialVM := module.VersionMap{"bank": uint64(1)} - s.upgradeKeeper.SetModuleVersionMap(s.ctx, initialVM) + s.Require().NoError(s.upgradeKeeper.SetModuleVersionMap(s.ctx, initialVM)) vmBefore, err := s.upgradeKeeper.GetModuleVersionMap(s.ctx) s.Require().NoError(err) @@ -299,7 +298,7 @@ func (s *KeeperTestSuite) TestMigrations() { Height: 123450000, } - s.upgradeKeeper.ApplyUpgrade(s.ctx, dummyPlan) + s.Require().NoError(s.upgradeKeeper.ApplyUpgrade(s.ctx, dummyPlan)) vm, err := s.upgradeKeeper.GetModuleVersionMap(s.ctx) s.Require().Equal(vmBefore["bank"]+1, vm["bank"]) s.Require().NoError(err) @@ -319,10 +318,10 @@ func (s *KeeperTestSuite) TestLastCompletedUpgrade() { return vm, nil }) - keeper.ApplyUpgrade(s.ctx, types.Plan{ + s.Require().NoError(keeper.ApplyUpgrade(s.ctx, types.Plan{ Name: "test0", Height: 10, - }) + })) s.T().Log("verify valid upgrade name and height") name, height, err = keeper.GetLastCompletedUpgrade(s.ctx) @@ -335,10 +334,10 @@ func (s *KeeperTestSuite) TestLastCompletedUpgrade() { }) newCtx := s.ctx.WithHeaderInfo(header.Info{Height: 15}) - keeper.ApplyUpgrade(newCtx, types.Plan{ + s.Require().NoError(keeper.ApplyUpgrade(newCtx, types.Plan{ Name: "test1", Height: 15, - }) + })) s.T().Log("verify valid upgrade name and height with multiple upgrades") name, height, err = keeper.GetLastCompletedUpgrade(newCtx) @@ -358,10 +357,10 @@ func (s *KeeperTestSuite) TestLastCompletedUpgradeOrdering() { return vm, nil }) - keeper.ApplyUpgrade(s.ctx, types.Plan{ + s.Require().NoError(keeper.ApplyUpgrade(s.ctx, types.Plan{ Name: "test-v0.9", Height: 10, - }) + })) name, height, err := keeper.GetLastCompletedUpgrade(s.ctx) require.Equal("test-v0.9", name) diff --git a/x/upgrade/plan/downloader.go b/x/upgrade/plan/downloader.go index 7bcb153bd5..199cc1b528 100644 --- a/x/upgrade/plan/downloader.go +++ b/x/upgrade/plan/downloader.go @@ -30,7 +30,8 @@ func DownloadUpgrade(dstRoot, url, daemonName string) error { // First try to download it as a single file. If there's no error, it's okay and we're done. if err := getFile(url, target); err != nil { // If it was a checksum error, no need to try as directory. - if _, ok := err.(*getter.ChecksumError); ok { + var checksumError *getter.ChecksumError + if errors.As(err, &checksumError) { return err } // File download didn't work, try it as an archive. diff --git a/x/upgrade/plan/downloader_test.go b/x/upgrade/plan/downloader_test.go index 7768b30c16..16ef29585d 100644 --- a/x/upgrade/plan/downloader_test.go +++ b/x/upgrade/plan/downloader_test.go @@ -109,6 +109,7 @@ func (s *DownloaderTestSuite) saveSrcTestFile(f *TestFile) string { // requireFileExistsAndIsExecutable requires that the given file exists and is executable. func requireFileExistsAndIsExecutable(t *testing.T, path string) { + t.Helper() info, err := os.Stat(path) require.NoError(t, err, "stat error") perm := info.Mode().Perm() @@ -120,6 +121,7 @@ func requireFileExistsAndIsExecutable(t *testing.T, path string) { // requireFileEquals requires that the contents of the file at the given path // is equal to the contents of the given TestFile. func requireFileEquals(t *testing.T, path string, tf *TestFile) { + t.Helper() file, err := os.ReadFile(path) require.NoError(t, err, "reading file") require.Equal(t, string(tf.Contents), string(file), "file contents") @@ -127,6 +129,7 @@ func requireFileEquals(t *testing.T, path string, tf *TestFile) { // makeFileUrl converts the given path to a URL with the correct checksum query parameter. func makeFileURL(t *testing.T, path string) string { + t.Helper() f, err := os.Open(path) require.NoError(t, err, "opening file") defer f.Close() diff --git a/x/upgrade/plan/info.go b/x/upgrade/plan/info.go index 5ad692d3b1..ae3cfe1a24 100644 --- a/x/upgrade/plan/info.go +++ b/x/upgrade/plan/info.go @@ -68,7 +68,7 @@ func ParseInfo(infoStr string, opts ...ParseOption) (*Info, error) { // Now, try to parse it into the expected structure. var planInfo Info if err := json.Unmarshal(conv.UnsafeStrToBytes(infoStr), &planInfo); err != nil { - return nil, fmt.Errorf("could not parse plan info: %v", err) + return nil, fmt.Errorf("could not parse plan info: %w", err) } planInfo.parseConfig = *parseConfig diff --git a/x/upgrade/plan/info_test.go b/x/upgrade/plan/info_test.go index 48432935db..047cd49def 100644 --- a/x/upgrade/plan/info_test.go +++ b/x/upgrade/plan/info_test.go @@ -47,11 +47,13 @@ func (s *InfoTestSuite) TestParseInfo() { } makeInfoStrFuncString := func(val string) func(t *testing.T) string { return func(t *testing.T) string { + t.Helper() return val } } makeInfoStrFuncURL := func(file string) func(t *testing.T) string { return func(t *testing.T) string { + t.Helper() return makeFileURL(t, file) } } diff --git a/x/upgrade/types/proposal_test.go b/x/upgrade/types/proposal_test.go index 0f54bbdeef..6989663a88 100644 --- a/x/upgrade/types/proposal_test.go +++ b/x/upgrade/types/proposal_test.go @@ -50,7 +50,6 @@ func TestContentAccessors(t *testing.T) { types.RegisterLegacyAminoCodec(cdc) for name, tc := range cases { - tc := tc // copy to local variable for scopelint t.Run(name, func(t *testing.T) { assert.Equal(t, tc.title, tc.p.GetTitle()) assert.Equal(t, tc.desc, tc.p.GetDescription()) @@ -73,7 +72,6 @@ func TestContentAccessors(t *testing.T) { assert.Equal(t, "upgrade", unwrap.Prop.ProposalRoute()) assert.Equal(t, tc.str, unwrap.Prop.String()) }) - } } diff --git a/x/upgrade/types/storeloader_test.go b/x/upgrade/types/storeloader_test.go index 461de9383b..6889033511 100644 --- a/x/upgrade/types/storeloader_test.go +++ b/x/upgrade/types/storeloader_test.go @@ -26,6 +26,8 @@ func useUpgradeLoader(height int64, upgrades *storetypes.StoreUpgrades) func(*ba } func initStore(t *testing.T, db dbm.DB, storeKey string, k, v []byte) { + t.Helper() + rs := rootmulti.NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) rs.SetPruning(pruningtypes.NewPruningOptions(pruningtypes.PruningNothing)) key := storetypes.NewKVStoreKey(storeKey) @@ -43,6 +45,7 @@ func initStore(t *testing.T, db dbm.DB, storeKey string, k, v []byte) { } func checkStore(t *testing.T, db dbm.DB, ver int64, storeKey string, k, v []byte) { + t.Helper() rs := rootmulti.NewStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) rs.SetPruning(pruningtypes.NewPruningOptions(pruningtypes.PruningNothing)) key := storetypes.NewKVStoreKey(storeKey) @@ -125,7 +128,8 @@ func TestSetLoader(t *testing.T) { require.Equal(t, int64(1), oldApp.LastBlockHeight()) for i := int64(2); i <= upgradeHeight-1; i++ { - oldApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: i}) + _, err = oldApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: i}) + require.NoError(t, err) _, err := oldApp.Commit() require.NoError(t, err) } @@ -146,7 +150,8 @@ func TestSetLoader(t *testing.T) { require.Equal(t, upgradeHeight-1, newApp.LastBlockHeight()) // "execute" one block - newApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: upgradeHeight}) + _, err = newApp.FinalizeBlock(&abci.RequestFinalizeBlock{Height: upgradeHeight}) + require.NoError(t, err) _, err = newApp.Commit() require.NoError(t, err) require.Equal(t, upgradeHeight, newApp.LastBlockHeight())