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

目录

基本使用

报错处理

端口占用


基本使用

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

猜你喜欢

转载自blog.csdn.net/JBY2020/article/details/129733751