github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/testutils/bufsync/bufsync.go (about)

     1  package bufsync
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"strings"
     7  	"sync"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  type ThreadSafeBuffer struct {
    15  	buf *bytes.Buffer
    16  	mu  sync.Mutex
    17  }
    18  
    19  func NewThreadSafeBuffer() *ThreadSafeBuffer {
    20  	return &ThreadSafeBuffer{
    21  		buf: bytes.NewBuffer(nil),
    22  	}
    23  }
    24  
    25  func (b *ThreadSafeBuffer) Write(bs []byte) (int, error) {
    26  	b.mu.Lock()
    27  	defer b.mu.Unlock()
    28  	return b.buf.Write(bs)
    29  }
    30  
    31  func (b *ThreadSafeBuffer) String() string {
    32  	b.mu.Lock()
    33  	defer b.mu.Unlock()
    34  	return b.buf.String()
    35  }
    36  
    37  func (b *ThreadSafeBuffer) AssertEventuallyContains(tb testing.TB, expected string, timeout time.Duration) {
    38  	tb.Helper()
    39  	assert.Eventuallyf(tb, func() bool {
    40  		return strings.Contains(b.String(), expected)
    41  	}, timeout, 10*time.Millisecond,
    42  		"Expected: %q. Actual: %q", expected, LazyString(b.String))
    43  }
    44  
    45  func (b *ThreadSafeBuffer) Reset() {
    46  	b.mu.Lock()
    47  	defer b.mu.Unlock()
    48  
    49  	b.buf.Reset()
    50  }
    51  
    52  var _ io.Writer = &ThreadSafeBuffer{}
    53  
    54  type LazyString func() string
    55  
    56  func (s LazyString) String() string {
    57  	return s()
    58  }