- 场景链路压测的时候通常都是按照用户实际使用流程进行压测,同接口自动化一样,一定会涉及到数据依赖的问题
1.举例
-
Django
后台通常需要csrf
验证,而一般csrftoken
需要通过get接口获得
from locust import HttpUser, task, between
from lxml import etree
USER_CREDENTIALS = [
("login1", "pwd1"),
("login2", "pwd2"),
("login3", "pwd3"),
] # 登录账户
csrf_token = []
class LoginDemo(HttpUser):
wait_time = between(2, 5) # 模拟用户等待2到5s然后执行
@task(1)
def on_start(self): # 任务开始时准备
header = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/83.0.4103.61 Safari/537.36 "
} # 请求头
# 获取csrf
r_get = self.client.get("user/login/")
# 从返回的html页面中,解析出 csrfmiddlewaretoken
dom = etree.HTML(r_get.content.decode("utf-8"))
try:
csrf_token['csrfmiddlewaretoken'] = dom.xpath('//input[@name="csrfmiddlewaretoken"]')[0].get("value")
print(csrf_token)
except:
print('参数csrfmiddlewaretoken获取失败!')
if len(USER_CREDENTIALS) > 0:
user, pwd = USER_CREDENTIALS.pop() # 取出账户名密码
r_post = self.client.post("user/login/", {
"token": 'TOKEN', # TOKEN
"username": user, # 用户名
"password": pwd, # 密码
"next": ""
}, header=header
)
assert r_post.status_code == 200 # 断言请求返回200
print(r_post.status_code, r_post.text[:1000]) # 打印状态码及返回text
@task(2)
def view_index(self):
print('访问首页')
r = self.client.get("/index/")
print(r.status_code)
@task(6)
def view_tag(self):
print('访问标签页')
r = self.client.get("/tag/")
print(r.status_code)
if __name__ == "__main__":
import os
os.system("locust -f demo.py --host=URL") # 需要测试的地址
- 这里我们使用了
etree
来获取get
接口返回的数据
2.更新请求头
self.client.headers.update(header)
3. 数据依赖
- 转化接口返回数据,然后获得
import json
@task(2)
def view_index(self):
r = self.client.get("/index/")
response = json.loads(r.text)
demo = response['取值'] # 假如取demo
print("===>", response['取值'], type(response)) # 取值
self.client.get('index/url/{}/'.format(demo))
4. 小结
- 可以先看一下request库 ,涉及到数据依赖的问题更好学习
https://yiluotalk.com/2019/12/19/Python%20requests%E5%BA%93(%E4%B8%80)/
欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !
网友评论