safebuffer.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. "fmt"
  17. "strings"
  18. "sync"
  19. "testing"
  20. "time"
  21. "gotest.tools/v3/poll"
  22. )
  23. // SafeBuffer is a thread safe version of bytes.Buffer
  24. type SafeBuffer struct {
  25. m sync.RWMutex
  26. b bytes.Buffer
  27. }
  28. // Read is a thread safe version of bytes.Buffer::Read
  29. func (b *SafeBuffer) Read(p []byte) (n int, err error) {
  30. b.m.RLock()
  31. defer b.m.RUnlock()
  32. return b.b.Read(p)
  33. }
  34. // Write is a thread safe version of bytes.Buffer::Write
  35. func (b *SafeBuffer) Write(p []byte) (n int, err error) {
  36. b.m.Lock()
  37. defer b.m.Unlock()
  38. return b.b.Write(p)
  39. }
  40. // String is a thread safe version of bytes.Buffer::String
  41. func (b *SafeBuffer) String() string {
  42. b.m.RLock()
  43. defer b.m.RUnlock()
  44. return b.b.String()
  45. }
  46. // Bytes is a thread safe version of bytes.Buffer::Bytes
  47. func (b *SafeBuffer) Bytes() []byte {
  48. b.m.RLock()
  49. defer b.m.RUnlock()
  50. return b.b.Bytes()
  51. }
  52. // RequireEventuallyContains is a thread safe eventual checker for the buffer content
  53. func (b *SafeBuffer) RequireEventuallyContains(t testing.TB, v string) {
  54. t.Helper()
  55. var bufContents strings.Builder
  56. poll.WaitOn(t, func(logt poll.LogT) poll.Result {
  57. bufContents.Reset()
  58. b.m.Lock()
  59. defer b.m.Unlock()
  60. if _, err := b.b.WriteTo(&bufContents); err != nil {
  61. return poll.Error(fmt.Errorf("failed to copy from buffer. Error: %w", err))
  62. }
  63. if !strings.Contains(bufContents.String(), v) {
  64. return poll.Continue(
  65. "buffer does not contain %q\n============\n%s\n============",
  66. v, &bufContents)
  67. }
  68. return poll.Success()
  69. },
  70. poll.WithTimeout(2*time.Second),
  71. poll.WithDelay(20*time.Millisecond),
  72. )
  73. }