catch_response = True :布尔类型,如果设置为 True, 允许该请求被标记为失败。
from locust import HttpUser, task, TaskSet
# 定义用户行为(测试用例)
class TestCase(TaskSet):
@task()
def index(self):
self.client.get('/HelloWorld') # 访问路径
@task()
def index1(self):
with self.client.get('/HelloWorld4', catch_response=True) as response:
if response.status_code == 404:
response.failure('index is error')
# 设置场景
class WebsiteUser(HttpUser):
tasks = [TestCase] # 将测试用例添加到测试套件中
min_wait = 1
max_wait = 2
host = 'http://127.0.0.1:5000'
参数化-百度搜索例子
from locust import HttpUser, task, TaskSet
from random import randint
# 定义用户行为(测试用例)
class TestCase(TaskSet):
@task()
def index(self):
key =['locust','接口测试']
sj = randint(0,1) # 随机返回0,1
url_data = '/s?wd='+ key[sj] # 拼接路径
#catch_response = True :布尔类型,如果设置为 True, 允许该请求被标记为失败。
with self.client.get(url_data, catch_response=True) as response:
if response.status_code == 200: # 如果状态码是200,返回页面数据
print(response.content) # 返回页面数据
response.success()
else: # 失败时记录
response.failure('index is error')
# 设置场景
class WebsiteUser(HttpUser):
tasks = [TestCase] # 将测试用例添加到测试套件中
min_wait = 1
max_wait = 2
host = 'https://www.baidu.com' # 百度url



