locust的http请求断言实在没有太多可说的。http的请求加上catch_response=True参数,然后用response.success()和response.failure(“Got wrong response”)分别去标注成功还是失败就好了。运行结束在locust的控制台上就可以看到成功和败的统计。注意看图里的总数和失败数那两列。
设计一个例子,分别上送不同的报文,其中age节点送的值会不同。分别送5和6。返回分别为"测试请求的类型为post"和"未匹配到对应请求"。
这个实现起来很简单,下载一个moco工具,moco-runner-1.3.0-standalone.jar,然后添加一个dftest.json文件,文件代码如下:
[
{
“description”: “未匹配到对应请求默认配置”,
“response”: {
“text”: “未匹配到对应请求”
}
},
{
“description”: “示例1:method请求类型,用于定于请求类别,对应于jmeter的mocotest1,请求类型不同的不响应”,
“request”: {
“uri”:“/testmethod1234”,
“method”:“post”,
“json”: {
“name”:“doubao”,
“age”:“5”
}
},
“response”: {
“text”:“测试请求的类型为post”
}
}
}
]
之后用命令Java -Dfile.encoding=UTF-8 -jar D:\tools\moco\moco-runner-1.3.0-standalone.jar http -p 9010 -c D:\tools\moco\testmoco\dftestcon.json调起,这样一个简单的server端就做好了。可以对locust发起的请求进行响应。
发起请求端的locust代码例子如下所示:
很简单,TestUser1的user1_task1里面设定一个随机函数,随机把age分别送5(预期成功)和6(预期失败),然后进行对应的设置。
import datetime
import sre_constants
TestUser2=0
class TestUser1(HttpUser):
fixed_count = 30
wait_time = constant(5)
@task
def user1_task1(self):
#设定一个随机函数,让测试结果随机成功或者失败。
random_int=random.choice([0,1])
if random_int==0:
data123 = {"name" :"doubao","age":"5"}
else:
data123 = {"name": "doubao", "age": "6"}
datastr=json.dumps(data123)
log.info(datastr)
#需要加一个content-type?
with self.client.post('http://127.0.0.1:9010/testmethod1234',data=datastr,catch_response=True) as response:
if "post" in response.text:
response.success()
else:
response.failure("Got wrong response")
log.info("the user1 task1 complete!!!")
log.info(datetime.datetime.now())
log.info(response.text)
log.info(str(response.status_code))
@task
def user1_task2(self):
log.info("the user1 task2 complete!!!")
log.info(datetime.datetime.now())
class TestUser2(User):
fixed_count = 50
wait_time = constant(10)
@task
def user2_task1(self):
log.info("the user2 task1 complete!!!")
log.info(datetime.datetime.now())
@task
def user2_task2(self):
log.info("the user2 task2 complete!!!")
log.info(datetime.datetime.now())
locust -f D:\Users\dai__\PycharmProjects\pythonProject\dftesttools\dftestlocust2.py --logfile D:\Users\dai__\PycharmProjects\pythonProject\dftesttools\dftestlocust2.log --web-host 127.0.0.1 --web-port 8809命令运行起来以后。你可以去观察日志(比如拿ue去搜查看关键字的总数)中的成功数("测试请求的类型为post"的数量)和失败数("未匹配到对应请求"的数量)和locust控制台中的成功数和失败数是对应的。