-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathwriter_test.go
91 lines (85 loc) · 2.09 KB
/
writer_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
package pool
import (
"bytes"
"testing"
)
func checkSize(t *testing.T, w *Writer) {
if w.Size()-w.Buffered() != w.Available() {
t.Fatalf("size (%d), buffered (%d), available (%d) mismatch", w.Size(), w.Buffered(), w.Available())
}
}
func TestWriter(t *testing.T) {
var b bytes.Buffer
w := Writer{W: &b}
n, err := w.Write([]byte("foobar"))
checkSize(t, &w)
if err != nil || n != 6 {
t.Fatalf("write failed: %d, %s", n, err)
}
if b.Len() != 0 {
t.Fatal("expected the buffer to be empty")
}
if w.Buffered() != 6 {
t.Fatalf("expected 6 bytes to be buffered, got %d", w.Buffered())
}
checkSize(t, &w)
if err := w.Flush(); err != nil {
t.Fatal(err)
}
checkSize(t, &w)
if err := w.Flush(); err != nil {
t.Fatal(err)
}
checkSize(t, &w)
if b.String() != "foobar" {
t.Fatal("expected to have written foobar")
}
b.Reset()
buf := make([]byte, WriterBufferSize)
n, err = w.Write(buf)
if n != WriterBufferSize || err != nil {
t.Fatalf("write failed: %d, %s", n, err)
}
checkSize(t, &w)
if b.Len() != WriterBufferSize {
t.Fatal("large write should have gone through directly")
}
if err := w.Flush(); err != nil {
t.Fatal(err)
}
checkSize(t, &w)
b.Reset()
if err := w.WriteByte(1); err != nil {
t.Fatal(err)
}
if w.Buffered() != 1 {
t.Fatalf("expected 1 byte to be buffered, got %d", w.Buffered())
}
if n, err := w.WriteRune('1'); err != nil || n != 1 {
t.Fatal(err)
}
if w.Buffered() != 2 {
t.Fatalf("expected 2 bytes to be buffered, got %d", w.Buffered())
}
checkSize(t, &w)
if n, err := w.WriteString("foobar"); err != nil || n != 6 {
t.Fatal(err)
}
if w.Buffered() != 8 {
t.Fatalf("expected 8 bytes to be buffered, got %d", w.Buffered())
}
checkSize(t, &w)
if b.Len() != 0 {
t.Fatal("write should have been buffered")
}
n, err = w.Write(buf)
if n != WriterBufferSize || err != nil {
t.Fatalf("write failed: %d, %s", n, err)
}
if b.Len() != WriterBufferSize || b.Bytes()[0] != 1 || b.String()[1:8] != "1foobar" {
t.Fatalf("failed to flush properly: len:%d, prefix:%#v", b.Len(), b.Bytes()[:10])
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
}