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

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

相关推荐
呱牛do it5 小时前
企业级软件研发团队绩效考核系统开发(持续更新 Day 8)
python·fastapi·研发管理
曲幽5 小时前
FastAPI + Celery 实战:异步任务的坑与解法,我帮你踩了一遍
redis·python·fastapi·web·async·celery·background·task·queue
I'm Jie6 小时前
FastAPI 集成 Redis 开发手册
redis·fastapi
samson_www8 小时前
用nssm部署FASTAPI服务
数据库·python·fastapi
小李云雾8 小时前
零基础-从ESS6基础到前后端联通实战
前端·python·okhttp·中间件·eclipse·html·fastapi
呱牛do it13 小时前
企业级软件研发团队绩效考核系统开发(持续更新 Day 7)
python·fastapi·研发管理
曲幽1 天前
FastAPI子应用挂载:别再让root_path坑你一夜
python·nginx·fastapi·web·mount·admin·404·docs·root_path
Ares-Wang1 天前
Python》》FastAPI 异步框架 接口 pymysql【同步】 aiomysql【异步】
开发语言·python·fastapi
Thomas.Sir2 天前
第十四章:基于 FastAPI+Vue3 的智能聊天系统全栈开发实战
vue·状态模式·fastapi·智能
在屏幕前出油3 天前
06. FastAPI——中间件
后端·python·中间件·pycharm·fastapi