- 无论是做接口自动化还是做压测,解决了登录就离成功进步了一大半,下面做个简单的登录案例,后续再说下数据依赖及参数化等问题
1. 登录
- 登录示例
from locust import HttpUser, task, between
USER_CREDENTIALS = [
("login1", "pwd1"),
("login2", "pwd2"),
("login3", "pwd3"),
] # 登录账户
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 "
} # 请求头
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") # 需要测试的地址
-
task
后面的意思可以理解为权重,在上面的示例中,view_tag
被选择为view_index
的几率是两倍
2.Task的另外使用方式
from locust import User, constant
def task_one(l):
print('https://yiluotalk.com/')
class MyUser(User):
tasks = [task_one]
wait_time = constant(1)
if __name__ == "__main__":
import os
os.system("locust -f demo.py ")
- 执行脚本
https://yiluotalk.com/
https://yiluotalk.com/
https://yiluotalk.com/
https://yiluotalk.com/
https://yiluotalk.com/
https://yiluotalk.com/
https://yiluotalk.com/
https://yiluotalk.com/
- 如果是多个任务的话
task = [my_task, my_task, my_task, another_task]
3. 小结
如果很熟悉request库
的话,基本没有上手的难度
https://yiluotalk.com/2019/12/19/Python%20requests%E5%BA%93(%E4%B8%80)/
欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !
网友评论