8 "github.com/onsi/gomega/format"
12 type MatchYAMLMatcher struct {
13 YAMLToMatch interface{}
16 func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err error) {
17 actualString, expectedString, err := matcher.toStrings(actual)
25 if err := yaml.Unmarshal([]byte(actualString), &aval); err != nil {
26 return false, fmt.Errorf("Actual '%s' should be valid YAML, but it is not.\nUnderlying error:%s", actualString, err)
28 if err := yaml.Unmarshal([]byte(expectedString), &eval); err != nil {
29 return false, fmt.Errorf("Expected '%s' should be valid YAML, but it is not.\nUnderlying error:%s", expectedString, err)
32 return reflect.DeepEqual(aval, eval), nil
35 func (matcher *MatchYAMLMatcher) FailureMessage(actual interface{}) (message string) {
36 actualString, expectedString, _ := matcher.toNormalisedStrings(actual)
37 return format.Message(actualString, "to match YAML of", expectedString)
40 func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual interface{}) (message string) {
41 actualString, expectedString, _ := matcher.toNormalisedStrings(actual)
42 return format.Message(actualString, "not to match YAML of", expectedString)
45 func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) {
46 actualString, expectedString, err := matcher.toStrings(actual)
47 return normalise(actualString), normalise(expectedString), err
50 func normalise(input string) string {
52 err := yaml.Unmarshal([]byte(input), &val)
54 panic(err) // guarded by Match
56 output, err := yaml.Marshal(val)
58 panic(err) // guarded by Unmarshal
60 return strings.TrimSpace(string(output))
63 func (matcher *MatchYAMLMatcher) toStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) {
64 actualString, ok := toString(actual)
66 return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1))
68 expectedString, ok := toString(matcher.YAMLToMatch)
70 return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.YAMLToMatch, 1))
73 return actualString, expectedString, nil