优点:
并发量大
缺点:
测试结果报表不丰富
jmeter通过线程启动用户,受到服务器本身限制,而locust单台服务器的并发量要远高于jmeter
locust创建任务:
#基础HttpUser
class CarRental(HttpUser):
# 被测系统的url
host: str = ""
# 随机延迟时间为2-5s
wait_time = between(2,5)
def on_start(self):
print("前置任务")
def on_stop(self):
print("后置任务")
# 定义任务 1表示任务间比例
@task(1)
#定义两种标签
@tag("load","stable")
def login(self):
# 发起请求
cs={"":"","":""}
url=self.host+""
# 发送请求
res=self.client.post(url,cs)
print(res.status_code)
assert res.status_code==200
@task(3)
@tag("load")
def load_customer(self):
cs={"":,"":}
url=""
res=self.client.get(url,params=cs)
assert res.status_code==200
@task(3)
@tag("stable")
def load_user(self):
cs = {"": , "": }
url = ""
res = self.client.get(url, params=cs)
assert res.status_code == 200
运行任务:
在项目路径下通过命令启动Locust代码:指定运行的.py文件,IP地址和端口号
执行后在浏览器访问IP:PORT进行并发用户的设置
locust -f XXX.py --web-host=IP --web-port=PORT
按照tag标签运行不同任务:
#包含标签
locust -f XXX.py --web-host=IP --web-port=PORT --tags 标签名1 标签名2
#不包含标签
locust -f XXX.py --web-host=IP --web-port=PORT --exclude-tags 标签名1 标签名2
前后置方法:
在每一个用户线程前后执行该方法,且自动进行Cookie管理
def on_start(self):
print("前置任务")
def on_stop(self):
print("后置任务")
按照功能不同划分模块:
-
主类:继承HttpUser
-
host
-
wait_time
-
tasks=() 元组的元素类型是类,默认每个任务类的执行比例1:1
-
tasks={} 字典的key是任务类,value是执行的占比
-
-
任务类:继承TaskSet
-
定义任务
-
@task
-
普通的方法,发起请求用self.client
-
-
class Main(HttpUser):
host: str = ""
#随机数
wait_time = between(2, 5)
#前置
def on_start(self):
cs = {"": "", "": ""}
url = ""
res = self.client.post(url, cs)
assert res.status_code == 200
# 加载测试任务 数据类型为元组 元组的元素是类
#tasks=(BaseManager,Sys_manager)
tasks = {BaseManager:1,Sys_manager:3}
无界面运行Locust代码:
locust -f xxx.py --headless -u XX -r XX -t XX --csv=XXX --html=XXX.html
-
-f xxx.py 要运行的py文件
-
–headless 指明用无界面的方式运行
-
-u 20 最大启动20个用户
-
-r 10 1s启动10个用户
-
-t 1m30s 运行时长
-
h小时 m分钟 s表示秒
-
1h40m
-
-
–csv=port 生成以port为前缀的csv文件
-
–html=index.html 在当前目录下生成index.html测试报告
locust运行参数:
-
基本参数
-
界面参数
-
分布式运行参数
-
运行标签
-
测试报告
locust加压模式:
- 普通加压模式:
- 自定义加压模式:创建类继承LoadTestShape重写tick方法
自定义阶梯加压模式:
class StepLoadShape(LoadTestShape):
"""
A step load shape
Keyword arguments:
step_time -- Time between steps
step_load -- User increase amount at each step
spawn_rate -- Users to stop/start per second at every step
time_limit -- Time limit in seconds
"""
#每一阶段持续时间
step_time = 30
#每次启动用户量
step_load = 10
#1s启动/关闭10个用户
spawn_rate = 10
#持续时间
time_limit = 600
def tick(self):
run_time = self.get_run_time()
if run_time > self.time_limit:
return None
current_step = math.floor(run_time / self.step_time) + 1
return (current_step * self.step_load, self.spawn_rate)