一文让 locust 小白,变成性能测试老司机


 1 #  -*-coding:utf-8 -*-
 2 # Author : pcx
 3 # Data : 2021/11/27,13:57
 4 # 项目:ppp_test
 5 # 文件名 :Locust3
 6 from locust import HttpUser, SequentialTaskSet, task, between
 7 # 定义用户行为类
 8 class UserBehavior(SequentialTaskSet):
 9     # 脚本开始前执行
10     def on_start(self):
11         print('开始***')
12     # 脚本结束后执行
13     def on_stop(self):
14         print('结束***')
15     @task(1)  # 任务项2,这里面数字越大,执行权重比越高,不设置默认1
16     def login_(self):
17         url = 'https://www.fastmock.site/mock/a652a362e923265933dc67dbfd46c521/api_index/index/login'  # 接口请求的URL地址
18         # 定义请求头为类变量,这样其他任务也可以调用该变量
19         self.headers = {"Content-Type": "application/json"}
20         self.username = "admin"
21         self.pwd = '123456'
22         data = {"username": self.username, "password": self.pwd}
23         with self.client.post(url,
24                               json=data,
25                               headers=self.headers,
26                               catch_response=True) as rsp:
27             # self.token = rsp.json()['token']
28             if rsp.status_code == 200:
29                 print(rsp.text)
30             else:
31                 rsp.failure('admin登录 接口失败!')
32     @task(1)  # 任务项1
33     def select_(self):
34         url = '/test1'  # 接口请求的URL地址
35         # 引用上一个任务的 类变量值   实现参数关联
36         # headers = {"Token": self.token}
37         # 使用self.client发起请求,请求的方法 选择 get
38         with self.client.get(url, catch_response=True) as rsp:
39             if rsp.status_code == 200:
40                 print(rsp.text)
41             else:
42                 rsp.failure('getuser_ 接口失败!')
43 class WebsiteUser(HttpUser):
44     tasks = [UserBehavior]
45     wait_time = between(0.5, 1)  # 执行事务的暂停时间下限和上限
46 
47 if __name__ == '__main__':
48     import os
49     os.system("locust -f locust3.py --host=https://www.fastmock.site/mock/a652a362e923265933dc67dbfd46c521/api_index")
50     # -f指定文件
51     # --host指定被测的url