-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_empty_reader_test.go
88 lines (79 loc) · 2.42 KB
/
check_empty_reader_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package ioutils_test
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "github.com/koofr/go-ioutils"
)
var _ = Describe("CheckEmptyReader", func() {
It("should return true if the reader is empty", func() {
r := NewCheckEmptyReader(ioutil.NopCloser(bytes.NewReader(nil)))
isEmpty, err := r.IsEmpty()
Expect(err).NotTo(HaveOccurred())
Expect(isEmpty).To(BeTrue())
bb, err := ioutil.ReadAll(r)
r.Close()
Expect(err).NotTo(HaveOccurred())
Expect(bb).To(BeEmpty())
})
It("should return false if the reader is not empty", func() {
r := NewCheckEmptyReader(ioutil.NopCloser(bytes.NewReader([]byte{42})))
isEmpty, err := r.IsEmpty()
Expect(err).NotTo(HaveOccurred())
Expect(isEmpty).To(BeFalse())
bb, err := ioutil.ReadAll(r)
r.Close()
Expect(err).NotTo(HaveOccurred())
Expect(bb).To(Equal([]byte{42}))
})
It("should return and not cache the error", func() {
readCalls := 0
r := NewCheckEmptyReader(ioutil.NopCloser(FuncReader(func(b []byte) (int, error) {
readCalls++
return 0, fmt.Errorf("custom error")
})))
_, err := r.IsEmpty()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("custom error"))
Expect(readCalls).To(Equal(1))
_, err = ioutil.ReadAll(r)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("custom error"))
Expect(readCalls).To(Equal(2))
})
It("should call the original readers close", func() {
closeCalled := true
originalReader := NewPassCloseReader(bytes.NewReader(nil), func() error {
closeCalled = true
return nil
})
r := NewCheckEmptyReader(originalReader)
isEmpty, err := r.IsEmpty()
Expect(err).NotTo(HaveOccurred())
Expect(isEmpty).To(BeTrue())
bb, err := ioutil.ReadAll(r)
r.Close()
Expect(err).NotTo(HaveOccurred())
Expect(bb).To(BeEmpty())
Expect(closeCalled).To(BeTrue())
})
It("should fail if IsEmpty is called more than once", func() {
r := NewCheckEmptyReader(ioutil.NopCloser(bytes.NewReader(nil)))
isEmpty, err := r.IsEmpty()
Expect(err).NotTo(HaveOccurred())
Expect(isEmpty).To(BeTrue())
_, err = r.IsEmpty()
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, ErrDirtyReader)).To(BeTrue())
})
It("should read even if IsEmpty is not called", func() {
r := NewCheckEmptyReader(ioutil.NopCloser(bytes.NewReader([]byte{42})))
bb, err := ioutil.ReadAll(r)
r.Close()
Expect(err).NotTo(HaveOccurred())
Expect(bb).To(Equal([]byte{42}))
})
})