FastAPI 学习之路(四十八)WebSockets(四)接口测试
创始人
2025-01-10 09:06:18
0

在我们测试的过程中,肯定会对接口进行测试。之前分享过的FastApi学习之路(三十八)对开发接口进行测试,那么我们针对websockets接口怎么测试呢。

其实也很简单

from fastapi.testclient import TestClient from main import app   def test_websocket():     client = TestClient(app)     with client.websocket_connect("/items/ws?token=fake-token") as websocket:         websocket.send_text("Hello, this is testing websocket")         data = websocket.receive_text()         assert str(data) == f"Message is: Hello, this is testing websocket"   if __name__ == '__main__':     test_websocket() 

执行测试发现报错

这个错误,主要是我们在最后的时候没有释放链接,我们可以在代码中链接接受到消息后,返回完毕关闭链接,或者说我们单元测试的时候关闭链接。

@app.websocket("/items/ws") async def websocket_endpoint(     websocket: WebSocket,     cookie_or_token: str = Depends(get_cookie_or_token), ):     await websocket.accept()     while True:         data = await websocket.receive_text()         if data == "Hello, this is testing websocket":             await websocket.send_text(f"Message is: {data}")             break         else:             await websocket.send_text(f"Message is: {data}")

其实要做的测试很简单,我们可以利用这个方式对于我们已经开发的接口进行测试。

相关内容

热门资讯

透视好友!wepoker透视版... 透视好友!wepoker透视版下载(透视)永久脚本辅助方法(详细辅助德州论坛)所有人都在同一条线上,...
透视中牌率"wpk辅... 透视中牌率"wpk辅助插件"详细辅助软件教程(真是是真的有挂);运wpk辅助插件辅助工具,进入游戏界...
透视透视挂!wepoker底牌... 透视透视挂!wepoker底牌透视(透视)永久脚本辅助软件(详细辅助2025新版);运wepoker...
透视了解"wepok... 透视了解"wepoker破解器有用吗"详细辅助软件教程(都是真的是有挂)1、很好的工具软件,可以解锁...
透视中牌率!wepoker私人... 透视中牌率!wepoker私人局开挂视频(透视)永久脚本辅助软件(详细辅助技巧教程)所有人都在同一条...
透视黑科技"aa p... 透视黑科技"aa poker辅助包"详细辅助详细教程(切实是有挂);1、玩家可以在aa poker辅...
透视app!德州透视脚本(透视... 透视app!德州透视脚本(透视)永久脚本辅助器(详细辅助AI教程)1、德州透视脚本系统规律教程、德州...
透视科技"we-po... 透视科技"we-poker辅助软件教程"详细辅助细节方法(一直是真的有挂)1、we-poker辅助软...
透视透视挂!hhpoker可以... 透视透视挂!hhpoker可以开挂吗(透视)永久脚本辅助app(详细辅助AI教程)1、hhpoker...
透视线上"pokem... 透视线上"pokemmo脚本手机版"详细辅助存在挂教程(竟然真的有挂)1、实时pokemmo脚本手机...