File: have_key_matcher.go

package info (click to toggle)
golang-gomega 1.0%2Bgit20160910.d59fa0a-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 728 kB
  • sloc: makefile: 12
file content (53 lines) | stat: -rw-r--r-- 1,359 bytes parent folder | download | duplicates (2)
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
package matchers

import (
	"fmt"
	"github.com/onsi/gomega/format"
	"reflect"
)

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)
	}
}