Path: blob/main/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go
2880 views
package matchers12import (3"bytes"4"encoding/json"5"fmt"67"github.com/onsi/gomega/format"8)910type MatchJSONMatcher struct {11JSONToMatch any12firstFailurePath []any13}1415func (matcher *MatchJSONMatcher) Match(actual any) (success bool, err error) {16actualString, expectedString, err := matcher.prettyPrint(actual)17if err != nil {18return false, err19}2021var aval any22var eval any2324// this is guarded by prettyPrint25json.Unmarshal([]byte(actualString), &aval)26json.Unmarshal([]byte(expectedString), &eval)27var equal bool28equal, matcher.firstFailurePath = deepEqual(aval, eval)29return equal, nil30}3132func (matcher *MatchJSONMatcher) FailureMessage(actual any) (message string) {33actualString, expectedString, _ := matcher.prettyPrint(actual)34return formattedMessage(format.Message(actualString, "to match JSON of", expectedString), matcher.firstFailurePath)35}3637func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual any) (message string) {38actualString, expectedString, _ := matcher.prettyPrint(actual)39return formattedMessage(format.Message(actualString, "not to match JSON of", expectedString), matcher.firstFailurePath)40}4142func (matcher *MatchJSONMatcher) prettyPrint(actual any) (actualFormatted, expectedFormatted string, err error) {43actualString, ok := toString(actual)44if !ok {45return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1))46}47expectedString, ok := toString(matcher.JSONToMatch)48if !ok {49return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.JSONToMatch, 1))50}5152abuf := new(bytes.Buffer)53ebuf := new(bytes.Buffer)5455if err := json.Indent(abuf, []byte(actualString), "", " "); err != nil {56return "", "", fmt.Errorf("Actual '%s' should be valid JSON, but it is not.\nUnderlying error:%s", actualString, err)57}5859if err := json.Indent(ebuf, []byte(expectedString), "", " "); err != nil {60return "", "", fmt.Errorf("Expected '%s' should be valid JSON, but it is not.\nUnderlying error:%s", expectedString, err)61}6263return abuf.String(), ebuf.String(), nil64}656667