-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathioutil_test.go
123 lines (104 loc) · 2.4 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
package engineio
import (
"bytes"
"github.com/zhouhui8915/engine.io-go/parser"
"io"
"sync"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
func TestConnIoutil(t *testing.T) {
Convey("Reader", t, func() {
Convey("Normal read", func() {
r := bytes.NewBufferString("\x34\xe6\xb5\x8b\xe8\xaf\x95")
decoder, err := parser.NewDecoder(r)
So(err, ShouldBeNil)
closeChan := make(chan struct{})
reader := newConnReader(decoder, closeChan)
b := make([]byte, 1024)
n, err := reader.Read(b)
So(err, ShouldBeNil)
So(string(b[:n]), ShouldEqual, "测试")
n, err = reader.Read(b)
So(err, ShouldEqual, io.EOF)
Convey("Wait close", func() {
check := make(chan int)
go func() {
err := reader.Close()
if err != nil {
t.Fatal(err)
}
check <- 1
}()
time.Sleep(time.Second / 10) // wait goroutine start
select {
case <-check:
So("should not run here", ShouldEqual, "")
default:
}
<-closeChan
time.Sleep(time.Second / 10) // wait goroutine end
select {
case <-check:
default:
So("should not run here", ShouldEqual, "")
}
Convey("Close again", func() {
err := reader.Close()
So(err, ShouldBeNil)
})
})
})
})
Convey("Wrtier", t, func() {
Convey("Normal write", func() {
locker := sync.Mutex{}
w := bytes.NewBuffer(nil)
locker.Lock()
writer := newConnWriter(writeCloser{w}, &locker)
_, err := writer.Write([]byte("abc"))
So(err, ShouldBeNil)
So(w.String(), ShouldEqual, "abc")
writer.Close()
})
Convey("Sync", func() {
locker := sync.Mutex{}
w1 := bytes.NewBuffer(nil)
locker.Lock()
writer1 := newConnWriter(writeCloser{w1}, &locker)
check := make(chan int)
go func() {
w2 := bytes.NewBuffer(nil)
locker.Lock()
writer2 := newConnWriter(writeCloser{w2}, &locker)
defer writer2.Close()
check <- 1
}()
time.Sleep(time.Second / 10)
select {
case <-check:
So("should not run here", ShouldEqual, "")
default:
}
err := writer1.Close()
So(err, ShouldBeNil)
time.Sleep(time.Second / 10) // wait goroutine end
select {
case <-check:
default:
So("should not run here", ShouldEqual, "")
}
Convey("Close again", func() {
err := writer1.Close()
So(err, ShouldBeNil)
})
})
})
}
type writeCloser struct {
io.Writer
}
func (w writeCloser) Close() error {
return nil
}