FastAPI(60)- 针对 WebSocket 进行单元测试

这篇博客介绍了如何对 FastAPI 中的 WebSocket 进行单元测试,包括如何运行测试、连接、发送和接收不同类型的数据,以及如何关闭连接。详细讲解了.send_text(), .send_bytes(), .send_json()等方法以及.receive_text(), .receive_bytes(), .receive_json()的使用,并提到了可能遇到的WebSocketDisconnect异常。" 112069348,10293602,15分钟生活圈距离衰减:高斯曲线拟合,"['GIS', '数据分析', '城市规划', '交通研究', '数据拟合']
摘要由CSDN通过智能技术生成

前言

还是比较简单的,直接写代码啦

FastAPI 的单元测试:https://www.cnblogs.com/poloyy/p/15354901.html

直接上代码

#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/10/7 9:05 下午
# file: 51_test_websocket.py
"""

from fastapi import FastAPI
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocket

app = FastAPI()
testClient = TestClient(app)


@app.websocket("/ws")
async def connect(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_json({
    "msg": "Hello WebSocket"})
    await websocket.close()


def test_websocket():
   
Python FastAPI 是一个高性能、易于使用、快速编写 APIWeb 框架。如果你想要在 FastAPI 中增加 WebSocket,可以使用第三方库 fastapi-websocket 来实现。 首先,你需要在你的项目中安装 fastapi-websocket 库。你可以使用 pip 命令进行安装: ``` pip install fastapi-websocket ``` 安装完成后,在你的 FastAPI 项目中导入 fastapi_websocket 包。然后,你可以通过创建一个 WebSocketEndpoint 类来实现 WebSocket: ```python from fastapi import FastAPI from fastapi_websocket import WebSocket app = FastAPI() class WebSocketEndpoint: def __init__(self, ws: WebSocket): self.ws = ws async def send_message(self, message: str): await self.ws.send_text(message) @app.websocket("/ws") async def websocket_endpoint(ws: WebSocket): websocket = WebSocketEndpoint(ws) await websocket.send_message("Hello, WebSocket!") ``` 在上面的代码中,我们创建了一个 WebSocketEndpoint 类来实现 WebSocket。这个类中包含了一个 send_message 方法,用来发送消息给客户端。然后,在 websocket_endpoint 函数中,我们创建了一个 WebSocketEndpoint 对象,并通过 send_message 方法发送一条消息。 最后,我们将这个 WebSocketEndpoint 函数装饰为 /ws 路径的 WebSocket: ```python @app.websocket("/ws") async def websocket_endpoint(ws: WebSocket): websocket = WebSocketEndpoint(ws) await websocket.send_message("Hello, WebSocket!") ``` 如果你想要了解更多关于 FastAPIfastapi-websocket 的内容,可以查看官方文档:https://fastapi.tiangolo.com/tutorial/websockets/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小菠萝测试笔记

来支持下测试小锅锅

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值