cosmos-sdk/errors/errors_test.go

262 lines
8.2 KiB
Go
Raw Normal View History

package errors
import (
stdlib "errors"
"fmt"
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/suite"
)
type errorsTestSuite struct {
suite.Suite
}
func TestErrorsTestSuite(t *testing.T) {
suite.Run(t, new(errorsTestSuite))
}
func (s *errorsTestSuite) SetupSuite() {
s.T().Parallel()
}
func (s *errorsTestSuite) TestCause() {
std := stdlib.New("this is a stdlib error")
cases := map[string]struct {
err error
root error
}{
"Errors are self-causing": {
err: ErrUnauthorized,
root: ErrUnauthorized,
},
"Wrap reveals root cause": {
err: Wrap(ErrUnauthorized, "foo"),
root: ErrUnauthorized,
},
"Cause works for stderr as root": {
err: Wrap(std, "Some helpful text"),
root: std,
},
}
for testName, tc := range cases {
s.Require().Equal(tc.root, errors.Cause(tc.err), testName)
}
}
func (s *errorsTestSuite) TestErrorIs() {
cases := map[string]struct {
a *Error
b error
wantIs bool
}{
"instance of the same error": {
a: ErrUnauthorized,
b: ErrUnauthorized,
wantIs: true,
},
"two different coded errors": {
a: ErrUnauthorized,
b: ErrOutOfGas,
wantIs: false,
},
"successful comparison to a wrapped error": {
a: ErrUnauthorized,
b: errors.Wrap(ErrUnauthorized, "gone"),
wantIs: true,
},
"unsuccessful comparison to a wrapped error": {
a: ErrUnauthorized,
b: errors.Wrap(ErrInsufficientFee, "too big"),
wantIs: false,
},
"not equal to stdlib error": {
a: ErrUnauthorized,
b: fmt.Errorf("stdlib error"),
wantIs: false,
},
"not equal to a wrapped stdlib error": {
a: ErrUnauthorized,
b: errors.Wrap(fmt.Errorf("stdlib error"), "wrapped"),
wantIs: false,
},
"nil is nil": {
a: nil,
b: nil,
wantIs: true,
},
"nil is any error nil": {
a: nil,
b: (*customError)(nil),
wantIs: true,
},
"nil is not not-nil": {
a: nil,
b: ErrUnauthorized,
wantIs: false,
},
"not-nil is not nil": {
a: ErrUnauthorized,
b: nil,
wantIs: false,
},
}
for testName, tc := range cases {
s.Require().Equal(tc.wantIs, tc.a.Is(tc.b), testName)
}
}
Remove bech32 PubKey support (#7477) * Move PubKey bech32 to legacy package and migrate the usage where possible * update /server * wip * move proto json encoding helper functions to internal * update internal/marshal * wip * update sections which needs legacybech32 * update validators output * fix conflicts * slashing update * add more tests and helper function for ANY JSON serialization * update slashing * Update function documentation * Rename code any-marshal helper functions * Update pubkey unpacking test * Update test comments * solve TestDecodeStore * solve legacytx issues * all code compiles * keyring tests * keyring cleanup * remove AssertMsg * fix some tests * fix add_ledger_test.go * update cli tests * debug cli test * rename clashed bech32 names * linter fixes * update tmservice tests * linter: update legacy deprecated checks * fix names * linting * legacybech32 pubkey type rename * fix staking client * fix test compilation * fix TestGetCmdQuerySigningInfo * rename NewIfcJSONAnyMarshaler * keyring: remove duplicated information from multinfo structure * todo cleanups * Update Changelog * remove some legacybech32 from tests * remove todos * remove printlnJSON from /server CLI and amino encoding * remove protocdc.MarshalJSON * client/show remove duplicated function * remove protocdc package * comment update * remove legacybech32.MustMarshalPubKey from a test * add todo * fix TestPublicKeyUnsafe test * review update * fix bech32 UnmarshalPubKey * Use codec.MarshalIfcJSON * fix linter issues * merging conflict: fix codec.Unmarshal calls * cleanups * Update CHANGELOG.md Co-authored-by: Aaron Craelius <aaron@regen.network> * Reword changelog updates * use pubkey.String for comparison in Test_runAddCmdLedgerWithCustomCoinType * Update GetCmdQuerySigningInfo example * cli: update keys add docs * Add errors AsOf and errors.ErrIO type * restore multisigPubKeyInfo structure bring it back to multiInfo struct * Update codec/proto_codec.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * Update crypto/keys/ed25519/ed25519_test.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * Update codec/proto_codec.go Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * move pubkey any marshaling tests * Apply suggestions from code review Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com> * review updates * adding missing return * errors: use IsOf instead of AsOf * keyring: add a correct check for key not found in keyring.Get * add checkKeyNotFound * fix linter issues * fix: keyring key not found check * fix keyring tests * fix linting issues * cli tests * fix: 'simd keys show <key> -p' * fix: TestVerifyMultisignature * rename keyring Bech32... functions to Mk... * fix RunAddCmd * Update pubkey display * wip * add more tests * udate keyring output tests * remove todo from ledger tests * rename MkKeyOutput * Changelog update * solve liner issues * add link to github issue Co-authored-by: Aaron Craelius <aaron@regen.network> Co-authored-by: Marie Gauthier <marie.gauthier63@gmail.com>
2021-03-25 07:53:22 -07:00
func (s *errorsTestSuite) TestIsOf() {
require := s.Require()
var errNil *Error
var err = ErrInvalidAddress
var errW = Wrap(ErrLogic, "more info")
require.False(IsOf(errNil), "nil error should always have no causer")
require.False(IsOf(errNil, err), "nil error should always have no causer")
require.False(IsOf(err))
require.False(IsOf(err, nil))
require.False(IsOf(err, ErrLogic))
require.True(IsOf(errW, ErrLogic))
require.True(IsOf(errW, err, ErrLogic))
require.True(IsOf(errW, nil, errW), "error should much itself")
var err2 = errors.New("other error")
require.True(IsOf(err2, nil, err2), "error should much itself")
}
type customError struct {
}
func (customError) Error() string {
return "custom error"
}
func (s *errorsTestSuite) TestWrapEmpty() {
s.Require().Nil(Wrap(nil, "wrapping <nil>"))
}
func (s *errorsTestSuite) TestWrappedIs() {
require := s.Require()
err := Wrap(ErrTxTooLarge, "context")
require.True(stdlib.Is(err, ErrTxTooLarge))
err = Wrap(err, "more context")
require.True(stdlib.Is(err, ErrTxTooLarge))
err = Wrap(err, "even more context")
require.True(stdlib.Is(err, ErrTxTooLarge))
err = Wrap(ErrInsufficientFee, "...")
require.False(stdlib.Is(err, ErrTxTooLarge))
errs := stdlib.New("other")
require.True(stdlib.Is(errs, errs))
errw := &wrappedError{"msg", errs}
require.True(errw.Is(errw), "should match itself")
fix: types/errors Wrap and Wrapf (#10674) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description The `Error.Wrap` and `Error.Wrapf` functions in `types/errors` didn't work with `Is` and `IsOf` because they had non-pointer receivers. This adds a fix and tests that failed and now pass. --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [x] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [x] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-12-05 16:25:42 -08:00
require.True(stdlib.Is(ErrInsufficientFee.Wrap("wrapped"), ErrInsufficientFee))
require.True(IsOf(ErrInsufficientFee.Wrap("wrapped"), ErrInsufficientFee))
require.True(stdlib.Is(ErrInsufficientFee.Wrapf("wrapped"), ErrInsufficientFee))
require.True(IsOf(ErrInsufficientFee.Wrapf("wrapped"), ErrInsufficientFee))
}
func (s *errorsTestSuite) TestWrappedIsMultiple() {
var errTest = errors.New("test error")
var errTest2 = errors.New("test error 2")
err := Wrap(errTest2, Wrap(errTest, "some random description").Error())
s.Require().True(stdlib.Is(err, errTest2))
}
func (s *errorsTestSuite) TestWrappedIsFail() {
var errTest = errors.New("test error")
var errTest2 = errors.New("test error 2")
err := Wrap(errTest2, Wrap(errTest, "some random description").Error())
s.Require().False(stdlib.Is(err, errTest))
}
func (s *errorsTestSuite) TestWrappedUnwrap() {
var errTest = errors.New("test error")
err := Wrap(errTest, "some random description")
s.Require().Equal(errTest, stdlib.Unwrap(err))
}
func (s *errorsTestSuite) TestWrappedUnwrapMultiple() {
var errTest = errors.New("test error")
var errTest2 = errors.New("test error 2")
err := Wrap(errTest2, Wrap(errTest, "some random description").Error())
s.Require().Equal(errTest2, stdlib.Unwrap(err))
}
func (s *errorsTestSuite) TestWrappedUnwrapFail() {
var errTest = errors.New("test error")
var errTest2 = errors.New("test error 2")
err := Wrap(errTest2, Wrap(errTest, "some random description").Error())
s.Require().NotEqual(errTest, stdlib.Unwrap(err))
}
func (s *errorsTestSuite) TestABCIError() {
feat: standalone errors go.mod (#10779) ## Description This PR: * moves all of the `types/errors` code to a new `errors` go module, except: * the `RootCodespace` errors in `types/errors` stay there * ABCI stuff that depends on tendermint stays in `types/errors * adds aliases to everything in `types/errors` referencing `errors` so **this is not a breaking change** This will allow standalone go modules to use the same error types as the SDK. In particular, I want the `orm` to reference `errors` and then the SDK will be able to import `orm` and it can stay standalone. The same could apply to the `db` module. After this PR the plan is to: * tag `github.com/cosmos/cosmos-sdk/errors` as `v1.0` 🎉 * remove the `replace` directive for `errors` in the main SDK `go.mod` --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [x] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-12-17 13:53:08 -08:00
s.Require().Equal("custom: tx parse error", ABCIError(testCodespace, 2, "custom").Error())
s.Require().Equal("custom: unknown", ABCIError("unknown", 1, "custom").Error())
}
func ExampleWrap() {
err1 := Wrap(ErrInsufficientFunds, "90 is smaller than 100")
err2 := errors.Wrap(ErrInsufficientFunds, "90 is smaller than 100")
fmt.Println(err1.Error())
fmt.Println(err2.Error())
// Output:
// 90 is smaller than 100: insufficient funds
// 90 is smaller than 100: insufficient funds
}
func ExampleWrapf() {
err1 := Wrap(ErrInsufficientFunds, "90 is smaller than 100")
err2 := errors.Wrap(ErrInsufficientFunds, "90 is smaller than 100")
fmt.Println(err1.Error())
fmt.Println(err2.Error())
// Output:
// 90 is smaller than 100: insufficient funds
// 90 is smaller than 100: insufficient funds
}
feat: standalone errors go.mod (#10779) ## Description This PR: * moves all of the `types/errors` code to a new `errors` go module, except: * the `RootCodespace` errors in `types/errors` stay there * ABCI stuff that depends on tendermint stays in `types/errors * adds aliases to everything in `types/errors` referencing `errors` so **this is not a breaking change** This will allow standalone go modules to use the same error types as the SDK. In particular, I want the `orm` to reference `errors` and then the SDK will be able to import `orm` and it can stay standalone. The same could apply to the `db` module. After this PR the plan is to: * tag `github.com/cosmos/cosmos-sdk/errors` as `v1.0` 🎉 * remove the `replace` directive for `errors` in the main SDK `go.mod` --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [x] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-12-17 13:53:08 -08:00
const testCodespace = "testtesttest"
var (
ErrTxDecode = Register(testCodespace, 2, "tx parse error")
ErrInvalidSequence = Register(testCodespace, 3, "invalid sequence")
ErrUnauthorized = Register(testCodespace, 4, "unauthorized")
ErrInsufficientFunds = Register(testCodespace, 5, "insufficient funds")
ErrUnknownRequest = Register(testCodespace, 6, "unknown request")
ErrInvalidAddress = Register(testCodespace, 7, "invalid address")
ErrInvalidPubKey = Register(testCodespace, 8, "invalid pubkey")
ErrUnknownAddress = Register(testCodespace, 9, "unknown address")
ErrInvalidCoins = Register(testCodespace, 10, "invalid coins")
ErrOutOfGas = Register(testCodespace, 11, "out of gas")
ErrInsufficientFee = Register(testCodespace, 13, "insufficient fee")
ErrTooManySignatures = Register(testCodespace, 14, "maximum number of signatures exceeded")
ErrNoSignatures = Register(testCodespace, 15, "no signatures supplied")
ErrJSONMarshal = Register(testCodespace, 16, "failed to marshal JSON bytes")
ErrJSONUnmarshal = Register(testCodespace, 17, "failed to unmarshal JSON bytes")
ErrInvalidRequest = Register(testCodespace, 18, "invalid request")
ErrMempoolIsFull = Register(testCodespace, 20, "mempool is full")
ErrTxTooLarge = Register(testCodespace, 21, "tx too large")
ErrKeyNotFound = Register(testCodespace, 22, "key not found")
ErrorInvalidSigner = Register(testCodespace, 24, "tx intended signer does not match the given signer")
ErrInvalidChainID = Register(testCodespace, 28, "invalid chain-id")
ErrInvalidType = Register(testCodespace, 29, "invalid type")
ErrUnknownExtensionOptions = Register(testCodespace, 31, "unknown extension options")
ErrPackAny = Register(testCodespace, 33, "failed packing protobuf message to Any")
ErrLogic = Register(testCodespace, 35, "internal logic error")
ErrConflict = Register(testCodespace, 36, "conflict")
ErrNotSupported = Register(testCodespace, 37, "feature not supported")
ErrNotFound = Register(testCodespace, 38, "not found")
ErrIO = Register(testCodespace, 39, "Internal IO error")
)