buffered_writer_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package fileexporter
  4. import (
  5. "bytes"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "os"
  10. "path"
  11. "testing"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. )
  15. const (
  16. msg = "it is a beautiful world"
  17. SizeByte = 1
  18. SizeKiloByte = 1 << (10 * iota)
  19. SizeMegaByte
  20. )
  21. type NopWriteCloser struct {
  22. w io.Writer
  23. }
  24. func (NopWriteCloser) Close() error { return nil }
  25. func (wc *NopWriteCloser) Write(p []byte) (int, error) { return wc.w.Write(p) }
  26. func TestBufferedWrites(t *testing.T) {
  27. t.Parallel()
  28. b := bytes.NewBuffer(nil)
  29. w := newBufferedWriteCloser(&NopWriteCloser{b})
  30. _, err := w.Write([]byte(msg))
  31. require.NoError(t, err, "Must not error when writing data")
  32. assert.NoError(t, w.Close(), "Must not error when closing writer")
  33. assert.Equal(t, msg, b.String(), "Must match the expected string")
  34. }
  35. var (
  36. errBenchmark error
  37. )
  38. func BenchmarkWriter(b *testing.B) {
  39. tempfile := func(tb testing.TB) io.WriteCloser {
  40. f, err := os.CreateTemp(tb.TempDir(), tb.Name())
  41. require.NoError(tb, err, "Must not error when creating benchmark temp file")
  42. tb.Cleanup(func() {
  43. assert.NoError(tb, os.RemoveAll(path.Dir(f.Name())), "Must clean up files after being written")
  44. })
  45. return f
  46. }
  47. for _, payloadSize := range []int{
  48. 10 * SizeKiloByte,
  49. 100 * SizeKiloByte,
  50. SizeMegaByte,
  51. 10 * SizeMegaByte,
  52. } {
  53. payload := make([]byte, payloadSize)
  54. for i := 0; i < payloadSize; i++ {
  55. payload[i] = 'a'
  56. }
  57. for name, w := range map[string]io.WriteCloser{
  58. "discard": &NopWriteCloser{io.Discard},
  59. "buffered-discard": newBufferedWriteCloser(&NopWriteCloser{io.Discard}),
  60. "raw-file": tempfile(b),
  61. "buffered-file": newBufferedWriteCloser(tempfile(b)),
  62. } {
  63. w := w
  64. b.Run(fmt.Sprintf("%s_%d_bytes", name, payloadSize), func(b *testing.B) {
  65. b.ReportAllocs()
  66. b.ResetTimer()
  67. var err error
  68. for i := 0; i < b.N; i++ {
  69. _, err = w.Write(payload)
  70. }
  71. errBenchmark = errors.Join(err, w.Close())
  72. })
  73. }
  74. }
  75. }