-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassert_len.go
48 lines (38 loc) · 1 KB
/
assert_len.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package actually
import (
"reflect"
"testing"
)
// Len asserts that the specified object has specific length.
// Len also fails if the object has a type that len() not accept.
func (a *testingA) Len(t *testing.T, testNames ...string) *testingA {
invalidCall(a)
a.name = a.naming(testNames...)
a.t = t
a.t.Helper()
wi := a.wi().Got(a.got).Expect(a.expect)
if k, ok := isValidExpect(a.expect); !ok {
return a.failf(wi, reason_ExpectvalueNotInt, k)
}
gotLen, ok := getLen(a.got)
if !ok {
return a.fail(wi, reason_CouldNotBeAppliedLen)
}
if gotLen != a.expect {
return a.failf(wi, reason_ShouldHaveItems, a.expect, gotLen)
}
return a
}
func isValidExpect(e any) (reflect.Kind, bool) {
k := reflect.ValueOf(e).Kind()
return k, k == reflect.Int || k == reflect.Int32
}
// 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() {
ok = recover() == nil
}()
return v.Len(), true
}