-
Notifications
You must be signed in to change notification settings - Fork 2
/
break_reader_test.go
86 lines (70 loc) · 1.61 KB
/
break_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
package badio
import (
"bytes"
"fmt"
"io"
"strings"
"testing"
)
func TestBreakReader(t *testing.T) {
// reader to generate infinite stream of 0x01
tr := NewSequenceReader([]byte{0xFF})
tests := 1024
for i := 0; i < tests; i++ {
// create a big buffer
p := make([]byte, tests)
r := NewBreakReader(tr, int64(i))
// read one byte at a time
var n, o int
var err error
for x := 0; x < tests && err == nil; x++ {
n, err = r.Read(p[x : x+1])
o += n
}
// ensure an error happened
if !IsBadIOError(err) {
t.Fatalf("Expected BadIOError, got: %v", err)
}
// make sure break point was accurate
if o != i {
t.Fatalf("Expected to read %d bytes, got: %d", i, n)
}
// count actual read bytes
n = 0
for x := 0; x < len(p); x++ {
if p[x] != 0 {
n++
}
}
if n != i {
t.Fatalf("Expected %d bytes to be changed, got %d", i, n)
}
// make sure next read is an error
n, err = r.Read(p)
if n != 0 {
t.Errorf("Expected to read 0 bytes, got %d", n)
}
if !IsBadIOError(err) {
t.Fatalf("Expected BadIOError, got: %v", err)
}
}
// what if underlying reader is shorter than the break point?
tr = NewBreakReader(bytes.NewReader(make([]byte, 8)), 16)
var n, o int
var err error
for err == nil && o < 16 {
n, err = tr.Read(make([]byte, 16))
o += n
}
if err != io.EOF {
t.Fatalf("Expected io.EOF, got: %v", err)
}
}
func ExampleNewBreakReader() {
s := strings.NewReader("banananananananananana")
r := NewBreakReader(s, 6)
p := make([]byte, 20)
_, err := r.Read(p)
fmt.Printf("Error: %v\n", err)
// Output: Error: Reader break point at offset 6 (0x6)
}