解决locust新版本性能测试报错
问题描述
代码如下:
from locust import TaskSet,HttpLocust
# 定义任务
def login(l):
l.client.post("/login", data={"username": "admin", "password": "123456"})
def index(l):
l.client.get("/index")
def profile(l):
l.client.get("/profile")
def logout(l):
l.client.post("/logout")
class UserBehavior(TaskSet):
tasks = {index: 3, profile: 1}
def on_start(self):
login(self)
def on_stop(self):
logout(self)
class WebsiteUser(HttpLocust):
task_set = UserBehavior
min_wait = 2000
max_wait = 3000
host = "http://www.baidu.com"
weight = 10
问题1
报错信息如下:
ImportError: The HttpLocust class has been renamed to HttpUser in version 1.0. For more info see: https://docs.locust.io/en/latest/changelog.html#changelog-1-0
解决方法
将从locust中导入的HttpLocust改为HttpUser,即from locust import HttpLocust改为from locust import HttpUser,将脚本中引用的所有HttpLocust都改为HttpUser.
问题2:
报错信息如下
No tasks defined on WebsiteUser. Use the @task decorator or set the 'tasks' attribute of the User (or mark it as abstract = True if you only intend to subclass it)
解决方法
把task_set = UserBehavior
改成tasks = [UserBehavior]
即可,UserBehavior
指的是你继承TaskSet
的那个子类
问题原因
locust进入1.x版本后,语法发生相应变化
问题解决
代码如下:
from locust import TaskSet, HttpUser
# 定义任务
def login(l):
l.client.post("/login", data={"username": "admin", "password": "123456"})
def index(l):
l.client.get("/index")
def profile(l):
l.client.get("/profile")
def logout(l):
l.client.post("/logout")
class UserBehavior(TaskSet):
tasks = {index: 3, profile: 1}
def on_start(self):
login(self)
def on_stop(self):
logout(self)
class WebsiteUser(HttpUser):
tasks = [UserBehavior]
min_wait = 2000
max_wait = 3000
host = "http://www.baidu.com"
weight = 10