-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhave_key_matcher.go
59 lines (51 loc) · 1.75 KB
/
have_key_matcher.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package gnosj
import (
"fmt"
"github.com/totherme/nosj"
)
// HaveJSONKeyMatcher is a gomega matcher which tests if a given value
// represents a json object containing a particular key.
type HaveJSONKeyMatcher struct {
key string
}
// HaveJSONKey returns a gomega matcher which tests if a given value
// represents a json object containing a given `key`.
func HaveJSONKey(key string) HaveJSONKeyMatcher {
return HaveJSONKeyMatcher{key: key}
}
// Match is the gomega function that actually checks if the given value
// represents a json object containing the particular key.
func (m HaveJSONKeyMatcher) Match(actual interface{}) (bool, error) {
switch j := actual.(type) {
default:
return false, fmt.Errorf("not a JSON object. Have you done nosj.ParseJSON(...)?")
case nosj.JSON:
return j.HasKey(m.key), nil
}
}
// FailureMessage constructs a hopefully-helpful error message in the case that
// the given value does not represent a json object containing the particular
// key.
func (m HaveJSONKeyMatcher) FailureMessage(actual interface{}) (message string) {
actualString := fmt.Sprintf("%+v", actual)
return fmt.Sprintf("expected '%s' to be a nosj.JSON object with key '%s'",
truncateString(actualString),
m.key)
}
// NegatedFailureMessage constructs a hopefully-helpful error message in the
// case that the given value unexpectedly represents a json object containing
// the particular key.
func (m HaveJSONKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) {
actualString := fmt.Sprintf("%+v", actual)
return fmt.Sprintf("expected '%s' not to contain the key '%s'",
truncateString(actualString),
m.key)
}
func truncateString(s string) (t string) {
if len(s) > 50 {
t = fmt.Sprintf("%s...", s[0:50])
} else {
t = s
}
return
}