|
| 1 | +from unittest import mock |
| 2 | + |
| 3 | +import pytest |
| 4 | +from aiohttp import WSMsgType |
| 5 | + |
| 6 | +from graphql_ws.aiohttp import AiohttpConnectionContext, AiohttpSubscriptionServer |
| 7 | +from graphql_ws.base import ConnectionClosedException |
| 8 | + |
| 9 | + |
| 10 | +class AsyncMock(mock.Mock): |
| 11 | + def __call__(self, *args, **kwargs): |
| 12 | + |
| 13 | + async def coro(): |
| 14 | + return super(AsyncMock, self).__call__(*args, **kwargs) |
| 15 | + |
| 16 | + return coro() |
| 17 | + |
| 18 | + |
| 19 | +@pytest.fixture() |
| 20 | +def mock_ws(): |
| 21 | + ws = AsyncMock(spec=["receive", "send_str", "closed", "close"]) |
| 22 | + ws.closed = False |
| 23 | + ws.receive.return_value = AsyncMock(spec=["type", "data"]) |
| 24 | + return ws |
| 25 | + |
| 26 | + |
| 27 | +@pytest.mark.asyncio |
| 28 | +class TestConnectionContext: |
| 29 | + async def test_receive_good_data(self, mock_ws): |
| 30 | + msg = mock_ws.receive.return_value |
| 31 | + msg.type = WSMsgType.TEXT |
| 32 | + msg.data = "test" |
| 33 | + connection_context = AiohttpConnectionContext(ws=mock_ws) |
| 34 | + assert await connection_context.receive() == "test" |
| 35 | + |
| 36 | + async def test_receive_error(self, mock_ws): |
| 37 | + msg = mock_ws.receive.return_value |
| 38 | + msg.type = WSMsgType.ERROR |
| 39 | + connection_context = AiohttpConnectionContext(ws=mock_ws) |
| 40 | + with pytest.raises(ConnectionClosedException): |
| 41 | + await connection_context.receive() |
| 42 | + |
| 43 | + async def test_receive_closing(self, mock_ws): |
| 44 | + mock_ws.receive.return_value.type = WSMsgType.CLOSING |
| 45 | + connection_context = AiohttpConnectionContext(ws=mock_ws) |
| 46 | + with pytest.raises(ConnectionClosedException): |
| 47 | + await connection_context.receive() |
| 48 | + |
| 49 | + async def test_receive_closed(self, mock_ws): |
| 50 | + mock_ws.receive.return_value.type = WSMsgType.CLOSED |
| 51 | + connection_context = AiohttpConnectionContext(ws=mock_ws) |
| 52 | + with pytest.raises(ConnectionClosedException): |
| 53 | + await connection_context.receive() |
| 54 | + |
| 55 | + async def test_send(self, mock_ws): |
| 56 | + connection_context = AiohttpConnectionContext(ws=mock_ws) |
| 57 | + await connection_context.send("test") |
| 58 | + mock_ws.send_str.assert_called_with("test") |
| 59 | + |
| 60 | + async def test_send_closed(self, mock_ws): |
| 61 | + mock_ws.closed = True |
| 62 | + connection_context = AiohttpConnectionContext(ws=mock_ws) |
| 63 | + await connection_context.send("test") |
| 64 | + mock_ws.send_str.assert_not_called() |
| 65 | + |
| 66 | + async def test_close(self, mock_ws): |
| 67 | + connection_context = AiohttpConnectionContext(ws=mock_ws) |
| 68 | + await connection_context.close(123) |
| 69 | + mock_ws.close.assert_called_with(code=123) |
| 70 | + |
| 71 | + |
| 72 | +def test_subscription_server_smoke(): |
| 73 | + AiohttpSubscriptionServer(schema=None) |
0 commit comments