Skip to content

Commit

Permalink
assert: better formatting for Len() error
Browse files Browse the repository at this point in the history
Previously, the use of %s with array objects meant you would get an
error like this:

    "[%!s(int=1) %!s(int=2) %!s(int=3)]\" should have 4 item(s), but has 3

Use %v instead, which provides a much nicer error.

    "[1 2 3]" should have 4 item(s), but has 3

Fixes stretchr#1482.
  • Loading branch information
kevinburkesegment committed Oct 12, 2023
1 parent 882382d commit 9a7e703
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
4 changes: 2 additions & 2 deletions assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -751,11 +751,11 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{})
}
l, ok := getLen(object)
if !ok {
return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
return Fail(t, fmt.Sprintf("\"%v\" could not be applied builtin len()", object), msgAndArgs...)
}

if l != length {
return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
return Fail(t, fmt.Sprintf("\"%v\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
}
return true
}
Expand Down
27 changes: 27 additions & 0 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1677,6 +1677,33 @@ func TestLen(t *testing.T) {
for _, c := range cases {
False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
}

formatCases := []struct {
in interface{}
wantLen int
want string
}{
{[]int{1, 2, 3}, 3, "[1 2 3]"},
{[...]int{1, 2, 3}, 3, "[1 2 3]"},
{"ABC", 3, "ABC"},
{map[int]int{1: 2, 2: 4, 3: 6}, 3, "map[1:2 2:4 3:6]"},

{[]int{}, 0, "[]"},
{map[int]int{}, 0, "map[]"},

{[]int(nil), 0, "[]"},
{map[int]int(nil), 0, "map[]"},
{(chan int)(nil), 0, "<nil>"},
}

t.Run("Len() error message formatting", func(t *testing.T) {
for _, tt := range formatCases {
msgMock := new(mockTestingT)
Len(msgMock, tt.in, 1234567)
want := fmt.Sprintf(`"%s" should have 1234567 item(s), but has %d`, tt.want, tt.wantLen)
Contains(t, msgMock.errorString(), want)
}
})
}

func TestWithinDuration(t *testing.T) {
Expand Down

0 comments on commit 9a7e703

Please sign in to comment.