forked from zema1/suo5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader_test.go
91 lines (78 loc) · 1.92 KB
/
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
87
88
89
90
91
package netrans
import (
"bytes"
"context"
"github.com/stretchr/testify/require"
"io"
"io/ioutil"
"strings"
"testing"
"time"
)
func TestReader(t *testing.T) {
assert := require.New(t)
ctx := context.Background()
data := []byte("hello")
tr := NewTimeoutReadCloser(ctx, io.NopCloser(bytes.NewReader(data)), time.Second*3)
buf := make([]byte, 1024)
now := time.Now()
n, err := tr.Read(buf)
assert.Nil(err)
assert.True(time.Since(now).Seconds() < 1)
assert.Equal(buf[:n], data)
_ = tr.Close()
pr, pw := io.Pipe()
tr = NewTimeoutReadCloser(ctx, pr, time.Second*3)
now = time.Now()
_, err = tr.Read(buf)
assert.ErrorIs(err, ErrReadTimeout)
assert.True(time.Since(now).Seconds() > 3)
_, _ = pw.Write(data)
now = time.Now()
_, err = tr.Read(buf)
assert.Nil(err)
assert.True(time.Since(now).Seconds() < 1)
assert.Equal(buf[:n], data)
_ = pw.Close()
_, err = tr.Read(buf)
assert.ErrorIs(err, io.EOF)
_, err = tr.Read(buf)
assert.ErrorIs(err, ErrReaderClosed)
_ = tr.Close()
}
func TestChannelReader(t *testing.T) {
assert := require.New(t)
ch := make(chan []byte, 1)
r := NewChannelReader(ch)
buf := make([]byte, 2)
ch <- []byte("hel")
n, err := r.Read(buf)
assert.Equal(n, 2)
assert.Nil(err)
assert.Equal(buf[:n], []byte("he"))
n, err = r.Read(buf)
assert.Equal(n, 1)
assert.Nil(err)
assert.Equal(buf[:n], []byte("l"))
go func() {
time.Sleep(time.Second * 2)
ch <- []byte("e")
}()
now := time.Now()
n, err = r.Read(buf)
assert.Nil(err)
assert.True(time.Since(now).Seconds() >= 2)
assert.Equal(n, 1)
assert.Equal(buf[:n], []byte("e"))
close(ch)
_, err = r.Read(buf)
assert.ErrorIs(err, io.EOF)
}
func TestMultiReaderClosed(t *testing.T) {
assert := require.New(t)
rc := MultiReadCloser(ioutil.NopCloser(strings.NewReader("hello")), ioutil.NopCloser(strings.NewReader("world")))
data, err := ioutil.ReadAll(rc)
assert.Nil(err)
assert.Equal(data, []byte("helloworld"))
assert.Nil(rc.Close())
}