首页 > Windows开发 > 详细

FastApi教程|测试WebSockets

时间:2020-09-13 21:44:50      阅读:184      评论:0      收藏:0      [点我收藏+]
 

测试的WebSockets

您可以使用相同 TestClient 的工具测试WebSocket。

为此,您可以使用 TestClient in with 语句连接到WebSocket:

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

app = FastAPI()


@app.get("/")
async def read_main():
    return {"msg": "Hello World"}


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


def test_read_main():
    client = TestClient(app)
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": "Hello World"}


def test_websocket():
    client = TestClient(app)
    with client.websocket_connect("/ws") as websocket:
        data = websocket.receive_json()
        assert data == {"msg": "Hello WebSocket"}

FastApi教程|测试WebSockets

原文:https://www.cnblogs.com/a00ium/p/13662342.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!