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

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

相关推荐
带娃的IT创业者1 天前
第2集:技术选型的智慧:Flask vs FastAPI,GLM-4 vs GPT
python·gpt·flask·fastapi·glm·技术选型
万粉变现经纪人5 天前
如何解决 pip install 安装报错 ImportError: cannot import name ‘xxx’ from ‘yyy’ 问题
python·selenium·测试工具·flask·scikit-learn·fastapi·pip
闲人编程6 天前
2025年,如何选择Python Web框架:Django, Flask还是FastAPI?
前端·后端·python·django·flask·fastapi·web
chao_7896 天前
Union 和 Optional 区别
开发语言·数据结构·python·fastapi
BTU_YC7 天前
Django+FastAPI+Vue微服务架构指南
架构·django·fastapi
Gerlat小智7 天前
【Python精讲 16】实战项目演练(二):用Flask/FastAPI发布你的第一个Web API
python·flask·fastapi
onelafite8 天前
淘宝开放平台拍立淘接口返回参数及调用操作指南
api·fastapi
weixin_421133418 天前
使用 SQLAlchemy 和 Alembic 处理 FastAPI 中的模型变更
fastapi
老坛程序员9 天前
FastAPI WebSocket 由浅入深的开发范例
websocket·网络协议·fastapi
万粉变现经纪人10 天前
如何解决 pip install 安装报错 ModuleNotFoundError: No module named ‘tokenizers’ 问题
python·selenium·测试工具·scrapy·beautifulsoup·fastapi·pip