Path: blob/main/vendor/github.com/onsi/gomega/gbytes/say_matcher.go
2880 views
// untested sections: 112package gbytes34import (5"fmt"6"regexp"78"github.com/onsi/gomega/format"9)1011// Objects satisfying the BufferProvider can be used with the Say matcher.12type BufferProvider interface {13Buffer() *Buffer14}1516/*17Say is a Gomega matcher that operates on gbytes.Buffers:1819Expect(buffer).Should(Say("something"))2021will succeed if the unread portion of the buffer matches the regular expression "something".2223When Say succeeds, it fast forwards the gbytes.Buffer's read cursor to just after the successful match.24Thus, subsequent calls to Say will only match against the unread portion of the buffer2526Say pairs very well with Eventually. To assert that a buffer eventually receives data matching "[123]-star" within 3 seconds you can:2728Eventually(buffer, 3).Should(Say("[123]-star"))2930Ditto with consistently. To assert that a buffer does not receive data matching "never-see-this" for 1 second you can:3132Consistently(buffer, 1).ShouldNot(Say("never-see-this"))3334In addition to bytes.Buffers, Say can operate on objects that implement the gbytes.BufferProvider interface.35In such cases, Say simply operates on the *gbytes.Buffer returned by Buffer()3637If the buffer is closed, the Say matcher will tell Eventually to abort.38*/39func Say(expected string, args ...any) *sayMatcher {40if len(args) > 0 {41expected = fmt.Sprintf(expected, args...)42}43return &sayMatcher{44re: regexp.MustCompile(expected),45}46}4748type sayMatcher struct {49re *regexp.Regexp50receivedSayings []byte51}5253func (m *sayMatcher) buffer(actual any) (*Buffer, bool) {54var buffer *Buffer5556switch x := actual.(type) {57case *Buffer:58buffer = x59case BufferProvider:60buffer = x.Buffer()61default:62return nil, false63}6465return buffer, true66}6768func (m *sayMatcher) Match(actual any) (success bool, err error) {69buffer, ok := m.buffer(actual)70if !ok {71return false, fmt.Errorf("Say must be passed a *gbytes.Buffer or BufferProvider. Got:\n%s", format.Object(actual, 1))72}7374didSay, sayings := buffer.didSay(m.re)75m.receivedSayings = sayings7677return didSay, nil78}7980func (m *sayMatcher) FailureMessage(actual any) (message string) {81return fmt.Sprintf(82"Got stuck at:\n%s\nWaiting for:\n%s",83format.IndentString(string(m.receivedSayings), 1),84format.IndentString(m.re.String(), 1),85)86}8788func (m *sayMatcher) NegatedFailureMessage(actual any) (message string) {89return fmt.Sprintf(90"Saw:\n%s\nWhich matches the unexpected:\n%s",91format.IndentString(string(m.receivedSayings), 1),92format.IndentString(m.re.String(), 1),93)94}9596func (m *sayMatcher) MatchMayChangeInTheFuture(actual any) bool {97switch x := actual.(type) {98case *Buffer:99return !x.Closed()100case BufferProvider:101return !x.Buffer().Closed()102default:103return true104}105}106107108