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

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

相关推荐
浠寒AI15 小时前
【FastAPI高级实战】结合查询参数与SQLModel Joins实现高效多表查询(分页、过滤、计数)
fastapi
浠寒AI3 天前
FastAPI核心解密:深入“路径操作”与HTTP方法,构建API的坚实骨架
网络协议·http·fastapi
you鬰4 天前
FastAPI基础入门(三)
fastapi
Python私教6 天前
FastAPI 与 JWT 身份验证:保护你的 API
网络·fastapi
白嫖不白嫖6 天前
Django、Flask、FastAPI与Jupyter对比
django·flask·fastapi
一刀到底2116 天前
Python 高级应用10:在python 大型项目中 FastAPI 和 Django 的相互配合
python·django·fastapi
fengbingchun7 天前
线性规划饮食问题求解:FastAPI作为服务端+libhv作为客户端实现
fastapi·libhv·pyomo
zhangsan09337 天前
web框架(Django 与 FastAPI)
django·fastapi
jingyucsdn7 天前
网页端 VUE+C#/FastAPI获取客户端IP和hostname
网络协议·tcp/ip·fastapi
掘金-我是哪吒10 天前
分布式微服务系统架构第144集:FastAPI全栈开发教育系统
分布式·微服务·架构·系统架构·fastapi