Locust负载测试

官方文档:https://docs.locust.io/en/stable/index.html
第1章 安装
pip install locustio
查看locust帮助
locust --help
第2章 快速入门
locustfile.py例子:

from locust import HttpLocust,TaskSet,task,between

class UserBehavior(TaskSet):
	def on_start(self):
		"""on_startiscalledwhenaLocuststartbeforeanytaskisscheduled"""
		self.login()
	
	def on_stop(self):
		"""on_stopiscalledwhentheTaskSetisstopping"""
		self.logout()
	
	def login(self):
		self.client.post("/login",{"username":"ellen_key","password":"education"})
	
	def logout(self):
		self.client.post("/logout",{"username":"ellen_key","password":"education"})
	
	@task(2)
	def index(self):
		self.client.get("/")
	
	@task(1)
	def profile(self):
		self.client.get("/profile")

class WebsiteUser(HttpLocust):
	task_set=UserBehavior
	wait_time=between(5.0,9.0)
#事务执行时间间隔,另一种写法,单位为毫秒
#min_wait=5000
#max_wait=9000

2.1 启动locust
cmd命令窗口输入命令:
在单台机器上运行Locust
locust -f locust_files/my_locust_file.py --host http://www.badiu.com
多进程之间运行locust,需要指定主进程,然后会启动任意从属进程
locust -f locust_files/my_locust_file.py --master5
locust -f locust_files/my_locust_file.py --slave
在多台机器上运行Locust
locust -f locust_files/my_locust_file.py --slave --master-host=192.168.0.100
第3章 写一个locustfile
3.1 Locust类
一个locust类代表一个用户。Locust类的一些典型属性
task_set属性
task_set:指向TaskSet类,这个类定义了用户的行为。
wait_time属性
wait_time:它用于确定模拟用户在执行任务之间将等待多长时间。Locust提供了一些内置的函数,返回一些常用的wait_time方法(between\constant\constant_pacing)。如

class MyTaskSet(TaskSet):
	@task
	def my_task(self):
		print("executingmy_task")

class User(Locust):
	task_set=MyTaskSet
#事务之间执行时间间隔5~15秒
wait_time=between(5,15)

weight属性
weight:当一个文件中有1个以上Locust类,并且命令行中没有指定哪个Locust类时,将会从中随机选取一个Locust类。否则,可以像这样从同一个文件中指定要使用哪些Locust类:
locust -f locust_file.py WebUserLocust MobileUserLocust
如果你想让这些Locust类中的一个执行得更频繁,你可以给这些类设置一个权重属性。例如,WebUserLocust的可能性是MobileUserLocust的三倍:


```python
class WebUserLocust(Locust):
	weight=3
	...

class MobileUserLocust(Locust):
	weight=1
	...

host属性
host:主机属性是要加载的主机的URL前缀(即“http://google.com”)。通常,这是在Locust的web UI或命令行中指定的,在启动Locust时使用--host选项。如:
locust  -f  E:\python_workspace\locust\locustfile.py  --host  http://r.lmjh.me/Manage MyLocust2  MyLocust1
3.2 TaskSet类
TaskSet是任务的集合。每个Locust类必须有一个指向TaskSet的task_set属性集
声明task
使用task装饰器,如

```python
from locust import Locust,TaskSet,task

class MyTaskSet(TaskSet):
	@task
	def my_task(self):
	print("Locustinstance(%r)executingmy_task"%(self.locust))

classMyLocust(Locust):
	task_set=MyTaskSet

task属性
指定事务的执行比例,即权重。下面例子task2执行次数是task1的2倍

from locust import Locust,TaskSet,task
from locust.wait_time import between

class MyTaskSet(TaskSet):
	wait_time=between(5,15)
	
	@task(3)
	def task1(self):
		pass
	
	@task(6)
	def task2(self):
		pass

class MyLocust(Locust):
	task_set=MyTaskSet

tasks属性也可以是python调用列表,或者是字典。例子:

from locust import Locust,TaskSet

def my_task(l):
	pass

class MyTaskSet(TaskSet):
	tasks=[my_task]

class MyLocust(Locust):
	task_set=MyTaskSet

tasks属性是一个列表时,每次执行随机从列表中选择一个任务。如果tasks参数是一个字典,callable作为关键字,int作为执行比例(权重),下面例子my_task执行次数是another_task的3倍。
{my_task:3,another_task:1}
TaskSets任务集可以嵌套
使用tasks属性引用另一个TaskSet类,例如:

class ForumPage(TaskSet):
	@task(20)
	def read_thread(self):
		pass
	
	@task(1)
	def new_thread(self):
		pass
	
	@task(5)
	def stop(self):
		self.interrupt()

class UserBehaviour(TaskSet):
	tasks={ForumPage:10}

	@task
	def index(self):
		pass

上面例子中,当执行 UserBehaviour时会先执行ForumPage。interrupt()方法必不可少的,用来停止执行ForumPage ,如果没使用该方法,这个ForumPage任务一旦开始就i不会停止运行。可以给interrupt()定义权重。
也可以使用@task装饰器在类中内联声明嵌套的TaskSet,就像声明普通任务一样,例如:

classMyTaskSet(TaskSet):
	@task
	class SubTaskSet(TaskSet):
		@task
		def my_task(self):
			pass

3.3 TaskSequence 类
TaskSequence类是一个TaskSet,但是它的任务是按顺序执行的。可以在tasksequence中嵌套任务集,反之亦然。例如:

from locust import HttpLocust,TaskSet,task,TaskSequence,seq_task
class MyTaskSequence(TaskSequence):
	@seq_task(1)
	def first_task(self):
		pass
	
	@seq_task(2)
	def second_task(self):
		pass
	
	@seq_task(3)
	@task(10)
	def third_task(self):
		pass

3.4 Setups, Teardowns, on_start, and on_stop方法
Locust级支持setup 和 teardown;TaskSet级支持setup 和 teardown、on_start 和 on_stop。这些方法只运行一次。setup在任务开始前运行,teardown在所有任务完成和Locust退出之后执行。
当有许多初始化和清除时,执行顺序如下:
1.Locust setup
2.TaskSet setup
3.TaskSet on_start
4.TaskSet tasks
5.TaskSet on_stop
6.TaskSet teardown
7.Locust teardown

3.4 发出HTTP请求
HttpLocust类,使用此类时,每个实例会得到一个client属性,该属性是HttpSession的一个实例,可用来发出HTTP请求。

from locust import HttpLocust,TaskSet,task,between

class MyTaskSet(TaskSet):
	@task(2)
	def index(self):
		self.client.get("/")
	
	@task(1)
	def about(self):
		self.client.get("/about/")

class MyLocust(HttpLocust):
	task_set=MyTaskSet
	wait_time=between(5,15)

请求方法有:get、post、put、delete、head、patch、options
如post请求
response=self.client.post("/login",{“username”:“testuser”,“password”:“secret”})

手动控制一个请求是成功还是失败
通过使用catch_response参数和with语句,将一个请求标记为失败(即使请求是成功的)或成功(即使请求是失败的)。

with self.client.get("/",catch_response=True)as response:
	if response.content!=b"Success":
		response.failure("Got wrong response")

with self.client.get("/does_not_exist/",catch_response=True)as response:
	if response.status_code==404:
		response.success()

使用动态参数将请求分组到url

#Statisticsfortheserequestswillbegroupedunder:/blog/?id=[id]
for I in range(10):
	self.client.get("/blog?id=%i"%i,name="/blog?id=[id]")

第4章 分布式运行Locust
一台机器不能满足你所需要的虚拟用户数,Locust支持在多台设备上运行负载测试。
主模式使用–master,主节点自己不能模拟用户数。子节点使用–slave,和–master-host一起使用(来指定主节点的IP或主机名)。
注意:主节点和字节点机器,在分布式运行时必须都有locust测试脚本的副本。分布式运行时还需要注意的是,虚拟用户数建议大于locust类个数*节点数。
例子:
在主模式启动locust
locust -f my_locustfile.py --master
在一个字节点上输入:
locust -f my_locustfile.py --slave --master-host=192.168.0.14

4.1选项(可通过locust --help命令查看)
–master -port=5557 用来设置主节点的端口,默认为5557
4.2使用Docker运行分布式
4.3无webUI界面运行分布式
4.4增加Locust的性能
第5章 无web界面运行Locust
命令:
locust -f locust_files/my_locust_file.py --no-web -c 1000 -r 100
–no-web代表无界面模式,-c虚拟用户数,-r每秒增加的用户数
5.1对测试设置时限
使用–run-time 或 -t 选项来对一个测试指定测试时间(注意这个选项只能在no web模式下使用):
locust -f --no-web -c 1000 -r 100 --run-time 1h30m
5.2 无web界面运行Locust分布式
在主节点命令中使用–expect-slaves选项
locust -f my_locustfile.py --no-web -c 3 -r 1 --master --expect-slave
第6章 使用更快的HTTP客户端提高Locust的性能
在很多情况下,我们建议使用默认的HttpLocust,请求。如果您计划运行真正大规模的测试,Locust提供了一个替代的HTTP客户端FastHttpLocust,它使用geventhttpclient而不是请求。geventhttpclient客户端要快得多,我们看到http请求的性能提高了5倍到6倍。
引入FastHttpLocust:from locust.contrib.fasthttp import FastHttpLocust
使用方法,将HttpLocust替换成FastHttpLocust,如:

from locust import TaskSet,task,between
from locust.contrib.fasthttp import FastHttpLocust

class MyTaskSet(TaskSet):
	@task
	def index(self):
		response=self.client.get("/")

class MyLocust(FastHttpLocust):
	task_set=MyTaskSet
	wait_time=between(1,60)

第7章 检索CSV格式的测试统计数据
获取测试统计数据CSV文件,两种方式:1.在Locust网站的Download Data里下载;
2.在no web模式下获取CSV文件,使用–csv=example 选项会定期保存2个CSV文件,文件名称将命名为example_distribution.csv和 example_requestes.csv。命令:locust -f examples/basic.py --csv=example --no-web -t10m
例子:locust -f E:\python_workspace\locust\locustfile2.py --host http://r.lmjh.me/Manage --csv=D:\example --no-web -t 30s可以自定义统计数据写入CSV文件的频率,默认是2s:
import locust.stats
locust.stats.CSV_STATS_INTERVAL_SEC=5 #defaultis2seconds

第7章 使用自定义客户端测试其他系统(略)
Locust以HTTP为主要目标而构建。 但是,通过编写触发request_success和request_failure事件的自定义客户端,可以轻松扩展它以对任何基于请求/响应的系统进行负载测试。查看更多:https://docs.locust.io/en/0.13.2/testing-other-systems.html

第8章 Locust扩展
8.1事件件监听
Locust带有许多事件,这些事件提供了以不同方式扩展locust的钩子。事件侦听器可以在模块级别上的locust文件中注册。 这是一个例子
from locust import events

def my_success_handler(request_type,name,response_time,response_length,**kw):
print(“Successfully fetched:%s”%(name))
events.request_success+=my_success_handler
8.2添加Web路径
Locust使用Flask来提供Web UI,因此很容易将Web端点添加到Web UI。 只需将Flask应用程序导入您的locustfile并设置一条新路径:
from locust import web

@web.app.route("/added_page")
def my_added_page():
return “Anotherpage”
现在,你应该能够启动locust并浏览到http://127.0.0.1:8089/added_page

第9章,日志(Logging)
Locust带有基本的日志记录配置,该配置可以选择使用–loglevel和/或–logfile来修改配置。 如果要控制日志记录配置,则可以提供–skip-log-setup标志,该标志将忽略其他参数。
选项:
–skip-log-setup 禁用Locust的日志记录设置。 而是由Locust测试或Python默认设置提供配置。
–loglevel 在DEBUG/INFO/WARNING/ERROR/CRITICAL之间选择。 默认值为INFO。 简写为-L。
–logfile 指定日志文件的路径(–logfile D:\locust_log.txt)。 如果未设置,日志将转到stdout / stderr

第10章 API(略)
第11章 第三方工具
使用其他语言
11.1 Glang
Boomer
11.2 Java
Locust4j
Swarm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值