• websocket接口测试


    参考文章:websocket接口自动化集成pytest测试框架

    对比需要学习:轮询、长轮询、websocket  三者关系 

    1、工作中遇到的情况

    F12功能看到的数据

     

      

    2、python中操作ws

    (1)websocket包

    安装

    pip install websocket -i https://pypi.douban.com/simple/

    参考文章:你真的了解WebSocket吗? - 武沛齐 - 博客园

    参考视频:08 python fullstack s9day131 websocket原理剖析_哔哩哔哩_bilibili

    非常详细,就是照抄学习

    (2)flask-websocket

    参考文章:Flask教程(十九)SocketIO - 迷途小书童的Note迷途小书童的Note

    参考视频:Flask Web开发教程(十九)SocketIO_哔哩哔哩_bilibili

    代码:index.html

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>SocketIO Demotitle>
    6. <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js">script>
    7. <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.0/socket.io.js">script>
    8. head>
    9. <body>
    10. <h2>Demo of SocketIOh2>
    11. <div id="t">div>
    12. <script>
    13. $(document).ready(function () {
    14. namespace = '/dcenter';
    15. var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);
    16. socket.on('dcenter', function (res) {
    17. var t = res.data;
    18. if (t) {
    19. $("#t").append(t).append('
      '
      );
    20. }
    21. });
    22. });
    23. script>
    24. body>
    25. html>

     fw.py

    1. # -*- coding:utf-8 -*-
    2. """
    3. 基于flask开发websocket服务
    4. 使用的包是flask-socketio
    5. """
    6. from flask import Flask, render_template
    7. from flask_socketio import SocketIO, emit
    8. app = Flask(__name__)
    9. app.config['SECRET_KEY'] = 'secret_key'
    10. socketio = SocketIO()
    11. socketio.init_app(app, cors_allowed_origins='*')
    12. name_space = '/dcenter'
    13. @app.route('/')
    14. def index():
    15. return render_template('index1.html')
    16. @app.route('/push')
    17. def push_once():
    18. event_name = 'dcenter'
    19. broadcasted_data = {'data': "test message!"}
    20. socketio.emit(event_name, broadcasted_data, broadcast=False, namespace=name_space)
    21. return 'done!'
    22. @socketio.on('connect', namespace=name_space)
    23. def connected_msg():
    24. print('client connected.')
    25. @socketio.on('disconnect', namespace=name_space)
    26. def disconnect_msg():
    27. print('client disconnected.')
    28. @socketio.on('my_event', namespace=name_space)
    29. def mtest_message(message):
    30. print(message)
    31. emit('my_response',
    32. {'data': message['data'], 'count': 1})
    33. if __name__ == '__main__':
    34. socketio.run(app, host='127.0.0.1', port=5000, debug=True)

    安装

    python39 -m pip install --upgrade Flask-SocketIO                升级到了最高版本

    python39 -m pip install --upgrade python-socketio==4.6.0   升级到指定版本

    python39 -m pip install python-engineio==3.13.2                  安装指定版本

    实际操作版本介绍:

    eventlet                       0.33.1

    python-engineio           4.3.4
    python-socketio           5.7.2
    Flask                           2.2.2
    Flask-SocketIO           5.3.1
    Python                        3.9.4

     代码与参考文章一致

    重点:!!!!!!!!!!!!!!!!!!!!!!!!

    下图问题原因:

    The client is using an unsupported version of the Socket.IO or Engine.IO protocols

    python - The client is using an unsupported version of the Socket.IO or Engine.IO protocols Error - Stack Overflow

    版本不匹配的原因,下面的链接找到的答案:方式就是根据socket.io版本降低,或者升高socket.io的版本

    在python-socketio的官网有说明:https://pypi.org/project/python-socketio/

     根据我安装的python-socketio的版本升高js的socket.io版本

    //cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.0/socket.io.js

    3、ws接口mock

    实际使用操作一波

    4、ws接口测试

    安装

    pip install websocket -i https://pypi.douban.com/simple/

    pip install websocket-client

    clinet.py

    1. # -*- coding:utf-8 -*-
    2. class websocketclient:
    3. def __init__(self):
    4. self.host = 'wss://url'
    5. def send(self, params):
    6. try:
    7. self.ws.send(params)
    8. print(f'发送数据成功:{params}')
    9. except Exception as e:
    10. print(f'发送数据{params}失败')
    11. def recv(self):
    12. try:
    13. res = self.ws.recv()
    14. print(f'接收数据成功:{res}')
    15. return res
    16. except Exception as e:
    17. print(f'接收数据{res}失败')
    18. return ''

    imserver_api.py

    1. # -*- coding:utf-8 -*-
    2. import websocket
    3. from nomalstudy.client import websocketclient
    4. class ImServerApi(websocketclient):
    5. def __init__(self, timeout=5):
    6. super(ImServerApi, self).__init__()
    7. self.url = f'{self.host}/urgeSocket?_token=6t6OGmrt3xm1SYqDRFrUUeHVhLvHvMVKJQ3UBxaQ4kK9RMde&_appType=receive'
    8. self.ws = websocket.create_connection(self.url, timeout=timeout)

    test_websocket_api.py

    1. # -*- coding:utf-8 -*-
    2. import json
    3. import pytest
    4. from nomalstudy.imserver_api import ImServerApi
    5. class TestImServerApi:
    6. kfid = '' # 定义客服id,全局变量作为各个测试用例的关联数据
    7. def setup_class(self):
    8. self.im = ImServerApi() # 创建一个websocket协议的接口对象
    9. # 测试客服匹配
    10. def test_match(self):
    11. params = {
    12. "msgId": "111",
    13. "type": "match",
    14. "from": "shamo",
    15. "to": "system"
    16. }
    17. self.im.send('heartbeat')
    18. res = self.im.recv()
    19. assert res == 'heartbeat'
    20. # res = json.loads(res) # 将其转换成json对象
    21. # assert res['code'] == '0'
    22. # 提取msg,msg是匹配到的客服id
    23. # self.__class__.kfid = res['msg']
    24. # 测试给客服发送正常消息
    25. def test_message(self):
    26. params = {
    27. "msgId": "111",
    28. "type": "normal",
    29. "from": "admin",
    30. "to": f"{self.__class__.kfid}",
    31. "msg": "你好"
    32. }
    33. self.im.send(json.dumps(params))
    34. res = self.im.recv()
    35. res = json.loads(res) # 将其转换成json对象
    36. pytest.assume(res['code'] == '0', f'期望值是0,实际结果是{res["code"]}')
    37. pytest.assume(res['msg'] == 'push success', f'期望值是0,实际结果是{res["msg"]}')
    38. # 再次接收客服发来的数据
    39. res = self.im.recv()
    40. res = json.loads(res) # 将其转换成json对象
    41. pytest.assume(res['code'] == '0', f'期望值是0,实际结果是{res["code"]}')
    42. pytest.assume(res['msg'] == '同学,你好,非常高兴为你服务,有什么需要我帮忙的呢?', f'期望值是0,实际结果是{res["msg"]}')
    43. # 测试发送数据时消息是空的
    44. def test_message_msgisnull(self):
    45. params = {
    46. "msgId": "111",
    47. "type": "normal",
    48. "from": "admin",
    49. "to": f"{self.kfid}",
    50. "msg": ""
    51. }
    52. self.im.send(json.dumps(params))
    53. res = self.im.recv()
    54. res = json.loads(res) # 将其转换成json对象
    55. # 断言系统推送消息时对于消息的判断
    56. pytest.assume(res['code'] == '1', f'期望值是1,实际结果是{res["code"]}')
    57. pytest.assume(res['msg'] == '消息内容为空', f'期望值是0,实际结果是{res["msg"]}')

  • 相关阅读:
    从底层结构开始学习FPGA(6)----分布式RAM(DRAM,Distributed RAM)
    Vue3.2+TypeScript管理模块记录1-登录模块
    Python中的HTTP高手:如何玩转requests模块
    2022年全球光纤连接市场将达50.1亿美元
    首饰饰品经营商城小程序的作用是什么
    ONNX OpenVino TensorRT MediaPipe NCNN Diffusers
    API经济下新物种的诞生
    服务老是被攻击,如何设计一套比较安全的接口访问策略?
    MySQL中的事务
    BUUCTF 秘密文件 1
  • 原文地址:https://blog.csdn.net/chenchen_nini/article/details/127534427