用Python进行websocket接口测试

这篇文章主要介绍了用Python进行websocket接口测试,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下

我们在做接口测试时,除了常见的http接口,还有一种比较多见,就是socket接口,今天讲解下怎么用Python进行websocket接口测试。

Socket

Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求,使主机间或者一台计算机上的进程间可以通讯。

Python 中,我们使用 socket 模块的 socket 函数来创建一个 socket 对象。语法格式如下:

复制代码
socket.socket ( family ,type ,proto)

现在大多数用的都是websocket,那我们就先来安装一下websocket的安装包。

复制代码
pip install websocket-client

安装完之后,我们就开始我们的websocket之旅了。

在websocket里,我们有常用的这几个方法:

on_message方法

复制代码
def on_message(ws, message):
  print(message)

on_message是用来接受消息的,server发送的所有消息都可以用on_message这个方法来收取。

on_error方法:

复制代码
def on_error(ws, error):
  print(error)

这个方法是用来处理错误异常的,如果一旦socket的程序出现了通信的问题,就可以被这个方法捕捉到。

on_open方法:

复制代码
def on_open(ws):
  def run(*args):
    for i in range(30):
      # send the message, then wait
      # so thread doesn't exit and socket
      # isn't closed
      ws.send("Hello %d" % i)
      time.sleep(1)

    time.sleep(1)
    ws.close()
    print("Thread terminating...")

  Thread(target=run).start()

on_open方法是用来保持连接的,上面这样的一个例子,就是保持连接的一个过程,每隔一段时间就会来做一件事,他会在30s内一直发送hello。最后停止。

on_close方法:

复制代码
def on_close(ws):
  print("### closed ###")

onclose主要就是关闭socket连接的。

如何创建一个websocket应用:

复制代码
ws = websocket.WebSocketApp("wss://echo.websocket.org")

括号里面就是你要连接的socket的地址,在WebSocketApp这个实例化的方法里面还可以有其他参数,这些参数就是我们刚刚介绍的这些方法。

复制代码
ws = websocket.WebSocketApp("ws://echo.websocket.org/",
              on_message=on_message,
              on_error=on_error,
              on_close=on_close)

完整代码:

复制代码
import websocket
from threading import Thread
import time
import sys

def on_message(ws, message):
  print(message)

def on_error(ws, error):
  print(error)

def on_close(ws):
  print("### closed ###")

def on_open(ws):
  def run(*args):
    for i in range(3):
      # send the message, then wait
      # so thread doesn't exit and socket
      # isn't closed
      ws.send("Hello %d" % i)
      time.sleep(1)

    time.sleep(1)
    ws.close()
    print("Thread terminating...")

  Thread(target=run).start()


if __name__ == "__main__":

  websocket.enableTrace(True)
  host = "ws://echo.websocket.org/"
  ws = websocket.WebSocketApp(host,
                on_message=on_message,
                on_error=on_error,
                on_close=on_close)
  ws.on_open = on_open
  ws.run_forever()

也可以使用python进行websocket的客户端压力测试。

复制代码
# -*- coding:utf-8 -*-
# __author__ == 'chenmingle'
 
import websocket
import time
import threading
import json
import multiprocessing
import uuid
from threadpool import ThreadPool, makeRequests
 
# 修改成自己的websocket地址
WS_URL = "xxxx"
# 定义进程数
processes = 4
# 定义线程数(每个文件可能限制1024个,可以修改fs.file等参数)
thread_num = 700
index = 1
 
 
def on_message(ws, message):
 # print(message)
 pass
 
 
def on_error(ws, error):
 print(error)
 pass
 
 
def on_close(ws):
 # print("### closed ###")
 pass
 
 
def on_open(ws):
 global index
 index = index + 1
 
 def send_thread():
  # 设置你websocket的内容
  # 每隔10秒发送一下数据使链接不中断
  while True:
   ws.send(u'hello服务器')
   time.sleep(10)
 
 t = threading.Thread(target=send_thread)
 t.start()
 
 
def on_start(num):
 time.sleep(5)
 # websocket.enableTrace(True)
 ws = websocket.WebSocketApp(WS_URL + str(num),
        on_message=on_message,
        on_error=on_error,
        on_close=on_close)
 ws.on_open = on_open
 ws.run_forever()
 
 
def thread_web_socket():
 # 线程池
 pool_list = ThreadPool(thread_num)
 num = list()
 # 设置开启线程的数量
 for ir in range(thread_num):
  num.append(ir)
 requests = makeRequests(on_start, num)
 [pool_list.putRequest(req) for req in requests]
 pool_list.wait()
 
 
if __name__ == "__main__":
 # 进程池
 pool = multiprocessing.Pool(processes=processes)
 # 设置开启进程的数量
 for i in xrange(processes):
  pool.apply_async(thread_web_socket)
 pool.close()
 pool.join()

以上就是用Python进行websocket接口测试的详细内容。


最后

如果你想学习自动化测试,那么下面这套视频应该会帮到你很多

如何逼自己1个月学完自动化测试,学完即就业,小白也能信手拈来,拿走不谢,允许白嫖....

最后我这里给你们分享一下我所积累和整理的一些文档和学习资料,有需要直接领取就可以了!

以上内容,对于软件测试的朋友来说应该是最全面最完整的备战仓库了,为了更好地整理每个模块,我也参考了很多网上的优质博文和项目,力求不漏掉每一个知识点,很多朋友靠着这些内容进行复习,拿到了BATJ等大厂的offer,这个仓库也已经帮助了很多的软件测试的学习者,希望也能帮助到你。

​​

​​​​

相关推荐
databook2 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar3 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780513 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_3 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机10 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机11 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机11 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机11 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i11 小时前
drf初步梳理
python·django
每日AI新事件11 小时前
python的异步函数
python