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}")

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

相关推荐
菜鸟学Python40 分钟前
Python生态在悄悄改变:FastAPI全面反超,Django和Flask还行吗?
开发语言·python·django·flask·fastapi
今晚务必早点睡11 小时前
Ubuntu 部署 RuoYi-Vue-FastAPI 完整实战指南(含踩坑总结)
vue.js·ubuntu·fastapi
曲幽12 小时前
FastAPI 生产环境避坑指南:用 Alembic 管理数据库迁移,别再手动改表结构了!
python·fastapi·web·async·sqlalchemy·env·alembic·migration
不瘦80斤不改名14 小时前
深入理解 FastAPI 核心架构:依赖注入、分页机制与数据流转的底层逻辑
python·架构·fastapi
古方路杰出青年15 小时前
学习笔记1:Python FastAPI极简后端API示例解析
笔记·后端·python·学习·fastapi
观无1 天前
FastAPI + SQLite 原生无主键表 完整增删改查
数据库·sqlite·fastapi
Json____2 天前
python-电商商城平台项目源码(管理端+用户端)
python·fastapi·电商商城·练习项目·wwwoop.com
曲幽2 天前
FastAPI服务半夜又挂了?先别急着重启,查查你的数据库连接池“池子”是不是漏了
python·prometheus·fastapi·web·async·sqlalchemy·connection·pool
花月C2 天前
Python Web框架-FastAPI
python·fastapi
小李云雾2 天前
FastAPI重要知识点---中间件(Middleware)
学习·程序人生·中间件·fastapi·middleware