zoukankan      html  css  js  c++  java
  • FastApi教程|测试WebSockets

     

    测试的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"}
  • 相关阅读:
    阶梯式测试
    websocket协议
    性能指标
    环境变量
    解密断言+参数写入文本
    将参数进行URL编码
    日志级别
    对返回结果进行断言
    python小题目:循环/函数
    如果使用JSON提取器 和正则提取器
  • 原文地址:https://www.cnblogs.com/a00ium/p/13662342.html
Copyright © 2011-2022 走看看