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

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

相关推荐
掘金-我是哪吒1 天前
分布式微服务系统架构第131集:fastapi-python
分布式·python·微服务·系统架构·fastapi
Anesthesia丶4 天前
Vue3 + naive-ui + fastapi使用心得
vue.js·ui·fastapi
weixin_307779134 天前
使用FastAPI微服务在AWS EKS中构建上下文增强型AI问答系统
人工智能·python·云计算·fastapi·aws
掘金-我是哪吒4 天前
分布式微服务系统架构第130集:Python工程化FastAPI,运维Nginx-keepalived+Nginx实现高可用集群
运维·分布式·微服务·系统架构·fastapi
LingRannn4 天前
JWT的介绍与在Fastapi框架中的应用
fastapi
Python私教4 天前
使用FastAPI和React以及MongoDB构建全栈Web应用05 FastAPI快速入门
前端·react.js·fastapi
Python私教5 天前
全栈开发实战:FastAPI + React + MongoDB 构建现代Web应用
前端·react.js·fastapi
weixin_307779135 天前
使用FastAPI和Apache Flink构建跨环境数据管道
redis·python·云计算·fastapi·aws
真智AI8 天前
构建安全的机器学习推理API:基于FastAPI的用户认证与管理实战
安全·机器学习·fastapi
Data 实验室11 天前
爬虫管理平台-最新版本发布
开发语言·爬虫·python·fastapi