forked from valyala/fasthttp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream_test.go
78 lines (68 loc) · 1.55 KB
/
stream_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
package fasthttp
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"testing"
"time"
)
func TestNewStreamReader(t *testing.T) {
ch := make(chan struct{})
r := NewStreamReader(func(w *bufio.Writer) {
fmt.Fprintf(w, "Hello, world\n")
fmt.Fprintf(w, "Line #2\n")
close(ch)
})
data, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
expectedData := "Hello, world\nLine #2\n"
if string(data) != expectedData {
t.Fatalf("unexpected data %q. Expecting %q", data, expectedData)
}
if err = r.Close(); err != nil {
t.Fatalf("unexpected error")
}
select {
case <-ch:
case <-time.After(time.Second):
t.Fatalf("timeout")
}
}
func TestStreamReaderClose(t *testing.T) {
firstLine := "the first line must pass"
ch := make(chan struct{})
r := NewStreamReader(func(w *bufio.Writer) {
fmt.Fprintf(w, "%s", firstLine)
if err := w.Flush(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
fmt.Fprintf(w, "the second line must fail")
if err := w.Flush(); err == nil {
t.Fatalf("expecting error")
}
close(ch)
})
result := firstLine + "the"
buf := make([]byte, len(result))
n, err := io.ReadFull(r, buf)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if n != len(buf) {
t.Fatalf("unexpected number of bytes read: %d. Expecting %d", n, len(buf))
}
if string(buf) != result {
t.Fatalf("unexpected result: %q. Expecting %q", buf, result)
}
if err := r.Close(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
select {
case <-ch:
case <-time.After(time.Second):
t.Fatalf("timeout")
}
}