-
Notifications
You must be signed in to change notification settings - Fork 13
/
server_integration_test.go
332 lines (313 loc) · 8.76 KB
/
server_integration_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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build serverintegration
// These tests are integration tests for when the api-server is served by the websocket server
package swaggersocket
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"testing"
"time"
"github.com/gorilla/websocket"
uuid "github.com/satori/go.uuid"
"github.com/stretchr/testify/assert"
)
var (
socketserver *WebsocketServer
socketclient *WebsocketClient
done chan struct{}
debugCh = make(chan string)
)
func simpleHandler(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte("Hello, Dolores!"))
}
func chunkedHandler(rw http.ResponseWriter, req *http.Request) {
flusher, ok := rw.(http.Flusher)
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
for i := 1; i <= 10; i++ {
fmt.Fprintf(rw, "Chunk #%d\n", i)
flusher.Flush()
time.Sleep(250 * time.Millisecond)
}
}
func closeNotifiedChunkedHandler(rw http.ResponseWriter, req *http.Request) {
flusher, ok := rw.(http.Flusher)
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
notify := rw.(http.CloseNotifier).CloseNotify()
for i := 1; i <= 10; i++ {
select {
case <-notify:
debugCh <- "Handler was notified of the client close"
log.Println("connection closed...exiting handler")
return
default:
fmt.Fprintf(rw, "Chunk #%d\n", i)
flusher.Flush()
time.Sleep(1 * time.Second)
}
}
}
func startSocketServer() (*WebsocketServer, chan struct{}) {
opts := SocketServerOpts{
Addr: ":9090",
KeepAlive: true,
}
wsServer := NewWebSocketServer(opts)
ch, err := wsServer.EventStream()
if err != nil {
panic(err)
}
m := http.NewServeMux()
m.HandleFunc("/simple/", simpleHandler)
m.HandleFunc("/chunked/", chunkedHandler)
m.HandleFunc("/closenotifiedchunked/", closeNotifiedChunkedHandler)
done := make(chan struct{})
go func() {
for {
select {
case event := <-ch:
if event.EventType == ConnectionReceived {
conn := wsServer.connectionFromConnID(event.ConnectionId)
conn.Serve(context.Background(), m)
}
case <-done:
return
}
}
}()
return wsServer, done
}
func TestMain(m *testing.M) {
socketserver, done = startSocketServer()
u, _ := url.Parse("ws://localhost:9090/")
opts := SocketClientOpts{
URL: u,
KeepAlive: true,
}
socketclient = NewWebSocketClient(opts)
code := m.Run()
close(done)
os.Exit(code)
}
func TestSimpleHandlerSuccess(t *testing.T) {
err := socketclient.Connect()
assert.Nil(t, err)
for i := 0; i < 4; i++ {
req, _ := http.NewRequest(http.MethodGet, "ws://localhost:9090/simple/", nil)
cid := uuid.NewV4().String()
req.Header.Set("X-Correlation-Id", cid)
err := socketclient.Connection().WriteRequest(req)
assert.Nil(t, err)
resp, err := socketclient.Connection().ReadResponse()
assert.Nil(t, err)
assert.NotNil(t, resp)
assert.Equal(t, cid, resp.Header.Get("X-Correlation-Id"))
b, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
assert.Nil(t, err)
assert.Equal(t, "Hello, Dolores!", string(b))
}
connID := socketclient.Connection().ID()
socketclient.Connection().Close()
// give some time for the server to unregister connection
// ToDo find a better way to do this
time.Sleep(1 * time.Second)
assert.Nil(t, socketserver.connectionFromConnID(connID))
}
func TestChunkedHandlerSuccess(t *testing.T) {
err := socketclient.Connect()
assert.Nil(t, err)
for i := 0; i < 2; i++ {
req, _ := http.NewRequest(http.MethodGet, "ws://localhost:9090/chunked/", nil)
cid := uuid.NewV4().String()
req.Header.Set("X-Correlation-Id", cid)
err := socketclient.Connection().WriteRequest(req)
assert.Nil(t, err)
resp, err := socketclient.Connection().ReadResponse()
assert.Nil(t, err)
assert.NotNil(t, resp)
assert.Equal(t, cid, resp.Header.Get("X-Correlation-Id"))
readbuf := make([]byte, 4096)
count := 1
for {
//line, err := reader.ReadBytes('\n')
n, err := resp.Body.Read(readbuf)
if n > 0 {
assert.Equal(t, fmt.Sprintf("Chunk #%d\n", count), string(bytes.Trim(readbuf, "\x00")))
count++
}
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
}
resp.Body.Close()
}
connID := socketclient.Connection().ID()
socketclient.Connection().Close()
// give some time for the server to unregister connection
// ToDo find a better way to do this
time.Sleep(1 * time.Second)
assert.Nil(t, socketserver.connectionFromConnID(connID))
}
func TestCloseNotifiedChunkedHandlerSuccess(t *testing.T) {
err := socketclient.Connect()
assert.Nil(t, err)
for i := 0; i < 2; i++ {
req, _ := http.NewRequest(http.MethodGet, "ws://localhost:9090/closenotifiedchunked/", nil)
cid := uuid.NewV4().String()
req.Header.Set("X-Correlation-Id", cid)
err := socketclient.Connection().WriteRequest(req)
assert.Nil(t, err)
resp, err := socketclient.Connection().ReadResponse()
assert.Nil(t, err)
assert.NotNil(t, resp)
assert.Equal(t, cid, resp.Header.Get("X-Correlation-Id"))
readbuf := make([]byte, 4096)
count := 1
for {
//line, err := reader.ReadBytes('\n')
n, err := resp.Body.Read(readbuf)
if n > 0 {
assert.Equal(t, fmt.Sprintf("Chunk #%d\n", count), string(bytes.Trim(readbuf, "\x00")))
count++
}
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
}
resp.Body.Close()
}
connID := socketclient.Connection().ID()
socketclient.Connection().Close()
// give some time for the server to unregister connection
// ToDo find a better way to do this
time.Sleep(1 * time.Second)
assert.Nil(t, socketserver.connectionFromConnID(connID))
}
func TestCloseNotifiedChunkedFailureClientSide(t *testing.T) {
err := socketclient.Connect()
// disabling failure detection at the socketclient side
socketclient.Connection().heartBeat.stop()
assert.Nil(t, err)
quit := false
var count int
for i := 0; i < 2; i++ {
req, _ := http.NewRequest(http.MethodGet, "ws://localhost:9090/closenotifiedchunked/", nil)
cid := uuid.NewV4().String()
req.Header.Set("X-Correlation-Id", cid)
err := socketclient.Connection().WriteRequest(req)
assert.Nil(t, err)
resp, err := socketclient.Connection().ReadResponse()
assert.Nil(t, err)
assert.NotNil(t, resp)
assert.Equal(t, cid, resp.Header.Get("X-Correlation-Id"))
readbuf := make([]byte, 4096)
count = 1
for {
//line, err := reader.ReadBytes('\n')
n, err := resp.Body.Read(readbuf)
defer resp.Body.Close()
if count == 3 {
socketclient.conn.conn.UnderlyingConn().Close()
quit = true
break
}
if n > 0 {
assert.Equal(t, fmt.Sprintf("Chunk #%d\n", count), string(bytes.Trim(readbuf, "\x00")))
count++
}
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
}
if quit == true {
break
}
}
select {
case <-time.After(30 * time.Second):
t.Fatal("timed out")
case s := <-debugCh:
assert.Equal(t, "Handler was notified of the client close", s)
}
}
func TestGeneralFailureClientSide(t *testing.T) {
err := socketclient.Connect()
// disabling failure detection at the socketclient side
connectionId := socketclient.Connection().ID()
socketclient.Connection().heartBeat.stop()
assert.Nil(t, err)
// force close the underlying network connection
socketclient.conn.conn.UnderlyingConn().Close()
// the server is expected to detect that and remove the connection from the connection map
success := make(chan bool, 1)
go func() {
for {
if socketserver.connectionFromConnID(connectionId) == nil {
success <- true
return
}
time.Sleep(1 * time.Second)
}
}()
select {
case <-time.After(30 * time.Second):
log.Printf("time out")
t.Fatal("timed out")
case <-success:
}
}
func TestGeneralFailureServerSide(t *testing.T) {
err := socketclient.Connect()
// disabling failure detection at the socketclient side
assert.Nil(t, err)
// force close the underlying network connection
socketclient.conn.conn.UnderlyingConn().Close()
// client should try to reconnect with backoff
success := make(chan bool, 1)
go func() {
for {
if err := socketclient.Connection().conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(10*time.Second)); err == nil {
success <- true
return
}
time.Sleep(1 * time.Second)
}
}()
select {
case <-time.After(20 * time.Second):
t.Fatal("timed out")
case <-success:
}
}