性能测试框架——python+locust(二)使用及报错处理、重启运行时端口占用处理

文章介绍了使用Locust进行接口测试的基本步骤,包括任务权重设置、登录操作、获取用户信息和报警列表。同时,文章详细讨论了几个常见的错误处理场景,如请求协议缺失、Content-Type错误以及端口占用问题,并给出了相应的解决方案。
摘要由CSDN通过智能技术生成

目录

基本使用

报错处理

端口占用


基本使用

import os
from locust import TaskSet, task, HttpUser, between, tag
from pprint import pprint
from load_data import get_data, user_mames, jqbh


class Test(TaskSet):  # 创建任务类
    def on_start(self):  # 初始化
        self.login()

    def login(self):
        self.headers = {
            "user-agent": "Dart/2.16 (dart:io)",
            "content-type": "application/json; charset=utf-8",
            "accept-encoding": "gzip",
            "content-length": "64",
            "host": "xxxxx"}
        json = {
            "username": get_data(user_mames),
            "password": "xxxxxx"
        }
        req = self.client.post('/user/oauth2/password', headers=self.headers, json=json, name='登录')
        self.user_token = req.json()['result']['jwt_token']
        # pprint(req.json()['result']['jwt_token'])  # 打印用户token
        self.headers["jwt-token"] = self.user_token  # 添加token到请求头中

    @tag('test1', 'test2')  # 设置标签
    @task(1)  # @task(1)中的数字表示任务的权重,数值越大表示执行的频率越高
    def get_UserInfo(self):
        userdata = self.client.get('/user/getUserInfo', headers=self.headers, name='获取用户信息')
        # pprint(userdata.json())   # 打印用户信息数据

    @tag('test2')
    @task(10)
    def get_AlarmList(self):
        json = {
            "pageNo": 0,
            "pageSize": 20,
            "mark": [],
        }
        AlarmList_data = self.client.post('/alarm/getAlarmList', headers=self.headers, json=json, name='查询jq列表')
        pprint(AlarmList_data.json())

    @task  # 不设置权重时,默认为1
    def get_AlarmBookList(self):
        json = {
            "jqbh": "20230301155826A",
            "pageSize": 20
        }
        AlarmBookList_data = self.client.post('/alarmBook/getAlarmBookList', headers=self.headers, json=json,
                                              name='查询jqws列表')
        pprint(AlarmBookList_data.json())

    def on_stop(self):  # 清除初始化,相当于teardown
        print('初始化清除')


class BI(HttpUser):  # 创建用户类
    # wait_time = between(3.0, 8.0)  # 设置运行过程中的间隔时间,需要在locust中引入between
    tasks = [Test]
    min_wait = 1000  # min_wait :执行事务之间用户等待时间的下界(单位:毫秒)
    max_wait = 5000  # 执行事务之间用户等待时间的上界(单位:毫秒)
    host = 'xxxx'

if __name__ == '__main__':
    os.system('locust -f main.py --tag test2')

部分功能说明:

  • 权重设置:@task装饰器加到定义的方法前面表示这个方法就是一个可执行任务,装饰方法中可以添加数字(@task(2)),表示执行任务的执行次数的比例(即权重)。
  • 响应断言:请求中添加断言必须在请求方法中设置catch_ response参数,值为True,响应断言如下
  with self.client.get('/', catch_response = True) as response:
            if response.status_code == 200:
                response.success()
            else:
                response.failure('Failed!')
  • 等待时间:wait_time = between(5, 9),使用between函数,可以在指定的最大值和最小值之间随机选择时间。
  • 标签过滤:在执行时可通过指定先关的标签来执行或者不执行对应的接口(挑选标签[--tag],参数后面为需要执行的接口,多个标签之间用空格分开;排除标签[--exclude-tags],参数后面的标签相关的接口不被执行,其他的将执行)

报错处理

请求协议缺失报错

报错信息:

File "D:\python\lib\site-packages\requests\sessions.py", line 792, in get_adapter
    raise InvalidSchema(f"No connection adapters were found for {url!r}")
requests.exceptions.InvalidSchema: No connection adapters were found for '117.57.107.86:48800/police-app/app-server/'

处理方式:

url = "127.0.0.1:xxxx",可在请求的地址前添加http:// 或https://

接口访问报错

报错信息:

{'code': '-1', 'message': "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported", 'status': 400, 'timeElapsed': 1, 'timestamp': 1676265488186}

处理方式:

无论是POST请求还是GET请求都是可以通过这种方式成功获取参数,但是如果前端POST请求中的body是Json对象的话,会报上述错误,需要给请求参数前指明参数名。

# 报错前:
        req = self.client.post('/user/oauth2/password',
                               {"username": "br", "password": "NO8tDZXEhvpiMYcI47amQA=="})

# 处理后:
        req = self.client.post('/user/oauth2/password',
                              json =  {"username": "br", "password": "NO8tDZXEhvpiMYcI47amQA=="})

Content-Type类型错误

知识点——Content-Type常见的三种格式:

  • Content-Type: application/json,如果没有特别声明,appiationl/son是Asios默认的Content-ype,也是我最常用的一种,它声明了请求体中的数据将会以json字符串的形式发送到后端。
  • Content-Type: application/x-www-form-urlencoded,声明了请求体中的数据会以键值对(普通表单形式)发送到后端,这种类型是Ajax默认的。
  • Content-Type: multipart/form-data,一般用来上传文件,指定传输数据为二进制数据,也可以是键值对的形式。

报错信息:

"Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported"

原因及处理方式:

此问题的原因是因为前后端数据交互出现json数据类型不符合
json 分为两种类型;
(1) json 对象类型,即前端定义的Content type 为 application/x-www-form-urlencoded等
(2) json字符串类型,即前端定义的Content type 为 application/json
解决办法
前端传输的json数据类型和后端使用的注解应有正确的对应关系

端口占用

windows查询及清除占用端口

查询所有正在运行的端口:netstat -ano

提示:‘netstat’不是内部或外部命令,也不是可运行的程序。解决方法:环境变量中添加path(;%SystemRoot%\system32)

通过pid查看进程:tasklist | findstr pid

查看被占用的端口pid:netstat -aon |findstr “8089”

杀死指定的pid进程:taskkill  -t -f /pid pid号

taskkill是Windows命令行里终止指定程序“进程”的命令:
参数:/f 表示强制终止
/im 表示指定的进程名称,例如“explor.exe",例:taskkill /f /im java.exe
/pid 表示指定的进程ID进程号,  例 :taskkill /f /pid 7176

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用PythonLocust来进行对ES7的压测。首先,确保你已经安装了PythonLocust。 接下来,你需要安装elasticsearch-py库,它是Python与Elasticsearch进行交互的库。可以使用以下命令安装: ``` pip install elasticsearch ``` 然后,创建一个Python脚本,导入必要的模块和库: ```python from locust import HttpUser, task, between from elasticsearch import Elasticsearch class ESUser(HttpUser): wait_time = between(1, 5) def on_start(self): # 创建一个Elasticsearch客户端连接 self.client = Elasticsearch(['localhost:9200']) @task def search(self): # 定义一个搜索任务 query = { "query": { "match_all": {} } } # 发送搜索请求 response = self.client.search(index='your_index', body=query) # 打印搜索结果 print(response) ``` 在上面的代码中,我们创建了一个名为ESUser的Locust用户类。在`on_start`方法中,我们创建了一个Elasticsearch客户端连接。 然后,在`@task`装饰的`search`方法中,我们定义了一个搜索任务。你可以根据自己的需求修改查询条件。在该方法中,我们发送了一个搜索请求,并打印了搜索结果。 最后,你可以在命令行中使用Locust命令来启动压测: ``` locust -f your_script.py --host=http://localhost:9200 ``` 替换`your_script.py`为你的脚本文件名,`http://localhost:9200`为你的ES7的地址。 然后,你可以在浏览器中访问Locust的Web界面(默认为http://localhost:8089)来配置并启动压测。 注意:在进行压测之前,请确保你已经在ES7中创建了索引,并且数据已经准备好。另外,压测会对目标系统造成一定的负载,请谨慎使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值