forked from alpacahq/alpaca-trade-api-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_stream.py
More file actions
77 lines (68 loc) · 2.53 KB
/
Copy pathtest_stream.py
File metadata and controls
77 lines (68 loc) · 2.53 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
from alpaca_trade_api.stream import StreamConn
import json
import pytest
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from websocket import WebSocketConnectionClosedException
@patch('websocket.WebSocket')
def test_stream(WebSocket):
class Fake(object):
def __init__(self):
self._state = 'init'
def _start_streaming(self):
for i in range(3):
for stream in self._streams:
yield stream
def send(self, jmsg):
msg = json.loads(jmsg)
if self._state == 'init':
assert msg['action'] == 'authenticate'
self._state = 'authenticated'
elif msg['action'] == 'listen':
assert self._state == 'authenticated'
self._streams = msg['data']['streams']
self._state = 'streaming'
self._streamer = self._start_streaming()
def recv(self):
if self._state == 'authenticated':
return json.dumps({
'stream': 'authentication',
'data': {
'status': 'authenticated',
}
}).encode()
elif self._state == 'streaming':
try:
stream = next(self._streamer)
except StopIteration:
raise WebSocketConnectionClosedException()
if stream == 'account_updates':
return json.dumps({
"stream": stream,
"data": {
"id": "ef505a9a-2f3c-4b8a-be95-6b6f185f8a03",
"created_at": "2018-02-26T19:22:31Z",
"updated_at": "2018-02-27T18:16:24Z",
"deleted_at": None,
"status": "ACTIVE",
"currency": "USD",
"amount_tradable": "1241.54",
"amount_withdrawable": "523.71"
}
})
else:
raise AssertionError('unexpected')
fake = Fake()
ws = WebSocket()
ws.send.side_effect = fake.send
ws.recv.side_effect = fake.recv
conn = StreamConn('account_id', 'api_key')
@conn.on('authenticated')
def on_auth(conn, stream, msg):
conn.subscribe([
'account_updates',
])
with pytest.raises(WebSocketConnectionClosedException):
conn.run()