ioutils_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. Copyright 2019 The Kubernetes 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 ioutils
  14. import (
  15. "bytes"
  16. "fmt"
  17. "math/rand"
  18. "testing"
  19. "github.com/stretchr/testify/assert"
  20. )
  21. func TestLimitWriter(t *testing.T) {
  22. r := rand.New(rand.NewSource(1234)) // Fixed source to prevent flakes.
  23. tests := []struct {
  24. inputSize, limit, writeSize int64
  25. }{
  26. // Single write tests
  27. {100, 101, 100},
  28. {100, 100, 100},
  29. {100, 99, 100},
  30. {1, 1, 1},
  31. {100, 10, 100},
  32. {100, 0, 100},
  33. {100, -1, 100},
  34. // Multi write tests
  35. {100, 101, 10},
  36. {100, 100, 10},
  37. {100, 99, 10},
  38. {100, 10, 10},
  39. {100, 0, 10},
  40. {100, -1, 10},
  41. }
  42. for _, test := range tests {
  43. t.Run(fmt.Sprintf("inputSize=%d limit=%d writes=%d", test.inputSize, test.limit, test.writeSize), func(t *testing.T) {
  44. input := make([]byte, test.inputSize)
  45. r.Read(input)
  46. output := &bytes.Buffer{}
  47. w := LimitWriter(output, test.limit)
  48. var (
  49. err error
  50. written int64
  51. n int
  52. )
  53. for written < test.inputSize && err == nil {
  54. n, err = w.Write(input[written : written+test.writeSize])
  55. written += int64(n)
  56. }
  57. expectWritten := bounded(0, test.inputSize, test.limit)
  58. assert.EqualValues(t, expectWritten, written)
  59. if expectWritten <= 0 {
  60. assert.Empty(t, output)
  61. } else {
  62. assert.Equal(t, input[:expectWritten], output.Bytes())
  63. }
  64. if test.limit < test.inputSize {
  65. assert.Error(t, err)
  66. } else {
  67. assert.NoError(t, err)
  68. }
  69. })
  70. }
  71. }
  72. func bounded(min, val, max int64) int64 {
  73. if max < val {
  74. val = max
  75. }
  76. if val < min {
  77. val = min
  78. }
  79. return val
  80. }