initial commit
[govpp.git] / vendor / github.com / onsi / gomega / matchers / match_json_matcher.go
1 package matchers
2
3 import (
4         "bytes"
5         "encoding/json"
6         "fmt"
7         "reflect"
8
9         "github.com/onsi/gomega/format"
10 )
11
12 type MatchJSONMatcher struct {
13         JSONToMatch interface{}
14 }
15
16 func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err error) {
17         actualString, expectedString, err := matcher.prettyPrint(actual)
18         if err != nil {
19                 return false, err
20         }
21
22         var aval interface{}
23         var eval interface{}
24
25         // this is guarded by prettyPrint
26         json.Unmarshal([]byte(actualString), &aval)
27         json.Unmarshal([]byte(expectedString), &eval)
28
29         return reflect.DeepEqual(aval, eval), nil
30 }
31
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)
35 }
36
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)
40 }
41
42 func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatted, expectedFormatted string, err error) {
43         actualString, ok := toString(actual)
44         if !ok {
45                 return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte.  Got actual:\n%s", format.Object(actual, 1))
46         }
47         expectedString, ok := toString(matcher.JSONToMatch)
48         if !ok {
49                 return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte.  Got expected:\n%s", format.Object(matcher.JSONToMatch, 1))
50         }
51
52         abuf := new(bytes.Buffer)
53         ebuf := new(bytes.Buffer)
54
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)
57         }
58
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)
61         }
62
63         return abuf.String(), ebuf.String(), nil
64 }