Loading

Httprunner4 - websocket

说明文档:https://testerhome.com/topics/33229

本地 ws 服务

import asyncio
import websockets


# 接收客户端消息并处理,这里只是简单把客户端发来的返回回去
async def recv_user_msg(websocket):
    while True:
        recv_text = await websocket.recv()
        print("recv_text:", websocket.pong, recv_text)
        response_text = f"Server return: {recv_text}"
        print("response_text:", response_text)
        await websocket.send(response_text)


# 服务器端主逻辑
async def run(websocket, path):
    while True:
        try:
            await recv_user_msg(websocket)
        except websockets.ConnectionClosed:
            print("ConnectionClosed...", path)    # 链接断开
            break
        except websockets.InvalidState:
            print("InvalidState...")    # 无效状态
            break
        except Exception as e:
            print("Exception:", e)


if __name__ == '__main__':
    print("127.0.0.1:8181 websocket...")
    asyncio.get_event_loop().run_until_complete(websockets.serve(run, "127.0.0.1", 8181))
    asyncio.get_event_loop().run_forever()

Hrun 用例

config:
    name: 本地websocket测试
    base_url: ws://127.0.0.1:8181

teststeps:
    -   name: open connection
        websocket:
            type: open
            url: "/"
            headers:
                User-Agent: HttpRunnerPlus
        validate:
            -   check: status_code
                assert: equals
                expect: 101
                msg: check open status code
            -   check: headers.Connection
                assert: equals
                expect: Upgrade
                msg: check headers

    -   name: ping pong test
        websocket:
            type: ping
            url: "/"
            timeout: 5000

    -   name: 客户端发送消息
        websocket:
            type: w
            url: "/"
            text: "你好"

    -   name: 客户端读取服务端返回的消息
        websocket:
            type: r
            url: "/"
        validate:
            -   check: body
                assert: contains
                expect: "你好"
                msg: validate msg

    -   name: write and read text
        websocket:
            type: wr
            url: "/"
            text: "先发后读"
        validate:
            -   check: body
                assert: contains
                expect: "先发后读"
                msg: check length equal

    -   name: close connection
        websocket:
            type: close
            url: "/"
            close_status: 1000
            timeout: 30000
        validate:
            -   check: status_code
                assert: equals
                expect: 1000
                msg: check close status code
posted @ 2023-03-07 15:41  ABEELAN  阅读(65)  评论(0编辑  收藏  举报