writer_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Copyright 2014 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 flushwriter
  14. import (
  15. "fmt"
  16. "testing"
  17. )
  18. type writerWithFlush struct {
  19. writeCount, flushCount int
  20. err error
  21. }
  22. func (w *writerWithFlush) Flush() {
  23. w.flushCount++
  24. }
  25. func (w *writerWithFlush) Write(p []byte) (n int, err error) {
  26. w.writeCount++
  27. return len(p), w.err
  28. }
  29. type writerWithNoFlush struct {
  30. writeCount int
  31. }
  32. func (w *writerWithNoFlush) Write(p []byte) (n int, err error) {
  33. w.writeCount++
  34. return len(p), nil
  35. }
  36. func TestWriteWithFlush(t *testing.T) {
  37. w := &writerWithFlush{}
  38. fw := Wrap(w)
  39. for i := 0; i < 10; i++ {
  40. _, err := fw.Write([]byte("Test write"))
  41. if err != nil {
  42. t.Errorf("Unexpected error while writing with flush writer: %v", err)
  43. }
  44. }
  45. if w.flushCount != 10 {
  46. t.Errorf("Flush not called the expected number of times. Actual: %d", w.flushCount)
  47. }
  48. if w.writeCount != 10 {
  49. t.Errorf("Write not called the expected number of times. Actual: %d", w.writeCount)
  50. }
  51. }
  52. func TestWriteWithoutFlush(t *testing.T) {
  53. w := &writerWithNoFlush{}
  54. fw := Wrap(w)
  55. for i := 0; i < 10; i++ {
  56. _, err := fw.Write([]byte("Test write"))
  57. if err != nil {
  58. t.Errorf("Unexpected error while writing with flush writer: %v", err)
  59. }
  60. }
  61. if w.writeCount != 10 {
  62. t.Errorf("Write not called the expected number of times. Actual: %d", w.writeCount)
  63. }
  64. }
  65. func TestWriteError(t *testing.T) {
  66. e := fmt.Errorf("Error")
  67. w := &writerWithFlush{err: e}
  68. fw := Wrap(w)
  69. _, err := fw.Write([]byte("Test write"))
  70. if err != e {
  71. t.Errorf("Did not get expected error. Got: %#v", err)
  72. }
  73. }