-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathioutil_test.go
127 lines (96 loc) · 2.44 KB
/
ioutil_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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"bytes"
"compress/gzip"
"io"
"io/ioutil"
"math/rand"
"net/http"
"reflect"
"testing"
"testing/iotest"
"time"
)
const expSize = 64 * 1024
func TestMultiReader(t *testing.T) {
t.Parallel()
randomSrc := randomDataMaker{rand.NewSource(1028890720402726901)}
lr := io.LimitReader(&randomSrc, expSize)
r1, r2 := newMultiReader(lr)
b1 := &bytes.Buffer{}
b2 := &bytes.Buffer{}
rs := make(chan copyRes, 2)
go bgCopy(b1, r1, rs)
go bgCopy(b2, r2, rs)
res1 := <-rs
res2 := <-rs
if res1.e != nil || res2.e != nil {
t.Logf("Error copying data: %v/%v", res1.e, res2.e)
}
if res1.s != res2.s || res1.s != expSize {
t.Fatalf("Read %v/%v bytes, expected %v",
res1.s, res2.s, expSize)
}
if !reflect.DeepEqual(b1, b2) {
t.Fatalf("Didn't read the same data from the two things")
}
}
func TestMultiReaderSourceError(t *testing.T) {
t.Parallel()
// This test fails if it doesn't complete quickly.
timer := time.AfterFunc(2*time.Second, func() {
t.Fatalf("Test seems to have hung.")
})
defer timer.Stop()
randomSrc := randomDataMaker{rand.NewSource(1028890720402726901)}
tordr := iotest.TimeoutReader(&randomSrc)
lr := io.LimitReader(tordr, expSize)
r1, _ := newMultiReaderTimeout(lr, 10*time.Millisecond)
b1 := &bytes.Buffer{}
rs := make(chan copyRes, 2)
go bgCopy(b1, r1, rs)
res1 := <-rs
if res1.e != Timeout {
t.Errorf("Expected a timeout, got %v", res1.e)
t.Fail()
}
}
func BenchmarkRandomDataMaker(b *testing.B) {
randomSrc := randomDataMaker{rand.NewSource(1028890720402726901)}
for i := 0; i < b.N; i++ {
b.SetBytes(int64(i))
copied, err := io.CopyN(ioutil.Discard, &randomSrc, int64(i))
if err != nil {
b.Fatalf("Error copying at %v: %v", i, err)
}
if copied != int64(i) {
b.Fatalf("Didn't copy enough stuff: %v", copied)
}
}
}
type testWriter struct {
}
func (c *testWriter) Header() http.Header {
return http.Header{}
}
func (c *testWriter) Write(b []byte) (int, error) {
return ioutil.Discard.Write(b)
}
func (c *testWriter) ReadFrom(r io.Reader) (int64, error) {
return io.Copy(ioutil.Discard, r)
}
func (c *testWriter) WriteHeader(code int) {
}
func BenchmarkGeezy(b *testing.B) {
b.StopTimer()
someBytes := make([]byte, 1024*1024*64)
b.SetBytes(int64(len(someBytes)))
w := http.ResponseWriter(&testWriter{})
gz := gzip.NewWriter(w)
defer gz.Close()
w = &geezyWriter{w, gz}
b.StartTimer()
for i := 0; i < b.N; i++ {
io.Copy(w, bytes.NewReader(someBytes))
}
}