-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhasmethod.go
96 lines (79 loc) · 2.39 KB
/
hasmethod.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package hamcrest
import (
"fmt"
"reflect"
"strings"
)
type HasMethodMatcher struct {
MethodName string
MethodResultMatchers []Matcher
}
func (me *HasMethodMatcher) Match(input interface{}) MatchResult {
result := &KeyValueResult{}
inVal := reflect.ValueOf(input)
meth := inVal.MethodByName(me.MethodName)
kResult := &KeyResult{KeyDescription: me.MethodName, ValueDescription: "<>"}
methodMatcher := Equals(me.MethodName)
kResult.KeyResult = methodMatcher.Match(me.MethodName)
methodReturn := meth.Call(nil)
if len(methodReturn) != len(me.MethodResultMatchers) {
return &SimpleResult{Description: fmt.Sprintf("Method call resulted in %d values, and not %d", len(methodReturn), len(me.MethodResultMatchers))}
}
methodResults := &MethodResults{}
sb := strings.Builder{}
sb.WriteString("<")
for idx, matcher := range me.MethodResultMatchers {
if idx > 0 {
sb.WriteRune(',')
}
var res MatchResult
if methodReturn[idx].CanInterface() {
res = matcher.Match(methodReturn[idx].Interface())
} else {
res = &SimpleResult{IsMatched: false, Description: fmt.Sprintf("could not get interface of return value %d: %s", idx, methodReturn[idx])}
}
methodResults.Results = append(methodResults.Results, res)
sb.WriteString(methodReturn[idx].String())
}
sb.WriteString(">")
kResult.ValueResult = methodResults
kResult.ValueDescription = sb.String()
result.Add(kResult)
return result
}
type MethodResults struct {
Results []MatchResult
}
func (me *MethodResults) Matched() bool {
for _, result := range me.Results {
if !result.Matched() {
return false
}
}
return true
}
func (me *MethodResults) WriteFailureReason(writer DescriptionWriter) {
reset := writer.IncreaseIndent(1)
defer reset()
for _, result := range me.Results {
writer.NewLine()
result.WriteFailureReason(writer)
}
}
func (me *HasMethodMatcher) WriteDescription(output DescriptionWriter) {
output.WriteString("has a method with a name")
reset := output.IncreaseIndent(1)
defer reset()
output.NewLine()
methodMatcher := Equals(me.MethodName)
methodMatcher.WriteDescription(output)
output.DecreaseIndent(1)
output.NewLine()
output.WriteStringf("and when called with no arguments returns %d values", len(me.MethodResultMatchers))
output.IncreaseIndent(1)
for i, matcher := range me.MethodResultMatchers {
output.NewLine()
output.WriteStringf("[%d] ", i)
matcher.WriteDescription(output)
}
}