-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathapi_test.go
492 lines (380 loc) · 11 KB
/
api_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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package deriv
import (
"bufio"
"context"
"log"
"os"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/ksysoev/deriv-api/schema"
)
func TestNewDerivAPI(t *testing.T) {
// Valid endpoint and origin
endpoint := "wss://example.com/ws"
origin := "https://example.com"
appID := 123
lang := "en"
api, err := NewDerivAPI(endpoint, appID, lang, origin)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if api.Endpoint.String() != endpoint+"?app_id=123&l=en" {
t.Errorf("Unexpected endpoint: got %v, want %v", api.Endpoint.String(), endpoint)
}
if api.Origin.String() != origin {
t.Errorf("Unexpected origin: got %v, want %v", api.Origin.String(), origin)
}
// Invalid endpoint scheme
endpoint = "https://example.com/ws"
origin = "https://example.com"
appID = 123
lang = "en"
if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}
// Invalid app ID
endpoint = "wss://example.com/ws"
origin = "https://example.com"
appID = -1
lang = "en"
if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}
// Invalid language
endpoint = "wss://example.com/ws"
origin = "https://example.com"
appID = 123
lang = "eng"
if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}
// Invalid endpoint URL
endpoint = ":invalid:"
origin = "https://example.com"
appID = 123
lang = "en"
if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}
// Invalid origin URL
endpoint = "wss://example.com/ws"
origin = ":invalid:"
appID = 123
lang = "en"
if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}
}
func TestGetNextRequestID(t *testing.T) {
api := &Client{lastRequestID: 0}
requestIDs := make(map[int]bool)
orderedRequestIDs := make([]int, 0)
numRequests := 5
for i := 0; i < numRequests; i++ {
requestID := api.getNextRequestID()
if _, ok := requestIDs[requestID]; ok {
t.Errorf("Request ID %d already used", requestID)
}
requestIDs[requestID] = true
orderedRequestIDs = append(orderedRequestIDs, requestID)
}
if len(requestIDs) != numRequests {
t.Errorf("Expected %d unique request IDs, but got %d", numRequests, len(requestIDs))
}
lastID := 0
for _, id := range orderedRequestIDs {
if id <= lastID {
t.Errorf("Request IDs not increasing, lastID=%d currentID=%d", lastID, id)
}
lastID = id
}
}
func TestConnect(t *testing.T) {
server := newMockWSServer(echoHandler)
url := "ws://" + server.Listener.Addr().String()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")
err := api.Connect()
if err != nil {
t.Errorf("Failed to connect to mocked WebSocket server: %v", err)
}
if api.ws == nil {
t.Errorf("WebSocket connection not established")
}
ws1 := api.ws
err = api.Connect()
if err != nil {
t.Errorf("Failed to connect to mocked WebSocket server: %v", err)
}
if api.ws != ws1 {
t.Errorf("Expected WebSocket connection to be the same, but got a different connection")
}
// Close the WebSocket connection and test that we can't connect again
server.Close()
api, _ = NewDerivAPI(url, 123, "en", "http://example.com")
err = api.Connect()
if err == nil {
t.Errorf("Expected fail to connect but didn't get any error")
}
if api.ws != nil {
t.Errorf("Expected fail to connect, but WebSocket connection was established")
}
}
func TestDisconnect(t *testing.T) {
server := newMockWSServer(echoHandler)
url := "ws://" + server.Listener.Addr().String()
defer server.Close()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")
api.Disconnect()
if api.ws != nil {
t.Errorf("Expected WebSocket connection to be nil, but got a connection")
}
err := api.Connect()
if err != nil {
t.Errorf("Failed to connect to mocked WebSocket server: %v", err)
}
if api.ws == nil {
t.Errorf("WebSocket connection not established")
}
api.Disconnect()
if api.ws != nil {
t.Errorf("Expected WebSocket connection to be nil, but got a connection")
}
}
func TestSend(t *testing.T) {
server := newMockWSServer(echoHandler)
url := "ws://" + server.Listener.Addr().String()
defer server.Close()
ctx := context.Background()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")
err := api.Connect()
if err != nil {
t.Errorf("Failed to connect to mocked WebSocket server: %v", err)
}
if api.ws == nil {
t.Errorf("WebSocket connection not established")
}
respChan, err := api.Send(ctx, 1, struct {
ReqID int `json:"req_id"`
}{1})
if err != nil {
t.Errorf("Failed to send message: %v", err)
}
if respChan == nil {
t.Errorf("Response channel is nil")
}
msg := <-respChan
testMsg := "{\"req_id\":1}"
if string(msg) != testMsg {
t.Errorf("Expected message to be %s, but got %s", testMsg, msg)
}
}
func TestSendToDisconnectedConnection(t *testing.T) {
server := newMockWSServer(echoHandler)
url := "ws://" + server.Listener.Addr().String()
server.Close()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")
ctx := context.Background()
respChan, err := api.Send(ctx, 1, struct {
ReqID int `json:"req_id"`
}{1})
if err == nil {
t.Errorf("Expected error, got nil")
}
if respChan != nil {
t.Errorf("Expected response channel to be nil, but got a channel")
}
}
func TestSendReqWhichNobodyWaits(t *testing.T) {
server := newMockWSServer(echoHandler)
url := "ws://" + server.Listener.Addr().String()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")
ctx := context.Background()
respChan, err := api.Send(ctx, 2, struct {
ReqID int `json:"req_id"`
}{1})
if err != nil {
t.Errorf("Failed to send message: %v", err)
}
select {
case <-respChan:
t.Errorf("Expected no response, but got a response")
case <-time.After(time.Millisecond):
}
}
func TestSendRequestTimeout(t *testing.T) {
server := newMockWSServer(
onMessageHanler(func(_ *websocket.Conn, _ websocket.MessageType, _ []byte) {
time.Sleep(time.Second)
}),
)
defer server.Close()
url := "ws://" + server.Listener.Addr().String()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
reqID := 1
req := schema.Ping{Ping: 1, ReqId: &reqID}
defer cancel()
var resp schema.PingResp
err := api.SendRequest(ctx, reqID, req, &resp)
if err != context.DeadlineExceeded {
t.Errorf("Expected timeout error, got %v", err)
}
}
func TestSendRequestAndGotInvalidJSON(t *testing.T) {
testResp := `{Corrupted JSON}`
server := newMockWSServer(
onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) {
err := ws.Write(context.Background(), websocket.MessageText, []byte(testResp))
if err != nil {
return
}
time.Sleep(time.Second) // to keep the connection open
}))
defer server.Close()
url := "ws://" + server.Listener.Addr().String()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")
err := api.Connect()
if err != nil {
t.Errorf("Failed to connect to mocked WebSocket server: %v", err)
}
ctx := context.Background()
respChan, err := api.Send(ctx, 2, struct {
ReqID int `json:"req_id"`
}{1})
if err != nil {
t.Errorf("Failed to send message: %v", err)
}
select {
case _, ok := <-respChan:
if ok {
t.Errorf("Expected no response, but got a response")
}
case <-time.After(time.Millisecond):
}
}
func TestSendRequest(t *testing.T) {
testResp := `{
"echo_req": {
"ping": 1,
"req_id": 1
},
"msg_type": "ping",
"ping": "pong",
"req_id": 1
}`
server := newMockWSServer(
onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) {
err := ws.Write(context.Background(), websocket.MessageText, []byte(testResp))
if err != nil {
return
}
time.Sleep(time.Second) // to keep the connection open
}))
defer server.Close()
url := "ws://" + server.Listener.Addr().String()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")
err := api.Connect()
if err != nil {
t.Errorf("Failed to connect to mocked WebSocket server: %v", err)
}
reqID := 1
req := schema.Ping{Ping: 1, ReqId: &reqID}
ctx := context.Background()
var resp schema.PingResp
err = api.SendRequest(ctx, reqID, req, &resp)
if err != nil {
t.Errorf("Failed to send message: %v", err)
}
if *resp.Ping != "pong" {
t.Errorf("Expected response to be pong, but got %s", *resp.Ping)
}
}
func TestSendRequestFailed(t *testing.T) {
server := newMockWSServer(
onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) {
err := ws.Write(context.Background(), websocket.MessageText, []byte(""))
if err != nil {
return
}
time.Sleep(time.Second) // to keep the connection open
}))
url := "ws://" + server.Listener.Addr().String()
server.Close()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")
reqID := 1
req := schema.Ping{Ping: 1, ReqId: &reqID}
ctx := context.Background()
var resp schema.PingResp
err := api.SendRequest(ctx, reqID, req, &resp)
if err == nil {
t.Errorf("Expected error, got nil")
}
}
func TestKeepConnectionAlive(t *testing.T) {
resChan := make(chan string)
testResp := `{
"echo_req": {
"ping": 1,
"req_id": 1
},
"msg_type": "ping",
"ping": "pong",
"req_id": 1
}`
server := newMockWSServer(
onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, msg []byte) {
resChan <- string(msg)
err := ws.Write(context.Background(), websocket.MessageText, []byte(testResp))
if err != nil {
return
}
time.Sleep(time.Second) // to keep the connection open
}))
url := "ws://" + server.Listener.Addr().String()
defer server.Close()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com", KeepAlive)
api.keepAliveInterval = time.Millisecond
if err := api.Connect(); err != nil {
t.Errorf("Failed to connect to mocked WebSocket server: %v", err)
}
select {
case msg := <-resChan:
if msg == "" {
t.Errorf("Expected to receive ping request, but got nothing")
}
case <-time.After(time.Millisecond * 2):
t.Errorf("Expected to receive ping request, but got nothing")
}
api.Disconnect()
if err := api.Connect(); err != nil {
t.Errorf("Failed to connect to mocked WebSocket server: %v", err)
}
select {
case msg, ok := <-resChan:
if ok && msg != "" {
t.Errorf("Expected to not receive ping request, but got n%sn>", msg)
}
case <-time.After(time.Millisecond * 2):
}
}
func TestDebugLogs(t *testing.T) {
reader, writer, err := os.Pipe()
if err != nil {
t.Errorf("Failed to create pipe: %v", err)
}
defer reader.Close()
log.SetOutput(writer)
scanner := bufio.NewScanner(reader)
server := newMockWSServer(echoHandler)
url := "ws://" + server.Listener.Addr().String()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com", Debug)
_ = api.Connect()
scanner.Scan()
got := scanner.Text()
want := "Connecting to " + url
if !strings.Contains(got, want) {
t.Errorf("Expected log to contain %s, but got %s", want, got)
}
}