-
Notifications
You must be signed in to change notification settings - Fork 1
/
match_len.go
55 lines (47 loc) · 1.43 KB
/
match_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
49
50
51
52
53
54
55
package matchers
import (
"fmt"
"reflect"
"github.com/onsi/gomega/format"
"github.com/onsi/gomega/types"
)
type MatchLenMatcher struct {
Matcher types.GomegaMatcher
}
func (matcher *MatchLenMatcher) Match(actual interface{}) (bool, error) {
length, ok := lengthOf(actual)
if !ok {
return false, fmt.Errorf("MatchLen matcher expects a string/array/map/channel/slice, or type with a Len() int method. Got:\n%s",
format.Object(actual, 1))
}
return matcher.Matcher.Match(length)
}
func (matcher *MatchLenMatcher) FailureMessage(actual interface{}) (message string) {
length, _ := lengthOf(actual)
return fmt.Sprintf("Expected length of\n%s\nto match, but failed with\n%s",
format.Object(actual, 1),
format.IndentString(matcher.Matcher.FailureMessage(length), 1))
}
func (matcher *MatchLenMatcher) NegatedFailureMessage(actual interface{}) (message string) {
length, _ := lengthOf(actual)
return fmt.Sprintf("Expected length of\n%s\nnot to match, but did with\n%s",
format.Object(actual, 1),
format.IndentString(matcher.Matcher.NegatedFailureMessage(length), 1))
}
func lengthOf(a interface{}) (int, bool) {
if a == nil {
return 0, false
}
if lengther, ok := a.(hasLen); ok {
return lengther.Len(), true
}
switch reflect.TypeOf(a).Kind() {
case reflect.Map, reflect.Array, reflect.String, reflect.Chan, reflect.Slice:
return reflect.ValueOf(a).Len(), true
default:
return 0, false
}
}
type hasLen interface {
Len() int
}