-
Notifications
You must be signed in to change notification settings - Fork 76
/
stream_request.go
122 lines (109 loc) · 2.53 KB
/
stream_request.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
package sharedtest
import (
"bufio"
"context"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/launchdarkly/eventsource"
"github.com/stretchr/testify/assert"
)
// StreamRecorder is an extension of ResponseRecorder to handle streaming content.
type StreamRecorder struct {
*bufio.Writer
*httptest.ResponseRecorder
}
func (r StreamRecorder) Write(data []byte) (int, error) {
return r.Writer.Write(data)
}
func (r StreamRecorder) Flush() {
_ = r.Writer.Flush()
}
func NewStreamRecorder() (StreamRecorder, io.Reader) {
reader, writer := io.Pipe()
recorder := httptest.NewRecorder()
return StreamRecorder{
ResponseRecorder: recorder,
Writer: bufio.NewWriter(writer),
}, reader
}
// WithStreamRequest makes a request that should receive an SSE stream, and calls the given code
// with a channel that will read from that stream. A nil value is pushed to the channel when the
// stream closes or encounters an error.
func WithStreamRequest(
t *testing.T,
req *http.Request,
handler http.Handler,
action func(<-chan eventsource.Event),
) *http.Response {
w, bodyReader := NewStreamRecorder()
wg := sync.WaitGroup{}
wg.Add(1)
eventCh := make(chan eventsource.Event, 10)
ctx, cancelRequest := context.WithCancel(context.Background())
reqWithContext := req.WithContext(ctx)
go func() {
handler.ServeHTTP(w, reqWithContext)
assert.Equal(t, http.StatusOK, w.Code)
AssertStreamingContentType(t, w.Header())
eventCh <- nil
wg.Done()
}()
dec := eventsource.NewDecoder(bodyReader)
go func() {
gotEvent := false
for {
event, err := dec.Decode()
if err == nil {
eventCh <- event
gotEvent = true
} else {
if !gotEvent {
assert.NoError(t, err)
}
eventCh <- nil
return
}
}
}()
action(eventCh)
cancelRequest()
wg.Wait()
return w.Result()
}
func WithStreamRequestLines(
t *testing.T,
req *http.Request,
handler http.Handler,
action func(<-chan string),
) *http.Response {
w, bodyReader := NewStreamRecorder()
wg := sync.WaitGroup{}
wg.Add(1)
linesCh := make(chan string, 10)
ctx, cancelRequest := context.WithCancel(context.Background())
reqWithContext := req.WithContext(ctx)
go func() {
handler.ServeHTTP(w, reqWithContext)
linesCh <- ""
assert.Equal(t, http.StatusOK, w.Code)
AssertStreamingContentType(t, w.Header())
wg.Done()
}()
r := bufio.NewReader(bodyReader)
go func() {
for {
line, err := r.ReadString('\n')
linesCh <- line
if err != nil {
return
}
}
}()
action(linesCh)
cancelRequest()
wg.Wait()
return w.Result()
}