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 的接口自动化测试。

实战效果预览:

在这里插入图片描述

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

# -*-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没有定义返回连接状态的函数结果,只能自己根据实际来做判断
2. 以上代码完成了对websocket测试的基本封装,个人愚见,仅供参考。
3. 更多好的内容,尽在个人主页,欢迎沟通交流!!!!

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python Django自动化测试平台源码是一个基于Python和Django框架开发的系统,用于帮助开发人员进行自动化测试任务的管理和执行。它提供了一个用户友好的界面,使用户能够轻松创建、编辑和执行各种自动化测试任务。 该平台源码基于Django框架构建,因此具有良好的扩展性和稳定性。它采用了MVC架构模式,使得代码易于维护和理解。 源码中包含了多个模块,包括用户管理、任务管理、测试用例管理等。用户管理模块负责用户的注册、登录和权限管理,确保只有授权的用户才能进行测试任务的操作。任务管理模块主要用于任务的创建、编辑和执行,用户可以根据自己的需求设置不同的任务参数,并可以查看任务的执行结果。测试用例管理模块允许用户创建和编辑测试用例,以便在任务中使用。 除了以上核心模块外,源码还包含了其他一些辅助模块,如日志管理、报告生成等。日志管理模块用于记录测试任务的执行日志,方便用户追踪和排查问题。报告生成模块能够生成详细的测试报告,展示测试任务的执行结果和统计信息,方便用户进行分析和评估。 总之,Python Django自动化测试平台源码提供了一个全面且易于使用的自动化测试解决方案,使开发人员能够更高效地进行自动化测试任务的管理和执行。通过该平台,可以提高测试效率,减少人工测试的工作量,提供更高质量的软件产品。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

测开小林

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值