/
hasfield.go
36 lines (33 loc) · 1.08 KB
/
hasfield.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
package has
import (
"fmt"
"github.com/corbym/gocrest"
"reflect"
)
//FieldNamed is a naive implementation for testing if a struct has a particular field name. Does not check type.
//Returns a matcher that will use reflect to check if the actual has the method given by expected
func FieldNamed(expected string) *gocrest.Matcher {
matcher := new(gocrest.Matcher)
matcher.Describe = fmt.Sprintf("struct with function %s", expected)
matcher.Matches = func(actual interface{}) bool {
typeOfActual := reflect.TypeOf(actual)
matcher.Actual = fieldStringValue(typeOfActual)
expectedName := reflect.ValueOf(expected).String()
_, ok := typeOfActual.Elem().FieldByName(expectedName)
return ok
}
return matcher
}
func fieldStringValue(actualType reflect.Type) string {
description := actualType.Elem().Name() + "{"
numFields := actualType.Elem().NumField()
for x := 0; x < numFields; x++ {
field := actualType.Elem().Field(x)
description += fmt.Sprintf("%s %s", field.Name, field.Type.Name())
if x != numFields-1 {
description += " "
}
}
description += "}"
return description
}