Skip to content

Commit d443404

Browse files
committed
refactor: better multiple-wants Err impl
1 parent 593bf21 commit d443404

1 file changed

Lines changed: 16 additions & 18 deletions

File tree

be.go

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,11 @@ func Equal[T any](tb testing.TB, got T, wants ...T) {
6464
// in the got's error tree using [errors.As].
6565
// - Otherwise fails the check.
6666
//
67-
// If no wants are provided, checks if got is not nil.
67+
// If no wants are given, checks if got is not nil.
6868
func Err(tb testing.TB, got error, wants ...any) {
6969
tb.Helper()
7070

71-
// If no wants are provided, we expect got to be a non-nil error.
71+
// If no wants are given, we expect got to be a non-nil error.
7272
if len(wants) == 0 {
7373
if got != nil {
7474
// got is a non-nil error, nothing to report.
@@ -89,28 +89,26 @@ func Err(tb testing.TB, got error, wants ...any) {
8989
}
9090
}
9191

92-
// Check if got matches the any of the wants.
93-
messages := make([]string, 0, len(wants))
92+
// Check if got matches any of the wants.
93+
var message string
9494
for _, want := range wants {
95-
msg := checkErr(got, want)
96-
if msg != "" {
97-
messages = append(messages, msg)
95+
errMsg := checkErr(got, want)
96+
if errMsg == "" {
97+
return
98+
}
99+
if message == "" {
100+
message = errMsg
98101
}
99102
}
100103

101-
// Report the results.
102-
if len(messages) < len(wants) {
103-
// Some of the checks passed, nothing to report.
104+
// There are no matches, report the failure.
105+
if len(wants) == 1 {
106+
// There is only one want, report it directly.
107+
tb.Error(message)
104108
return
105109
}
106-
107-
if len(messages) == 1 {
108-
// Only one check failed, report it directly.
109-
tb.Error(messages[0])
110-
} else {
111-
// All checks failed, report a summary.
112-
tb.Errorf("want any of the %v, got %T(%v)", wants, got, got)
113-
}
110+
// There are multiple wants, report a summary.
111+
tb.Errorf("want any of the %v, got %T(%v)", wants, got, got)
114112
}
115113

116114
// True asserts that got is true.

0 commit comments

Comments
 (0)