Django+vue自动化测试平台(27)-- 封装websocket测试

websocket概述:

WebSocket 是一种在单个 TCP 连接上进行全双工通信(Full Duplex 是通讯传输的一个术语。通信允许数 据在两个方向上同时传输,它在能力上相当于两个单工通信方式的结合。全双工指可以同时(瞬时)进 行信号的双向传输( A→B 且 B→A )。指 A→B 的同时 B→A,是瞬时同步的)的协议。

WebSocket 通信协议于 2011 年被 IETF 定为标准 RFC 6455,并由 RFC7936 补充规范。WebSocket API (WebSocket API 是一个使用WebSocket 协议的接口,通过它来建立全双工通道来收发消息) 也被 W3C 定为标准。

WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。 在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接, 并进行双向数据传输。

而 HTTP 协议就不支持持久连接,虽然在 HTTP1.1 中进行了改进,使得有一个 keep-alive,在一个 HTTP 连接中,可以发送多个 Request,接收多个 Response。

但是在 HTTP 中 Request = Response 永远是成立的,也就是说一个 request 只能有一个response。而且 这个response也是被动的,不能主动发起。

websocket 常用于社交/订阅、多玩家游戏、协同办公/编辑、股市基金报价、体育实况播放、音视频聊 天/视频会议/在线教育、智能家居与基于位置的应用。

websocket 接口不能使用 requests 直接进行接口的调用,可以依赖第三方库的方式来实现调用,以下内 容介绍如何调用第三方库实现 websocket 的接口自动化测试。

实战效果预览:

后端逻辑实现(前端就不展示了,各有各的想法):

python 复制代码
# -*-coding: gbk-*-
import io
import json
import socket
from datetime import datetime
from uuid import uuid4
from django.http import JsonResponse
import websocket
import threading
from django.views import View

# 定义一个dict字典,用来存储websocket的连接对象
websocket_info = {}


# 主类,使用的django的视图类,将其视为http对象
class WebSocketTestView(View):
    def create_websocket(self, request):
        try:
            data = json.loads(request.body)
            # 生成websocket唯一标识
            uuid = str(uuid4())

            def on_data(ws, frame_data, frame_opcode, frame_fin):
                # WebSocketApp方法的on_data,没用上,做着玩
                print("frame_data:", frame_data)
                print("frame_opcode:", frame_opcode)
                print("frame_fin:", frame_fin)

            # 初始化 WebSocket 连接及相关回调
            def on_message(ws, message):
                websocket_info[uuid]['history'].append({"message": message, "type": 2,
                                                        "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})

            # 异常函数回调
            def on_error(ws, error):
                websocket_info[uuid]["history"].append({"message": error, "type": 2,
                                                        "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})

            # websocket连接关闭回调
            def on_close(ws, close_status_code, close_message):
                websocket_info.pop(uuid, None)

            # 建立连接回调
            def on_open(ws):
                try:
                    websocket_info[uuid]['status'] = True
                except Exception as e:
                    print(e)
                    websocket_info[uuid]['status'] = False

            # websocket.WebSocketApp建立连接
            # params是url的传参,我用的是params=[{"key": "value"}, {"key": "value"}]
            # headers是websocket中传的请求头
            ws = websocket.WebSocketApp(f"{data['url']}?"
                                        f"{'&'.join([f'{k}={v}' for param in data['params'] for k, v in param.items()])}",
                                        on_open=on_open,
                                        on_message=on_message,
                                        on_error=on_error,
                                        on_close=on_close,
                                        on_data=on_data,
                                        header=data["headers"])

            websocket_info[uuid] = {
                'ws': ws,
                "status": False,
                "history": [],
            }
            # 启动多线程进行websocket的长久连接
            thread = threading.Thread(target=ws.run_forever)
            thread.start()
            on_open(ws)

            if websocket_info[uuid]['status']:
                websocket_info[uuid]["history"].append(
                    {'uuid': uuid, "message": "websocket Connecting", "type": 2, "code": 200,
                     "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
                return JsonResponse({'uuid': uuid, "message": "websocket Connecting", "type": 2, "code": 200,
                                     "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
            else:
                websocket_info[uuid]["history"].append(
                    {"message": "disconnected", "type": 2, "code": 100,
                     "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
                return JsonResponse({"message": "disconnected", "type": 2, "code": 100,
                                     "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
        except Exception as e:
            return JsonResponse({'Exception': e, "message": "disconnected", "type": 2, "code": 100,
                                 "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})

    # 发送websocket信息
    def send_message(self, request):
        try:
            data = json.loads(request.body)
            uuid = data["uuid"]
            if uuid in websocket_info:
                if data["type"] == 1:
                    websocket_info[uuid]['ws'].send(data["message"])
                elif data["type"] == 2:
                    websocket_info[uuid]['ws'].send(json.dumps(data["message"]))
                websocket_info[uuid]["history"].append({"message": str(data["message"]), "type": 1,
                                                        "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
                return JsonResponse({'message': f'Message sent: {str(data["message"])}', "code": 200,
                                     "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
            else:
                return JsonResponse({'message': 'WebSocket 不存在', "code": 100,
                                     "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
        except Exception as e:
            return JsonResponse({f'message': {str(e)}, "code": 100,
                                 "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})

    # 获取服务端返回的消息
    def get_response(self, request):
        data = json.loads(request.body)
        uuid = data["uuid"]
        if uuid in websocket_info and websocket_info[uuid]['history']:
            return JsonResponse({'response': websocket_info[uuid]['history'][::-1], "code": 200,
                                 "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
        else:
            return JsonResponse({'error': '未查询到结果', "code": 100,
                                 "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})

    # 主动断开websocket的连接
    def disconnect_websocket(self, request):
        data = json.loads(request.body)
        uuid = data["uuid"]
        if uuid in websocket_info:
            websocket_info[uuid]['ws'].close()
            websocket_info.pop(uuid, None)
            return JsonResponse({'message': 'WebSocket 已断开连接', "code": 200})
        else:
            return JsonResponse({'message': 'WebSocket 不存在', "code": 100})

总结

1 . websocket.WebSocketApp没有定义返回连接状态的函数结果,只能自己根据实际来做判断

  1. 以上代码完成了对websocket测试的基本封装,个人愚见,仅供参考。

  2. 更多好的内容,尽在个人主页,欢迎沟通交流!!!!

相关推荐
古夕11 小时前
前端文件下载的三种方式:a标签、Blob、ArrayBuffer
前端·javascript·vue.js
武昌库里写JAVA11 小时前
Java设计模式中的几种常用设计模式
vue.js·spring boot·sql·layui·课程设计
青软青之LIMS11 小时前
自动化土壤称重分样系统
自动化·自动化土壤称重分样系统
迦蓝叶12 小时前
JAiRouter 0.8.0 发布:Docker 全自动化交付 + 多架构镜像,一键上线不是梦
java·人工智能·网关·docker·ai·架构·自动化
Q_Q196328847512 小时前
python+springboot大学生心理测评与分析系统 心理问卷测试 自动评分分析 可视化反馈系统
开发语言·spring boot·python·django·flask·node.js·php
BYSJMG12 小时前
计算机毕设推荐:基于Hadoop+Spark物联网网络安全数据分析系统 物联网威胁分析系统【源码+文档+调试】
大数据·hadoop·python·物联网·spark·django·课程设计
波波烤鸭12 小时前
Netty 实战应用:从 RPC 到即时通讯,再到 WebSocket
websocket·网络协议·rpc
wow_DG13 小时前
【Vue2 ✨】Vue2 入门之旅 · 进阶篇(九):Vue2 性能优化
javascript·vue.js·性能优化
一 乐13 小时前
美食分享|基于Springboot和vue的地方美食分享网站系统设计与实现(源码+数据库+文档)
java·vue.js·spring boot·论文·毕设·美食·地方美食分享网站系统