FastAPI 学习之路(四十八)WebSockets(四)接口测试

在我们测试的过程中,肯定会对接口进行测试。之前分享过的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}")

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

相关推荐
淼澄研学7 小时前
Python构建AI应用:从环境配置到FastAPI部署的5个实操步骤
人工智能·python·fastapi
逻极1 天前
FastAPI 实战:从入门到自动化文档,如何把API开发效率提升200%
python·api·fastapi·swagger·异步
天使day2 天前
FastAPI快速入门
python·fastapi
Maiko Star2 天前
FastAPI如何解决跨越问题
fastapi
weixin_471383033 天前
07 FastAPI
python·fastapi
Python私教3 天前
AI 生成到 90% 突然断了怎么办?我用 SSE、检查点和幂等把任务接着跑
fastapi
李昊哲小课4 天前
FastAPI + Echarts 构建可交互数据仪表板
信息可视化·echarts·fastapi
未知违规用户4 天前
大模型项目: 学习FastAPI 服务器开发
服务器·人工智能·python·学习·fastapi
普通网友5 天前
Python FastAPI 异步数据库管理
数据库·fastapi
观察员5 天前
深入理解 Pydantic 的 BaseModel
fastapi