- 在编写locust脚本时,在设计综合性场景测试时,功能模块非常多,导致脚本维护较难,这时候我们就可以使用locust嵌套来让代码好维护一点了。
嵌套一:
from locust import HttpUser,TaskSet,between,task
import os,sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
PathProject = os.path.split(rootPath)[0]
sys.path.append(rootPath)
sys.path.append(PathProject)
class UserBehavior(TaskSet):
#首页
@task(50)
class Test_index(TaskSet):
@task(1)
def test_01(self):
"""
浏览首页商品列表
:return:
"""
param = {}
with self.client.post('/api/product/list', json=param) as response:
print("浏览首页商品列表")
@task(1)
def test_02(self):
"""
查看首页商品详情
:return:
"""
param = {}
with self.client.post('/api/product/detail?id=1', json=param) as response:
print("查看首页商品详情")
#我的页面
@task(50)
class Test_my(TaskSet):
@task(1)
def test_01(self):
"""
浏览订单列表
:return:
"""
param = {}
with self.client.post('/api/order/list', json=param) as response:
print("浏览订单列表")
@task(1)
def test_02(self):
"""
浏览订单详情
:return:
"""
param = {}
with self.client.post('/api/order/detail?id=1', json=param) as response:
print("浏览订单详情")
class WebsiteUser(HttpUser):
host = 'http://127.0.0.1'
tasks = [UserBehavior]
wait_time = between(1, 2)
if __name__ == '__main__':
os.system("locust -f ccc.py")
执行后查看结果:
首页和我的页面用例操作接近1比1,话说这个权重比例挺不靠谱的有时候执行次数能相差好几倍(........)

这里也存在一个问题,当虚拟用户数为1个时,程序只会选择其中一个任务类进行执行,这个虚拟用户一直在执行首页的操作

嵌套二:
from locust import HttpUser,TaskSet,between,task
import os,sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
PathProject = os.path.split(rootPath)[0]
sys.path.append(rootPath)
sys.path.append(PathProject)
# 首页
class Test_index(TaskSet):
@task(1)
def test_01(self):
"""
浏览首页商品列表
:return:
"""
param = {}
with self.client.post('/api/product/list', json=param) as response:
print("浏览首页商品列表")
@task(1)
def test_02(self):
"""
查看首页商品详情
:return:
"""
param = {}
with self.client.post('/api/product/detail?id=1', json=param) as response:
print("查看首页商品详情")
# 我的页面
class Test_my(TaskSet):
@task(1)
def test_01(self):
"""
浏览订单列表
:return:
"""
param = {}
with self.client.post('/api/order/list', json=param) as response:
print("浏览订单列表")
@task(1)
def test_02(self):
"""
浏览订单详情
:return:
"""
param = {}
with self.client.post('/api/order/detail?id=1', json=param) as response:
print("浏览订单详情")
class UserBehavior(TaskSet):
tasks = {Test_index: 1, Test_my: 1}
class WebsiteUser(HttpUser):
host = 'http://127.0.0.1'
tasks = [UserBehavior]
wait_time = between(1, 2)
if __name__ == '__main__':
os.system("locust -f ccc.py")
网友评论