-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathlocalserver_test.go
More file actions
441 lines (418 loc) · 18.8 KB
/
localserver_test.go
File metadata and controls
441 lines (418 loc) · 18.8 KB
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Copyright 2022-2026 Salesforce, Inc.
//
// 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.
package platform
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/gorilla/websocket"
"github.com/slackapi/slack-cli/internal/api"
"github.com/slackapi/slack-cli/internal/hooks"
"github.com/slackapi/slack-cli/internal/shared"
"github.com/slackapi/slack-cli/internal/slackcontext"
"github.com/slackapi/slack-cli/internal/slackerror"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
var WebsocketDialerDial = &websocketDialerDial
func Test_LocalServer_Start(t *testing.T) {
for name, tc := range map[string]struct {
Setup func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock)
Test func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock)
wsHandler func(w http.ResponseWriter, r *http.Request)
fakeDialer func(conn *WebSocketConnMock) func(d *websocket.Dialer, urlStr string,
requestHeader http.Header) (WebSocketConnection, *http.Response, error)
}{
"should return an error if there was a problem asking for a WebSocket connection URL": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
cm.API.On("ConnectionsOpen", mock.Anything, mock.Anything).Return(api.AppsConnectionsOpenResult{}, slackerror.New("no can do, pipes are clogged"))
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
require.ErrorContains(t, server.Start(ctx), "pipes are clogged")
},
},
"should return an error if there was a problem connecting to a WebSocket connection URL": {
wsHandler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
require.ErrorContains(t, server.Start(ctx), "bad handshake")
},
},
"should return an error if there was a problem reading from WebSocket": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
conn.On("ReadMessage").Return(0, []byte{}, slackerror.New("oh no"))
},
fakeDialer: func(conn *WebSocketConnMock) func(d *websocket.Dialer, urlStr string, requestHeader http.Header) (WebSocketConnection, *http.Response, error) {
return func(d *websocket.Dialer, urlStr string, requestHeader http.Header) (WebSocketConnection, *http.Response, error) {
return conn, nil, nil
}
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
require.ErrorContains(t, server.Start(ctx), "oh no")
},
},
"should re-establish connection if disconnect message received": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("{\"type\":\"disconnect\"}"), nil).Once()
conn.On("ReadMessage").Return(websocket.CloseMessage, []byte{}, &websocket.CloseError{Code: websocket.CloseNormalClosure, Text: "byebye"}).Once()
},
fakeDialer: func(conn *WebSocketConnMock) func(d *websocket.Dialer, urlStr string, requestHeader http.Header) (WebSocketConnection, *http.Response, error) {
return func(d *websocket.Dialer, urlStr string, requestHeader http.Header) (WebSocketConnection, *http.Response, error) {
return conn, nil, nil
}
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
require.ErrorContains(t, server.Start(ctx), slackerror.ErrLocalAppRunCleanExit)
// Once to re-establish post-disconnect message and once when close message received
conn.AssertNumberOfCalls(t, "Close", 2)
},
},
"should re-establish connection if unexpected, non-JSON response received": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
cm.Config.DebugEnabled = true
// Simulate TWO bad messages received, followed by a close message
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("CANCELLED: Failed to read message"), nil).Once()
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("CANCELLED: Failed to read message"), nil).Once()
conn.On("ReadMessage").Return(websocket.CloseMessage, []byte{}, &websocket.CloseError{Code: websocket.CloseNormalClosure, Text: "byebye"}).Once()
},
fakeDialer: func(conn *WebSocketConnMock) func(d *websocket.Dialer, urlStr string, requestHeader http.Header) (WebSocketConnection, *http.Response, error) {
return func(d *websocket.Dialer, urlStr string, requestHeader http.Header) (WebSocketConnection, *http.Response, error) {
return conn, nil, nil
}
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
require.ErrorContains(t, server.Start(ctx), slackerror.ErrLocalAppRunCleanExit)
// Expectation is each WS message we configured in Setup
// would cause the TCP connection to be closed (3 times)
// but the connection should be re-established only twice (once for each simulated error)
conn.AssertNumberOfCalls(t, "Close", 3)
},
},
} {
t.Run(name, func(t *testing.T) {
wsFakeURL := "http://slack.com/websocketzzzz"
if tc.wsHandler != nil {
ts := httptest.NewServer(http.HandlerFunc(tc.wsHandler))
defer ts.Close()
wsFakeURL = "ws" + strings.TrimPrefix(ts.URL, "http")
}
// Create mocks
ctx := slackcontext.MockContext(t.Context())
conn := NewWebSocketConnMock()
clientsMock := shared.NewClientsMock()
// Create clients that is mocked for testing
clients := shared.NewClientFactory(clientsMock.MockClientFactory(), func(cf *shared.ClientFactory) {
cf.SDKConfig = hooks.NewSDKConfigMock()
})
if tc.Setup != nil {
tc.Setup(t, clientsMock, clients, conn)
}
clientsMock.API.On("ConnectionsOpen", mock.Anything, mock.Anything).Return(api.AppsConnectionsOpenResult{URL: wsFakeURL}, nil)
// Setup default mock actions
conn.AddDefaultMocks()
clientsMock.AddDefaultMocks()
localContext := LocalHostedContext{
BotAccessToken: "ABC1234",
AppID: "A12345",
TeamID: "justiceleague",
}
server := LocalServer{
clients: clients,
token: "ABC123",
localHostedContext: localContext,
cliConfig: clients.SDKConfig,
appFilePath: "",
Connection: conn,
delegateCmd: nil,
delegateCmdMutex: sync.Mutex{},
}
if tc.fakeDialer != nil {
orig := *WebsocketDialerDial
websocketDialerDial = tc.fakeDialer(conn)
defer func() {
websocketDialerDial = orig
}()
}
tc.Test(t, ctx, clientsMock, &server, conn)
})
}
}
func Test_LocalServer_Listen(t *testing.T) {
for name, tc := range map[string]struct {
Setup func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock)
Test func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock)
}{
"should return and send special clean exit error if context is canceled": {
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
ctx2, cancel := context.WithCancel(ctx)
cancel()
errChan := make(chan error)
done := make(chan bool)
go server.Listen(ctx2, errChan, done)
select {
case err := <-errChan:
assert.True(t, slackerror.Is(err, slackerror.ErrLocalAppRunCleanExit))
case <-done:
assert.Fail(t, "unexpected done channel signalled")
}
},
},
"should return and send an error if ReadMessage has an unexpected error": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
conn.On("ReadMessage").Return(0, []byte{}, slackerror.New("oh no"))
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
errChan := make(chan error)
done := make(chan bool)
go server.Listen(ctx, errChan, done)
select {
case err := <-errChan:
assert.ErrorContains(t, err, "oh no")
case <-done:
assert.Fail(t, "unexpected done channel signalled")
}
},
},
"should return and send special clean exit error if ReadMessage receives a normal closure message": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
conn.On("ReadMessage").Return(websocket.CloseMessage, []byte{}, &websocket.CloseError{Code: websocket.CloseNormalClosure, Text: "byebye"})
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
errChan := make(chan error)
done := make(chan bool)
go server.Listen(ctx, errChan, done)
select {
case err := <-errChan:
assert.True(t, slackerror.Is(err, slackerror.ErrLocalAppRunCleanExit))
case <-done:
assert.Fail(t, "unexpected done channel signalled")
}
},
},
"should signal done=false (signalling a 'plz re-restablish socket connection') if we receive a non-JSON message": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("cache_error"), nil)
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
errChan := make(chan error)
done := make(chan bool)
go server.Listen(ctx, errChan, done)
select {
case err := <-errChan:
assert.Nil(t, err)
case quit := <-done:
assert.False(t, quit)
}
},
},
"should return and send on done if a disconnect message type is received": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("{\"type\":\"disconnect\"}"), nil)
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
errChan := make(chan error)
done := make(chan bool)
go server.Listen(ctx, errChan, done)
select {
case err := <-errChan:
assert.Fail(t, "unexpected err channel signalled", err)
case quit := <-done:
assert.False(t, quit)
}
},
},
"should return and send an error if there was a problem retrieving the SDK start hook": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("{\"type\":\"event\",\"payload\":{}}"), nil)
// Force the start hook to return an error
// TODO: should probably create a hookscript mock instead of doing this.
clients.SDKConfig.Hooks.Start = hooks.HookScript{Command: "", Name: "start"}
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
errChan := make(chan error)
done := make(chan bool)
go server.Listen(ctx, errChan, done)
select {
case err := <-errChan:
assert.ErrorContains(t, err, "command for 'start' was not found")
case <-done:
assert.Fail(t, "unexpected done channel signalled")
}
},
},
"should send a websocket response message if socket event message received was passed to start hook and hook returns successfully": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
// TODO: should probably create a hookscript mock instead of doing this.
clients.SDKConfig.Hooks.Start = hooks.HookScript{Command: "echo '{}'", Name: "start"}
// Simulate receiving an event, then a disconnect message
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("{\"type\":\"event\",\"payload\":{}}"), nil).Once()
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("{\"type\":\"disconnect\"}"), nil).Once()
cm.HookExecutor.On("Execute", mock.Anything, mock.Anything).Return("{}", nil)
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
errChan := make(chan error)
done := make(chan bool)
go server.Listen(ctx, errChan, done)
select {
case err := <-errChan:
assert.Fail(t, "unexpected err channel signalled", err)
case <-done:
conn.AssertNumberOfCalls(t, "WriteMessage", 1)
}
},
},
"should not send a websocket response message if socket event message received led to start hook error": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
// TODO: should probably create a hookscript mock instead of doing this.
clients.SDKConfig.Hooks.Start = hooks.HookScript{Command: "echo '{}'", Name: "start"}
// Simulate receiving an event, then a disconnect message
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("{\"type\":\"event\",\"payload\":{}}"), nil).Once()
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("{\"type\":\"disconnect\"}"), nil).Once()
cm.HookExecutor.On("Execute", mock.Anything, mock.Anything).Return("{}", slackerror.New("typescript error, probably"))
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
errChan := make(chan error)
done := make(chan bool)
go server.Listen(ctx, errChan, done)
select {
case err := <-errChan:
assert.Fail(t, "unexpected err channel signalled", err)
case <-done:
conn.AssertNumberOfCalls(t, "WriteMessage", 0)
}
},
},
"should return and send an error if there was a problem sending a websocket message": {
Setup: func(t *testing.T, cm *shared.ClientsMock, clients *shared.ClientFactory, conn *WebSocketConnMock) {
// TODO: should probably create a hookscript mock instead of doing this.
clients.SDKConfig.Hooks.Start = hooks.HookScript{Command: "echo '{}'", Name: "start"}
// Simulate receiving an event, then a disconnect message
conn.On("ReadMessage").Return(websocket.TextMessage, []byte("{\"type\":\"event\",\"payload\":{}}"), nil).Once()
cm.HookExecutor.On("Execute", mock.Anything, mock.Anything).Return("{}", nil)
conn.On("WriteMessage", mock.Anything, mock.Anything).Return(slackerror.New("socket pipe severed"))
},
Test: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, server *LocalServer, conn *WebSocketConnMock) {
errChan := make(chan error)
done := make(chan bool)
go server.Listen(ctx, errChan, done)
select {
case err := <-errChan:
assert.ErrorContains(t, err, "socket pipe severed")
case <-done:
assert.Fail(t, "unexpected done channel signalled")
}
},
},
} {
t.Run(name, func(t *testing.T) {
// Create mocks
ctx := slackcontext.MockContext(t.Context())
conn := NewWebSocketConnMock()
clientsMock := shared.NewClientsMock()
// Create clients that is mocked for testing
clients := shared.NewClientFactory(clientsMock.MockClientFactory(), func(cf *shared.ClientFactory) {
cf.SDKConfig = hooks.NewSDKConfigMock()
})
if tc.Setup != nil {
tc.Setup(t, clientsMock, clients, conn)
}
// Setup default mock actions
conn.AddDefaultMocks()
clientsMock.AddDefaultMocks()
localContext := LocalHostedContext{
BotAccessToken: "ABC1234",
AppID: "A12345",
TeamID: "justiceleague",
}
server := LocalServer{
clients: clients,
token: "ABC123",
localHostedContext: localContext,
cliConfig: clients.SDKConfig,
appFilePath: "",
Connection: conn,
delegateCmd: nil,
delegateCmdMutex: sync.Mutex{},
}
tc.Test(t, ctx, clientsMock, &server, conn)
})
}
}
func Test_sendWebSocketMessage(t *testing.T) {
t.Run("should error when linkResponse param is nil", func(t *testing.T) {
conn := NewWebSocketConnMock()
conn.AddDefaultMocks()
err := sendWebSocketMessage(conn, nil)
require.Error(t, err)
conn.AssertNotCalled(t, "WriteMessage", mock.Anything, mock.Anything)
})
t.Run("should write a message to the connection even when payload param is empty JSON", func(t *testing.T) {
conn := NewWebSocketConnMock()
conn.AddDefaultMocks()
linkResponse := LinkResponse{
EnvelopeID: validEnvelopeIDMock,
Payload: json.RawMessage("{}"),
}
expectedMessageData, err := json.Marshal(linkResponse)
require.NoError(t, err)
err = sendWebSocketMessage(conn, &linkResponse)
require.NoError(t, err)
conn.AssertCalled(t, "WriteMessage", websocket.TextMessage, expectedMessageData)
})
// When payload param is populated JSON
t.Run("When payload param is populated JSON", func(t *testing.T) {
conn := NewWebSocketConnMock()
conn.AddDefaultMocks()
linkResponse := LinkResponse{
EnvelopeID: validEnvelopeIDMock,
Payload: json.RawMessage("{ \"hello\": \"world\" }"),
}
expectedMessageData, err := json.Marshal(linkResponse)
require.NoError(t, err)
err = sendWebSocketMessage(conn, &linkResponse)
require.NoError(t, err)
conn.AssertCalled(t, "WriteMessage", websocket.TextMessage, expectedMessageData)
})
t.Run("should error when payload param is invalid JSON", func(t *testing.T) {
conn := NewWebSocketConnMock()
conn.AddDefaultMocks()
linkResponse := LinkResponse{
EnvelopeID: validEnvelopeIDMock,
Payload: json.RawMessage("hello world"),
}
err := sendWebSocketMessage(conn, &linkResponse)
require.Error(t, err)
conn.AssertNotCalled(t, "WriteMessage", mock.Anything, mock.Anything)
})
t.Run("should error when writing to websocket fails", func(t *testing.T) {
expectedError := fmt.Errorf("Error writing to websocket")
conn := NewWebSocketConnMock()
conn.On("WriteMessage", mock.Anything, mock.Anything).Return(expectedError)
conn.AddDefaultMocks()
linkResponse := LinkResponse{
EnvelopeID: validEnvelopeIDMock,
Payload: json.RawMessage("{}"),
}
err := sendWebSocketMessage(conn, &linkResponse)
require.ErrorIs(t, err, expectedError)
conn.AssertCalled(t, "WriteMessage", mock.Anything, mock.Anything)
})
}