-
Notifications
You must be signed in to change notification settings - Fork 2
/
truncate_reader_test.go
66 lines (53 loc) · 1.23 KB
/
truncate_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
package badio
import (
"bytes"
"fmt"
"io"
"strings"
"testing"
)
func TestTruncateReader(t *testing.T) {
s := "abcdefghijklmnopqrstuvwxyz"
for i := 0; i < len(s); i++ {
// create a full size buffer
p := make([]byte, len(s))
// create truncate read to truncate at i
r := NewTruncateReader(strings.NewReader(s), int64(i))
// read one byte at a time
var n, o int
var err error
for x := 0; x < len(s) && err == nil; x++ {
n, err = r.Read(p[x : x+1])
o += n
}
// ensure we reach EOF
if err != io.EOF {
t.Fatalf("Expected io.EOF, got: %v", err)
}
// make sure break point was accurate
if o != i {
t.Fatalf("Expected to read %d bytes, got: %d", i, n)
}
// validate new string
out := string(bytes.Trim(p, "\x00"))
if out != s[:i] {
t.Errorf("Expected '%s', got: '%s'", s[:i], out)
}
// make sure next read is io.EOF
n, err = r.Read(p)
if n != 0 {
t.Errorf("Expected to read 0 bytes, got %d", n)
}
if err != io.EOF {
t.Fatalf("Expected io.EOF, got: %v", err)
}
}
}
func ExampleNewTruncateReader() {
s := strings.NewReader("banananananananananana")
r := NewTruncateReader(s, 6)
p := make([]byte, 20)
r.Read(p)
fmt.Printf("%s\n", bytes.Trim(p, "\x00"))
// Output: banana
}