-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcancelreader_default_test.go
73 lines (64 loc) · 1.41 KB
/
cancelreader_default_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
//go:build !windows
// +build !windows
package cancelreader
import (
"os"
"testing"
"time"
)
func TestReader(t *testing.T) {
pr, pw, err := os.Pipe()
if err != nil {
t.Errorf("expected no error, but got %s", err)
}
defer pw.Close()
defer pr.Close()
cr, err := NewReader(pr)
if err != nil {
t.Errorf("expected no error, but got %s", err)
}
msg := "hello"
n, err := pw.Write([]byte(msg))
if n != 5 {
t.Errorf("expected 5 bytes written but got %d", n)
}
if err != nil {
t.Errorf("expected no error, but got %s", err)
}
done := make(chan struct{})
go func() {
defer close(done)
p := make([]byte, 1)
n, err = cr.Read(p)
}()
if !cr.Cancel() {
t.Errorf("expected cancellation to be success")
}
select {
case <-done:
case <-time.After(100 * time.Millisecond):
t.Errorf("expected cancellation to unblock reader")
}
if n != 0 {
t.Errorf("expected 0 bytes read but got %d", n)
}
if err != ErrCanceled {
t.Errorf("expected cancel error but got %s", err)
}
// Test that read is still possible after cancellation.
cr, err = NewReader(pr)
if err != nil {
t.Errorf("expected no error, but got %s", err)
}
p := make([]byte, 5)
n, err = cr.Read(p)
if n != 5 {
t.Errorf("expected 5 bytes written but got %d", n)
}
if err != nil {
t.Errorf("expected no error, but got %s", err)
}
if string(p[:n]) != msg[:n] {
t.Errorf("expected to read %q but got %q", msg[:n], string(p[:n]))
}
}