Skip to content

Commit

Permalink
Merge pull request #1445 from stretchr/assert-refactor-getLen
Browse files Browse the repository at this point in the history
assert: refactor internal func getLen()
  • Loading branch information
dolmen committed Aug 8, 2023
2 parents a23f5db + 9e58631 commit 0e90845
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
14 changes: 6 additions & 8 deletions assert/assertions.go
Expand Up @@ -731,16 +731,14 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {

}

// getLen try to get length of object.
// return (false, 0) if impossible.
func getLen(x interface{}) (ok bool, length int) {
// getLen tries to get the length of an object.
// It returns (0, false) if impossible.
func getLen(x interface{}) (length int, ok bool) {
v := reflect.ValueOf(x)
defer func() {
if e := recover(); e != nil {
ok = false
}
ok = recover() == nil
}()
return true, v.Len()
return v.Len(), true
}

// Len asserts that the specified object has specific length.
Expand All @@ -751,7 +749,7 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{})
if h, ok := t.(tHelper); ok {
h.Helper()
}
ok, l := getLen(object)
l, ok := getLen(object)
if !ok {
return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
}
Expand Down
4 changes: 2 additions & 2 deletions assert/assertions_test.go
Expand Up @@ -1582,7 +1582,7 @@ func Test_getLen(t *testing.T) {
struct{}{},
}
for _, v := range falseCases {
ok, l := getLen(v)
l, ok := getLen(v)
False(t, ok, "Expected getLen fail to get length of %#v", v)
Equal(t, 0, l, "getLen should return 0 for %#v", v)
}
Expand Down Expand Up @@ -1611,7 +1611,7 @@ func Test_getLen(t *testing.T) {
}

for _, c := range trueCases {
ok, l := getLen(c.v)
l, ok := getLen(c.v)
True(t, ok, "Expected getLen success to get length of %#v", c.v)
Equal(t, c.l, l)
}
Expand Down

0 comments on commit 0e90845

Please sign in to comment.