已经对Loust有了基本的了解,下面就可以做接口的请求
一、 Post请求
用户登录
根据业务需求的需求,登录接口只执行一次,在on_start()函数下编写登录信息
class MyTasks(TaskSet):
url = '/login'
headers = {'Content-Type': 'application/json'}
def on_start(self):
self.data = {"username":"admin","password":"123456"}
respon = self.client.post(self.url, headers = self.headers, data=json.dumps(self.data), name='用户登录', verify=False, timeout=10)
resp_dict = respon.json()
# print(f'响应数据为:{resp_dict}')
if respon.status_code == 200:
# 接口成功
print(resp_dict['msg'])
else:
# 请求失败
respon.failure(resp_dict['msg'])
class User(HttpUser):
tasks = [MyTasks]
host = 'https://www.baidu.com'
wait_time = between(2,2) # 每2秒执行一次
二、 Get请求
发送手机验证码
from locust import HttpUser, TaskSet, task
'''
get请求接口
'''
class MyTasks(TaskSet):
url = '/xxx/xxx/sendAuthCode'
headers = {'Content-Type': 'application/json',
'Authorization': 'xxxxx'
}
def on_start(self):
print("用户初始化--登录")
@task
def get_login(self):
print('发送验证码...')
# 定义一个对象属性
self.query_data = {'mobile': 1579715000}
respon = self.client.get(self.url, params = self.query_data, headers = self.headers, name='发送验证码', verify=False, timeout=10)
resp_dict = respon.json()
print(f'响应数据为:{resp_dict}')