have_key_matcher.go 1.4 KB

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