最近使用python locust对项目一个接口进行压测,由于被测接口使用的token进行用户凭证验证,大体实施思路是先请求登录接口获取响应头中的token,再将token拼接到被测接口的请求头中请求被测接口,实际运行时会有大概10%-20%的失败请求,初步验证是由于locuts模拟的token无效导致。
1.代码实现:
login方法和被测接口实现方法都属于继承了TaskSet的类下
- 1获取token方法
def login(self):
pw = '*****'
md = hashlib.md5()
md.update(pw.encode('utf-8'))
pwd5 = md.hexdigest()
url = "http://******:*****/login/login"
payload = json.dumps({
"code": "****",
"password": pwd5,
"username": "****"
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request('post',url, headers=headers, data=payload)
return response.headers['x-auth-token']
- 2.locust请求被测接口实现
token = self.login()
head={
'x-auth-token': token,
'Content-Type': 'application/json'
}
with self.client.post("/被测接口",headers= head,json=body,catch_response = True) as response:
code=response.json().get("code")
key=response.json().get("key")
request_header=response.request.headers
print("{0}--->:{1}".format(key,request_header),end="\n\n")
if code != 200 and key!= "SUCCESS":
response.failure("未成功请求响应码:%dkey值:%s"%(code,key))
由于被测接口对用户凭证验证成功或失败响应码都是200,所以通过if函数对响应体中的code值和key值进行判断,从而断言请求是否成功,响应中的code值不为200与key值不为SUCCESS直接将请求打为失败请求。print函数打印出响应体中的key值与请求头帮助验证。
2. 结果
设置20个虚拟用户每秒启动5个(其实不管怎么设置),运行都会有将近20%的请求是失败请求
将控制台中print函数中的打印信息中响应key值为"NOT_LOGIN"的请求头中的token取出使用postman验证,code值依然为401,说明断言没问题
对比:
与jmeter比较正则提取出来的token,每次请求用的都是同一个token,但不会出现失败请求。
结论:
初步验证认为locust会去模拟第一次拿到的token,但模拟的带token的请求通过后端验证率并不高,不知是locust内部对token处理机制的缺陷还是本人实现的错误。希望高人指教,谢谢!