-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache_read_test.go
103 lines (95 loc) · 1.85 KB
/
cache_read_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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package cachedreader
import (
"bytes"
"fmt"
"io"
"testing"
)
var str = []byte("the quick brown fox jumps over the lazy dog")
func Test_Read(t *testing.T) {
reader := NewCachedReader(bytes.NewReader(str))
b, err := io.ReadAll(reader)
if err != nil {
t.Error(err)
} else if !bytes.Equal(str, b) {
t.Errorf("expected %s, got %s", str, b)
}
}
func Test(t *testing.T) {
tests := []struct {
name string
preReads func(io.Reader)
}{
{
name: "PreReadByte",
preReads: func(r io.Reader) {
r.Read(make([]byte, 1))
},
},
{
name: "PreReadAll",
preReads: func(r io.Reader) {
r.Read(make([]byte, len(str)))
},
},
{
name: "PreReadNothing",
preReads: func(r io.Reader) {
r.Read(make([]byte, 0))
},
},
{
name: "PreReadMoreThenStream",
preReads: func(r io.Reader) {
r.Read(make([]byte, 1024))
},
},
{
name: "PreReadTwice",
preReads: func(r io.Reader) {
r.Read(make([]byte, 1))
r.Read(make([]byte, 2))
},
},
{
name: "PreReadAllByOne",
preReads: func(r io.Reader) {
for i := 0; i < len(str); i++ {
r.Read(make([]byte, 1))
}
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
reader := NewCachedReader(bytes.NewReader(str))
test.preReads(reader)
reader.Reset()
b, err := io.ReadAll(reader)
if err != nil {
t.Error(err)
} else if !bytes.Equal(str, b) {
t.Errorf("expected %s, got %s", str, b)
}
})
}
}
func Test_ResetTwice(t *testing.T) {
reader := NewCachedReader(bytes.NewReader(str))
reader.Reset()
defer func() {
// recover from panic if one occured. Set err to nil otherwise.
if recover() == nil {
t.Error("expected panic")
}
}()
reader.Reset()
}
// read reader until EOF
func readAll(r io.Reader) {
b, err := io.ReadAll(r)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%s", string(b))
}