1 from locust import HttpLocust, task, TaskSet
2 import os
3
4
5 '''
6 -f 指定性能测试脚本文件
7 --host 指定被测试应用的URL的地址
8 --port 端口设置,默认8089
9 --no-web 表示不使用Web界面运行测试
10 -c 设置虚拟用户数
11 -r 设置每秒启动虚拟用户数
12 -t 设置运行时间
13 '''
14
15
16 # ----------------使用locust进行性能测试----------------------
17
18
19 class UserBehavior(TaskSet): # 定义一个用户行为, 继承TaskSet类
20
21 @task # @task装饰该方法为一个事务
22 def test_czth(self): # 表示一个用户行为
23 print('--访问拼多多主页--')
24 url = '/'
25 with self.client.post(url, catch_response=True) as response: # client.get()用于指请求的路径“/”,首页指定根路径
26 print(response.status_code)
27 if response.status_code != 200:
28 response.failure('Failed!')
29 else:
30 response.success()
31
32 @task
33 def test_czth_login(self):
34 print('--访问拼多多商品展示页--')
35 payload = {'username': 'admin',
36 'password': '123456',
37 'validcode': '999999'}
38 url = '/home'
39
40 with self.client.post(url=url, data=payload) as response:
41 print(response.status_code)
42 print(response.text)
43 assert '欢迎您, 系统管理员' in response.text
44
45
46 class WebsiteUser(HttpLocust): # 用于设置性能测试, 继承Httplocust类
47 task_set = UserBehavior # 指向一个定义的用户行为类
48 min_wait = 1000 # 用户等待时间的下界(毫秒)
49 max_wait = 3000 # 用户等待时间的上界
50 host = '192.168.106.211:8100' # 指压测地址
51
52
53 if __name__ == '__main__':
54 # os.system('locust -f locust_xn.py --port=8999')
55 os.system('locust -f locust_xn.py --port=8999 --no-web -c 10000 -r 100 -t 1h')
56 # os.system('locust -f locust_xn.py --master-bind-port=8999 --expect-slaves=X --slave ')