2018-01-29 19:44:18 +00:00
|
|
|
package matchers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"reflect"
|
2018-09-05 15:36:14 +00:00
|
|
|
|
|
|
|
"github.com/onsi/gomega/format"
|
2018-01-29 19:44:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type HaveKeyMatcher struct {
|
|
|
|
Key interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err error) {
|
|
|
|
if !isMap(actual) {
|
|
|
|
return false, fmt.Errorf("HaveKey matcher expects a map. Got:%s", format.Object(actual, 1))
|
|
|
|
}
|
|
|
|
|
|
|
|
keyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher)
|
|
|
|
if !keyIsMatcher {
|
|
|
|
keyMatcher = &EqualMatcher{Expected: matcher.Key}
|
|
|
|
}
|
|
|
|
|
|
|
|
keys := reflect.ValueOf(actual).MapKeys()
|
|
|
|
for i := 0; i < len(keys); i++ {
|
|
|
|
success, err := keyMatcher.Match(keys[i].Interface())
|
|
|
|
if err != nil {
|
|
|
|
return false, fmt.Errorf("HaveKey's key matcher failed with:\n%s%s", format.Indent, err.Error())
|
|
|
|
}
|
|
|
|
if success {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message string) {
|
|
|
|
switch matcher.Key.(type) {
|
|
|
|
case omegaMatcher:
|
|
|
|
return format.Message(actual, "to have key matching", matcher.Key)
|
|
|
|
default:
|
|
|
|
return format.Message(actual, "to have key", matcher.Key)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (matcher *HaveKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) {
|
|
|
|
switch matcher.Key.(type) {
|
|
|
|
case omegaMatcher:
|
|
|
|
return format.Message(actual, "not to have key matching", matcher.Key)
|
|
|
|
default:
|
|
|
|
return format.Message(actual, "not to have key", matcher.Key)
|
|
|
|
}
|
|
|
|
}
|