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

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

相关推荐
摸鱼仙人~3 天前
ImportError: cannot import name ‘FixtureDef‘ from ‘pytest‘
conda·pytest·fastapi
安迪小宝4 天前
20 FastAPI 性能优化
oracle·性能优化·fastapi
_.Switch9 天前
FastAPI 高并发与性能优化
网络·数据库·python·性能优化·fastapi
安迪小宝11 天前
11 FastAPI文档自定义
fastapi
drebander12 天前
[特殊字符] 基于 FastAPI 和 React 构建车牌号识别网站
前端·react.js·fastapi
m0_7482329213 天前
纯 Python、Django、FastAPI、Flask、Pyramid、Jupyter、dbt 解析和差异分析
python·django·fastapi
一见已难忘15 天前
Flask与FastAPI对比选择最佳Python Web框架的指南
python·flask·fastapi
亿牛云爬虫专家17 天前
FastAPI与Selenium:打造高效的Web数据抓取服务
爬虫·python·selenium·fastapi·图片·代理ip·pixabay
股票数据接口19 天前
2025年度Python最新整理的免费股票数据API接口
开发语言·python·fastapi
老大白菜20 天前
在 Ubuntu 中使用 FastAPI 创建一个简单的 Web 应用程序
前端·ubuntu·fastapi