9 "github.com/onsi/gomega/format"
12 type MatchJSONMatcher struct {
13 JSONToMatch interface{}
16 func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err error) {
17 actualString, expectedString, err := matcher.prettyPrint(actual)
25 // this is guarded by prettyPrint
26 json.Unmarshal([]byte(actualString), &aval)
27 json.Unmarshal([]byte(expectedString), &eval)
29 return reflect.DeepEqual(aval, eval), nil
32 func (matcher *MatchJSONMatcher) FailureMessage(actual interface{}) (message string) {
33 actualString, expectedString, _ := matcher.prettyPrint(actual)
34 return format.Message(actualString, "to match JSON of", expectedString)
37 func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) {
38 actualString, expectedString, _ := matcher.prettyPrint(actual)
39 return format.Message(actualString, "not to match JSON of", expectedString)
42 func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatted, expectedFormatted string, err error) {
43 actualString, ok := toString(actual)
45 return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1))
47 expectedString, ok := toString(matcher.JSONToMatch)
49 return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.JSONToMatch, 1))
52 abuf := new(bytes.Buffer)
53 ebuf := new(bytes.Buffer)
55 if err := json.Indent(abuf, []byte(actualString), "", " "); err != nil {
56 return "", "", fmt.Errorf("Actual '%s' should be valid JSON, but it is not.\nUnderlying error:%s", actualString, err)
59 if err := json.Indent(ebuf, []byte(expectedString), "", " "); err != nil {
60 return "", "", fmt.Errorf("Expected '%s' should be valid JSON, but it is not.\nUnderlying error:%s", expectedString, err)
63 return abuf.String(), ebuf.String(), nil