safebuffer.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright 2020 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 utils
  14. import (
  15. "bytes"
  16. "strings"
  17. "sync"
  18. "testing"
  19. "time"
  20. "github.com/stretchr/testify/require"
  21. )
  22. // SafeBuffer is a thread safe version of bytes.Buffer
  23. type SafeBuffer struct {
  24. m sync.RWMutex
  25. b bytes.Buffer
  26. }
  27. // Read is a thread safe version of bytes.Buffer::Read
  28. func (b *SafeBuffer) Read(p []byte) (n int, err error) {
  29. b.m.RLock()
  30. defer b.m.RUnlock()
  31. return b.b.Read(p)
  32. }
  33. // Write is a thread safe version of bytes.Buffer::Write
  34. func (b *SafeBuffer) Write(p []byte) (n int, err error) {
  35. b.m.Lock()
  36. defer b.m.Unlock()
  37. return b.b.Write(p)
  38. }
  39. // String is a thread safe version of bytes.Buffer::String
  40. func (b *SafeBuffer) String() string {
  41. b.m.RLock()
  42. defer b.m.RUnlock()
  43. return b.b.String()
  44. }
  45. // Bytes is a thread safe version of bytes.Buffer::Bytes
  46. func (b *SafeBuffer) Bytes() []byte {
  47. b.m.RLock()
  48. defer b.m.RUnlock()
  49. return b.b.Bytes()
  50. }
  51. // RequireEventuallyContains is a thread safe eventual checker for the buffer content
  52. func (b *SafeBuffer) RequireEventuallyContains(t testing.TB, v string) {
  53. t.Helper()
  54. var bufContents strings.Builder
  55. require.Eventuallyf(t, func() bool {
  56. b.m.Lock()
  57. defer b.m.Unlock()
  58. if _, err := b.b.WriteTo(&bufContents); err != nil {
  59. require.FailNowf(t, "Failed to copy from buffer",
  60. "Error: %v", err)
  61. }
  62. return strings.Contains(bufContents.String(), v)
  63. }, 2*time.Second, 20*time.Millisecond,
  64. "Buffer did not contain %q\n============\n%s\n============",
  65. v, &bufContents)
  66. }