Locust安装
1、安装Python:
安装Python2 或Python3
2、安装Locuse
2.1, 通过pip命令安装 /> pip install locustio
2.2, 通过GitHub上克隆项目安装(Python3推荐):https://github.com/locustio/locust
编写简单的性能测试脚本
创建load_test.py文件,通过Python编写性能测试脚本。
from locust import HttpLocust, TaskSet, task class UserBehavior(TaskSet): @task(1) def baidu(self): self.client.get("/") class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 3000 max_wait = 6000
创建UserBehavior()类继承TaskSet类,为用户行为。
创建baidu() 方法表示一个行为,访问百度首页。用@task() 装饰该方法为一个任务。1表示一个Locust实例被挑选执行的权重,数值越大,执行频率越高。在当前UserBehavior()行为下只有一个baidu()任务,所以,这里的权重设置为几,并无影响。
WebsiteUser()类用于设置性能测试。
task_set :指向一个定义了的用户行为类。
min_wait :用户执行任务之间等待时间的下界,单位:毫秒。
max_wait :用户执行任务之间等待时间的上界,单位:毫秒。
运行性能测试
切换到性能测试脚本所在的目录,启动性能测试:
------------------------------------------------------------------
.../> locust -f load_test.py --host=https://www.baidu.com
[2016-11-19 22:38:16,967] fnngj-PC/INFO/locust.main: Starting web monitor at *:8089
[2016-11-19 22:38:16,967] fnngj-PC/INFO/locust.main: Starting Locust 0.7.5
-----------------------------------------------------------------
load_test.py 为测试脚本,https://www.baidu.com 为测试的网站。
打开浏览器访问:http://127.0.0.1:8089
如果引起了你的兴趣,剩下的你自个玩吧!难点在性能测试脚本的编写上。
参考文档:http://docs.locust.io/en/latest/quickstart.html
http://www.cnblogs.com/fnng/p/6081798.html
性能测试参数
-
Type: 请求的类型,例如GET/POST。
-
Name:请求的路径。这里为百度首页,即:https://www.baidu.com/
-
request:当前请求的数量。
-
fails:当前请求失败的数量。
-
Median:中间值,单位毫秒,一半的服务器响应时间低于该值,而另一半高于该值。
-
Average:平均值,单位毫秒,所有请求的平均响应时间。
-
Min:请求的最小服务器响应时间,单位毫秒。
-
Max:请求的最大服务器响应时间,单位毫秒。
-
Content Size:单个请求的大小,单位字节。
-
reqs/sec:是每秒钟请求的个数。
from locust import HttpLocust, TaskSet, task
class UserTask(TaskSet):
@task
def job(self):
with self.client.get('/', catch_response = True) as response:
if response.status_code == 200:
response.failure('Failed!')
else:
response.success()
class User(HttpLocust):
task_set = UserTask
min_wait = 1000
max_wait = 3000
host = "https://www.baidu.com"
from locust import HttpLocust, TaskSet, task
from random import randint
# Web性能测试
class UserBehavior(TaskSet):
def on_start(self):
self.login()
# 随机返回登录用户
def login_user():
users = {"user1":123456,"user2":123123,"user3":111222}
data = randint(1, 3)
username = "user"+str(data)
password = users[username]
return username, password
@task
def login(self):
username, password = login_user()
self.client.post("/login_action", {"username":username, "password":password})
class User(HttpLocust):
task_set = UserTask
min_wait = 1000
max_wait = 3000
host = "http://www.xxx.com"