我是一个非常基本的测试,用于检查未登录的用户是否可以连接到我的websocket,如下所示:
@pytest.mark.asyncio
async def test_unauthenticated_cant_connect_to_websocket(unauthenticated_websocket_communicator: WebsocketCommunicator):
connected, subprotocol = await unauthenticated_websocket_communicator.connect()
assert subprotocol == 3000 # subprotocol 3000 is Unauthorised
assert connected is False
当我使用pytest -k test_unauthenticated_cant_connect_to_websocket
从cli单独测试时,该测试通过
但当我从cli 使用pytest
时失败
我的消费者连接功能如下:
async def websocket_connect(self, event: dict) -> None:
if self.scope["user"].is_anonymous:
await self.close(code=3000)
else:
await self.accept()
我有很多其他的异步测试都有类似类型的代码,但它们都通过了
我通过在测试中添加@pytest.mark.django_db
装饰器来修复这个问题。