【发布时间】:2017-04-14 13:09:38
【问题描述】:
我有这段代码
class RTMClient:
...
#not important code
...
async def connect(self, queue: asyncio.Queue):
"""
Connect to the websocket stream and iterate over the messages
dumping them in the Queue.
"""
ws_url=''#url aquisition amended to readability
try:
self._ws = await websockets.connect(ws_url)
while not self.is_closed:
msg = await self._ws.recv()
if msg is None:
break
await queue.put(json.loads(msg))
except asyncio.CancelledError:
pass
finally:
self._closed.set()
self._ws = None
我想为它编写一个自动化测试。 我打算做什么:
- Monkeypatch
websockets.connect返回模拟连接 - 使模拟连接从预定义列表中返回模拟消息
- 将模拟连接设置为
is_closed到True - 断言 websocket 连接已关闭
- 断言所有预定义的消息都在队列中
我的问题:如何模拟 websockets.connection 以实现步骤 1-3?
我正在考虑像这样的 pytest 夹具
from websockets import WebSocketClientProtocol()
@pytest.fixture
def patch_websockets_connect(monkeypatch):
async def mock_ws_connect(*args, **kwargs):
mock_connection = WebSocketClientProtocol()
mock_connection.is_closed = False
return mock_connection
monkeypatch.setattr('target_module.websockets.connect', mock_ws_connect)
但我不知道如何以这种方式返回预定义的消息列表,而且必须有更好的方法来做到这一点。
【问题讨论】:
标签: python unit-testing websocket automated-tests python-asyncio