buffer.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright 2022 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package e2e
  14. import (
  15. "bytes"
  16. "strings"
  17. "sync"
  18. "testing"
  19. "time"
  20. "github.com/stretchr/testify/require"
  21. )
  22. type lockedBuffer struct {
  23. mu sync.Mutex
  24. buf bytes.Buffer
  25. }
  26. func (l *lockedBuffer) Read(p []byte) (n int, err error) {
  27. l.mu.Lock()
  28. defer l.mu.Unlock()
  29. return l.buf.Read(p)
  30. }
  31. func (l *lockedBuffer) Write(p []byte) (n int, err error) {
  32. l.mu.Lock()
  33. defer l.mu.Unlock()
  34. return l.buf.Write(p)
  35. }
  36. func (l *lockedBuffer) String() string {
  37. l.mu.Lock()
  38. defer l.mu.Unlock()
  39. return l.buf.String()
  40. }
  41. func (l *lockedBuffer) RequireEventuallyContains(t testing.TB, v string) {
  42. t.Helper()
  43. var bufContents strings.Builder
  44. require.Eventuallyf(t, func() bool {
  45. l.mu.Lock()
  46. defer l.mu.Unlock()
  47. if _, err := l.buf.WriteTo(&bufContents); err != nil {
  48. require.FailNowf(t, "Failed to copy from buffer",
  49. "Error: %v", err)
  50. }
  51. return strings.Contains(bufContents.String(), v)
  52. }, 5*time.Second, 20*time.Millisecond,
  53. "Buffer did not contain %q\n============\n%s\n============",
  54. v, &bufContents)
  55. }