Skip to content

Fix match.As to behave the same as errors.As #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions match/match.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,8 @@ func As(target interface{}) ErrorMatcher {
panic("errors: *target must be interface or implement error")
}

tar := reflect.New(typ).Interface()

return ErrorMatcherFunc(func(err error) bool {
target := tar

return errors.As(err, &target)
return errors.As(err, target)
})
}

Expand Down
42 changes: 42 additions & 0 deletions match/match_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,48 @@ func TestAs(t *testing.T) {
}
}

type errorData struct {
data string
}

func (e errorData) Error() string {
return e.data
}

type wrappingError struct {
error
}

func (w wrappingError) Unwrap() error {
return w.error
}

func TestAs_SetMatchedError(t *testing.T) {
var matchErr errorData

matcher := As(&matchErr)

matchingErr := wrappingError{error: errorData{"target data"}}

if !matcher.MatchError(matchingErr) {
t.Error("As matcher is not supposed to match an error that cannot be assigned from the error chain")
}

if matchErr.data != "target data" {
t.Error("As matcher is supposed to set the matched error to it's value in the chain")
}
}

func TestAs_IncompatibleErrors(t *testing.T) {
var matchErr errorData

matcher := As(&matchErr)

if matcher.MatchError(errors.New("error")) {
t.Error("As matcher is not supposed to match an error that cannot be assigned from the error chain")
}
}

func TestAs_Race(t *testing.T) {
var matchErr interface {
IsError() bool
Expand Down