match_json_matcher.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package matchers
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/onsi/gomega/format"
  7. )
  8. type MatchJSONMatcher struct {
  9. JSONToMatch interface{}
  10. firstFailurePath []interface{}
  11. }
  12. func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err error) {
  13. actualString, expectedString, err := matcher.prettyPrint(actual)
  14. if err != nil {
  15. return false, err
  16. }
  17. var aval interface{}
  18. var eval interface{}
  19. // this is guarded by prettyPrint
  20. json.Unmarshal([]byte(actualString), &aval)
  21. json.Unmarshal([]byte(expectedString), &eval)
  22. var equal bool
  23. equal, matcher.firstFailurePath = deepEqual(aval, eval)
  24. return equal, nil
  25. }
  26. func (matcher *MatchJSONMatcher) FailureMessage(actual interface{}) (message string) {
  27. actualString, expectedString, _ := matcher.prettyPrint(actual)
  28. return formattedMessage(format.Message(actualString, "to match JSON of", expectedString), matcher.firstFailurePath)
  29. }
  30. func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) {
  31. actualString, expectedString, _ := matcher.prettyPrint(actual)
  32. return formattedMessage(format.Message(actualString, "not to match JSON of", expectedString), matcher.firstFailurePath)
  33. }
  34. func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatted, expectedFormatted string, err error) {
  35. actualString, ok := toString(actual)
  36. if !ok {
  37. return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1))
  38. }
  39. expectedString, ok := toString(matcher.JSONToMatch)
  40. if !ok {
  41. return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.JSONToMatch, 1))
  42. }
  43. abuf := new(bytes.Buffer)
  44. ebuf := new(bytes.Buffer)
  45. if err := json.Indent(abuf, []byte(actualString), "", " "); err != nil {
  46. return "", "", fmt.Errorf("Actual '%s' should be valid JSON, but it is not.\nUnderlying error:%s", actualString, err)
  47. }
  48. if err := json.Indent(ebuf, []byte(expectedString), "", " "); err != nil {
  49. return "", "", fmt.Errorf("Expected '%s' should be valid JSON, but it is not.\nUnderlying error:%s", expectedString, err)
  50. }
  51. return abuf.String(), ebuf.String(), nil
  52. }