【问题标题】:How can I test Django Channels using native Django's test framework instead of pytest?如何使用原生 Django 的测试框架而不是 pytest 来测试 Django 频道?
【发布时间】:2020-07-29 23:08:28
【问题描述】:
Django Channels 建议使用 pytest 以获得启用异步的测试层。如果可以的话,我真的不想在我的项目中加入另一个测试框架。
有没有办法在本地使用 Django 的 TestCase 来测试 Django Channels?
我遇到了多个问题——一个是 async_to_sync() 不喜欢从主线程调用。
我目前受限于 Python 3.6。
【问题讨论】:
标签:
django
unit-testing
django-channels
【解决方案1】:
我相信我已经找到了一种可靠的方法来做到这一点。这还不是 DRY,但它是一个似乎适用于该测试的概念证明:
class TestWebSockets(TestCase):
def test_message(self):
async def wait_for_message(self):
try:
communicator = WebsocketCommunicator(application, f"/ws/channel/")
connected, subprotocol = await communicator.connect()
self.assertTrue(connected)
data = await communicator.receive_json_from(timeout=1)
return data
except Exception as exc:
logging.exception(exc)
raise
finally:
await communicator.disconnect()
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(async_to_sync(wait_for_message), self)
DoTheThingThatGeneratesChannelMessage()
message = future.result()
print(message)