Path: blob/main/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go
2880 views
package matchers12import (3"fmt"4"strings"56"github.com/onsi/gomega/format"7"go.yaml.in/yaml/v3"8)910type MatchYAMLMatcher struct {11YAMLToMatch any12firstFailurePath []any13}1415func (matcher *MatchYAMLMatcher) Match(actual any) (success bool, err error) {16actualString, expectedString, err := matcher.toStrings(actual)17if err != nil {18return false, err19}2021var aval any22var eval any2324if err := yaml.Unmarshal([]byte(actualString), &aval); err != nil {25return false, fmt.Errorf("Actual '%s' should be valid YAML, but it is not.\nUnderlying error:%s", actualString, err)26}27if err := yaml.Unmarshal([]byte(expectedString), &eval); err != nil {28return false, fmt.Errorf("Expected '%s' should be valid YAML, but it is not.\nUnderlying error:%s", expectedString, err)29}3031var equal bool32equal, matcher.firstFailurePath = deepEqual(aval, eval)33return equal, nil34}3536func (matcher *MatchYAMLMatcher) FailureMessage(actual any) (message string) {37actualString, expectedString, _ := matcher.toNormalisedStrings(actual)38return formattedMessage(format.Message(actualString, "to match YAML of", expectedString), matcher.firstFailurePath)39}4041func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual any) (message string) {42actualString, expectedString, _ := matcher.toNormalisedStrings(actual)43return formattedMessage(format.Message(actualString, "not to match YAML of", expectedString), matcher.firstFailurePath)44}4546func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual any) (actualFormatted, expectedFormatted string, err error) {47actualString, expectedString, err := matcher.toStrings(actual)48return normalise(actualString), normalise(expectedString), err49}5051func normalise(input string) string {52var val any53err := yaml.Unmarshal([]byte(input), &val)54if err != nil {55panic(err) // unreachable since Match already calls Unmarshal56}57output, err := yaml.Marshal(val)58if err != nil {59panic(err) // untested section, unreachable since we Unmarshal above60}61return strings.TrimSpace(string(output))62}6364func (matcher *MatchYAMLMatcher) toStrings(actual any) (actualFormatted, expectedFormatted string, err error) {65actualString, ok := toString(actual)66if !ok {67return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1))68}69expectedString, ok := toString(matcher.YAMLToMatch)70if !ok {71return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.YAMLToMatch, 1))72}7374return actualString, expectedString, nil75}767778