Skip to content
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

Suggest use of cmpopts.EquateErrors #234

Merged
merged 1 commit into from Aug 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions cmp/compare_test.go
Expand Up @@ -696,6 +696,19 @@ func comparerTests() []test {
},
wantEqual: true,
reason: "verify that exporter does not leak implementation details",
}, {
label: label + "/ErrorPanic",
x: io.EOF,
y: io.EOF,
wantPanic: "consider using cmpopts.EquateErrors",
reason: "suggest cmpopts.EquateErrors when accessing unexported fields of error types",
}, {
label: label + "/ErrorEqual",
x: io.EOF,
y: io.EOF,
opts: []cmp.Option{cmpopts.EquateErrors()},
wantEqual: true,
reason: "cmpopts.EquateErrors should equate these two errors as sentinel values",
}}
}

Expand Down
5 changes: 4 additions & 1 deletion cmp/options.go
Expand Up @@ -225,11 +225,14 @@ func (validator) apply(s *state, vx, vy reflect.Value) {

// Unable to Interface implies unexported field without visibility access.
if !vx.CanInterface() || !vy.CanInterface() {
const help = "consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported"
help := "consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported"
var name string
if t := s.curPath.Index(-2).Type(); t.Name() != "" {
// Named type with unexported fields.
name = fmt.Sprintf("%q.%v", t.PkgPath(), t.Name()) // e.g., "path/to/package".MyType
if _, ok := reflect.New(t).Interface().(error); ok {
help = "consider using cmpopts.EquateErrors to compare error values"
}
} else {
// Unnamed type with unexported fields. Derive PkgPath from field.
var pkgPath string
Expand Down