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

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

相关推荐
Amd79410 小时前
FastAPI中Pydantic异步分布式唯一性校验
redis·fastapi·分布式锁·多级缓存·pydantic·唯一性校验·异步校验
techdashen20 小时前
性能比拼: Go标准库 vs Python FastAPI
python·golang·fastapi
Amd7941 天前
掌握FastAPI与Pydantic的跨字段验证技巧
fastapi·web开发·数据校验·pydantic·验证器·api集成·跨字段验证
带娃的IT创业者2 天前
《Python Web部署应知应会》No2:如何基于FastAPI 和 OLLAMA 架构实现高并发 AI 推理服务
python·架构·flask·fastapi
Amd7942 天前
FastAPI中的Pydantic密码验证机制与实现
fastapi·数据验证·错误处理·pydantic·密码验证·安全机制·api集成
勘察加熊人3 天前
fastapi+angular在线音乐播放
前端·fastapi·angular.js
yukai080083 天前
【最后203篇系列】025 FastAPI+Celery
fastapi
冲上云霄的Jayden4 天前
Paddlex服务化代理处理跨域、替换Response中Json key
json·fastapi·代理·跨域·uvicorn·paddlex·服务化
小宁爱Python7 天前
Python从入门到精通2:SQLite数据库(FastAPI + SQLite全流程开发指南)
数据库·python·sqlite·fastapi
Cccc吃吃吃7 天前
python中深浅拷贝以及可变对象和不可变对象
开发语言·jvm·python·beautifulsoup·numpy·pyqt·fastapi