have_key_matcher.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package matchers
  2. import (
  3. "fmt"
  4. "reflect"
  5. "github.com/onsi/gomega/format"
  6. )
  7. type HaveKeyMatcher struct {
  8. Key interface{}
  9. }
  10. func (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err error) {
  11. if !isMap(actual) {
  12. return false, fmt.Errorf("HaveKey matcher expects a map. Got:%s", format.Object(actual, 1))
  13. }
  14. keyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher)
  15. if !keyIsMatcher {
  16. keyMatcher = &EqualMatcher{Expected: matcher.Key}
  17. }
  18. keys := reflect.ValueOf(actual).MapKeys()
  19. for i := 0; i < len(keys); i++ {
  20. success, err := keyMatcher.Match(keys[i].Interface())
  21. if err != nil {
  22. return false, fmt.Errorf("HaveKey's key matcher failed with:\n%s%s", format.Indent, err.Error())
  23. }
  24. if success {
  25. return true, nil
  26. }
  27. }
  28. return false, nil
  29. }
  30. func (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message string) {
  31. switch matcher.Key.(type) {
  32. case omegaMatcher:
  33. return format.Message(actual, "to have key matching", matcher.Key)
  34. default:
  35. return format.Message(actual, "to have key", matcher.Key)
  36. }
  37. }
  38. func (matcher *HaveKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) {
  39. switch matcher.Key.(type) {
  40. case omegaMatcher:
  41. return format.Message(actual, "not to have key matching", matcher.Key)
  42. default:
  43. return format.Message(actual, "not to have key", matcher.Key)
  44. }
  45. }