github.com/grahambrereton-form3/tilt@v0.10.18/internal/testutils/bufsync/bufsync.go (about) 1 package bufsync 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "strings" 8 "sync" 9 "time" 10 ) 11 12 type ThreadSafeBuffer struct { 13 buf *bytes.Buffer 14 mu sync.Mutex 15 } 16 17 func NewThreadSafeBuffer() *ThreadSafeBuffer { 18 return &ThreadSafeBuffer{ 19 buf: bytes.NewBuffer(nil), 20 } 21 } 22 23 func (b *ThreadSafeBuffer) Write(bs []byte) (int, error) { 24 b.mu.Lock() 25 defer b.mu.Unlock() 26 return b.buf.Write(bs) 27 } 28 29 func (b *ThreadSafeBuffer) String() string { 30 b.mu.Lock() 31 defer b.mu.Unlock() 32 return b.buf.String() 33 } 34 35 func (b *ThreadSafeBuffer) WaitUntilContains(expected string, timeout time.Duration) error { 36 start := time.Now() 37 for time.Since(start) < timeout { 38 result := b.String() 39 if strings.Contains(result, expected) { 40 return nil 41 } 42 time.Sleep(10 * time.Millisecond) 43 } 44 45 return fmt.Errorf("Timeout. Expected %q. Actual: %s", expected, b.String()) 46 } 47 48 var _ io.Writer = &ThreadSafeBuffer{}