async def read_msg(self, ws, keep_alive=True): """ :param ws: :param keep_alive: :return: """ start_timestamp = datetime.datetime.utcnow().timestamp() async for msg in ws: print('start:{}'.format(int(start_timestamp))) if msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR): print("websocket closed or msg type error") # todo raise exception? ws.close() raise aiohttp.ServerDisconnectedError(message='closed') print(f"ws msg:{msg}") # todo 消息处理 data = json.loads(msg.data) print(f"data: {data}") if keep_alive: intervel = datetime.datetime.utcnow().timestamp( ) - start_timestamp if intervel >= 20: print(f"intervel: {intervel}") await self.timer(ws=ws, params=self.evt_ping) start_timestamp = datetime.datetime.utcnow().timestamp()
def handle_response(self, resp): if resp.type == aiohttp.WSMsgType.CLOSE: raise aiohttp.ServerDisconnectedError('Socket was closed by server. (code={resp.data})') if resp.type == aiohttp.WSMsgType.ERROR: raise FatalError(f'Error raised while waiting for response from server: {resp}.') assert resp.type == aiohttp.WSMsgType.TEXT, resp.type return resp.data
async def read_msg(self, ws, channel: str): start_timestamp = datetime.utcnow().timestamp() async for msg in ws: print('start:{}'.format(int(start_timestamp))) if msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR): print("websocket closed or msg type error") # todo raise exception? ws.close() raise aiohttp.ServerDisconnectedError(message='closed') print(f"ws msg:{msg}") # todo 消息处理 data = json.loads(gzip.decompress(msg.data).decode()) if 'ping' in data.keys(): await ws.send_json({"pong": data.get("ping")}) await ws.send_str(data=channel) print(f"data: {data}")
async def test_disconnect(self, mock_book, mock_connect): mock_connect.return_value.aenter.receive_str = CoroutineMock() mock_connect.return_value.aenter.send_json = CoroutineMock() mock_book.return_value = {'bids': [], 'asks': [], 'sequence': 1} messages_expected = [ json.dumps({ "type": "done", "side": "sell", "order_id": "4eef1226-4b38-422c-a5b1-56def7107f9a", "reason": "canceled", "product_id": "ETH-USD", "price": "2601.76000000", "remaining_size": "3.09000000", "sequence": 2, "time": "2017-06-25T11:23:14.775000Z" }), aiohttp.ServerDisconnectedError('error'), json.dumps({ "type": "done", "side": "sell", "order_id": "4eef1226-4b38-422c-a5b1-56def7107f9a", "reason": "canceled", "product_id": "ETH-USD", "price": "2601.76000000", "remaining_size": "3.09000000", "sequence": 2, "time": "2017-06-25T11:23:14.775000Z" }) ] mock_connect.return_value.aenter.receive_str.side_effect = \ messages_expected async with gdax.orderbook.OrderBook() as orderbook: message = await orderbook.handle_message() assert message == json.loads(messages_expected[0]) message = await orderbook.handle_message() assert message is None message = await orderbook.handle_message() assert message == json.loads(messages_expected[2])
async def test_suppressed_exceptions(): async with SuppressedExceptions(is_intermittent_error) as se: pass assert se.exception is None async with SuppressedExceptions(is_intermittent_error) as se: raise asyncio.TimeoutError() assert isinstance(se.exception, asyncio.TimeoutError) async with SuppressedExceptions(is_intermittent_error) as se: raise aiohttp.ClientOSError(32, "Broken pipe") assert isinstance(se.exception, aiohttp.ClientOSError) async with SuppressedExceptions(is_intermittent_error) as se: raise aiohttp.ServerDisconnectedError() assert isinstance(se.exception, aiohttp.ServerDisconnectedError) with pytest.raises(AssertionError): async with SuppressedExceptions(is_intermittent_error): raise AssertionError()
def fail_with_disconnected_error(): raise aiohttp.ServerDisconnectedError("Darn it, can't connect")
async def receive_bytes(self) -> bytes: if self._raw_ws.closed: raise aiohttp.ServerDisconnectedError('server disconnected') return await self._raw_ws.receive_bytes()
async def send_bytes(self, data: bytes): if self._raw_ws.closed: raise aiohttp.ServerDisconnectedError('server disconnected') await self._raw_ws.send_bytes(data)
async def send_json(self, obj: Any): if self._raw_ws.closed: raise aiohttp.ServerDisconnectedError('server disconnected') await self._raw_ws.send_json(obj)
async def send_str(self, raw_str: str): if self._raw_ws.closed: raise aiohttp.ServerDisconnectedError('server disconnected') await self._raw_ws.send_str(raw_str)
from yarl import URL from galaxy.api.errors import (AccessDenied, AuthenticationRequired, BackendTimeout, BackendNotAvailable, BackendError, NetworkError, TooManyRequests, UnknownBackendResponse, UnknownError) from galaxy.http import handle_exception request_info = aiohttp.RequestInfo(URL("http://o.pl"), "GET", CIMultiDictProxy(CIMultiDict())) @pytest.mark.parametrize( "aiohttp_exception,expected_exception_type", [(asyncio.TimeoutError(), BackendTimeout), (aiohttp.ServerDisconnectedError(), BackendNotAvailable), (aiohttp.ClientConnectionError(), NetworkError), (aiohttp.ContentTypeError(request_info, ()), UnknownBackendResponse), (aiohttp.ClientResponseError( request_info, (), status=HTTPStatus.UNAUTHORIZED), AuthenticationRequired), (aiohttp.ClientResponseError(request_info, (), status=HTTPStatus.FORBIDDEN), AccessDenied), (aiohttp.ClientResponseError( request_info, (), status=HTTPStatus.SERVICE_UNAVAILABLE), BackendNotAvailable), (aiohttp.ClientResponseError( request_info, (), status=HTTPStatus.TOO_MANY_REQUESTS), TooManyRequests), (aiohttp.ClientResponseError( request_info,
@pytest.mark.parametrize( "max_tries, exceptions, calls_expected, expected_error", [ (1, [], 1, None), (1, [asyncio.TimeoutError()], 1, asyncio.TimeoutError), (1, [ya_activity.ApiException(408)], 1, ya_activity.ApiException), (1, [ya_activity.ApiException(500)], 1, ya_activity.ApiException), (1, [ValueError()], 1, ValueError), # (2, [], 1, None), (2, [asyncio.TimeoutError()], 2, None), (2, [ya_activity.ApiException(408)], 2, None), (2, [ya_market.ApiException(408)], 2, None), (2, [ya_payment.ApiException(408)], 2, None), (2, [ya_activity.ApiException(500)], 1, ya_activity.ApiException), (2, [aiohttp.ServerDisconnectedError()], 2, None), (2, [aiohttp.ClientOSError(32, "Broken pipe")], 2, None), (2, [aiohttp.ClientOSError(1132, "UnBroken pipe") ], 1, aiohttp.ClientOSError), (2, [ValueError()], 1, ValueError), (2, [asyncio.TimeoutError()] * 2, 2, asyncio.TimeoutError), # (3, [], 1, None), (3, [asyncio.TimeoutError()], 2, None), (3, [ya_activity.ApiException(408)], 2, None), (3, [asyncio.TimeoutError()] * 2, 3, None), (3, [asyncio.TimeoutError()] * 3, 3, asyncio.TimeoutError), (3, [ya_activity.ApiException(500)], 1, ya_activity.ApiException), (3, [asyncio.TimeoutError(), ValueError()], 2, ValueError), ], )