Python通过locust实现接口压测

1、下载locust包

1 pip install locust

2、脚本内容如下

文件名称为test.py

timeout来调整压测时长,单位是秒
 1 from locust import HttpUser, task
 2 from datetime import datetime
 3 import requests
 4 import time
 5 import json
 6 import os
 7 
 8 host = 'http://xite.apgw.icsc.net:8007'
 9 head_host = 'daa-tsdb-expt.xcloud.biu-int.com'
10 
11 class MyUser(HttpUser):
12     """ test class """
13     min_wait = 0
14     max_wait = 10
15     def __init__(self, *args, **kwargs):
16         """ init """
17         if self.host is None:
18             self.host = host
19         super().__init__(*args, **kwargs)
20   
21 
22     def runTest(self, url, method='GET', data={}):
23         """ run a http test """
24         header = {
25             'Accept': 'application/json'
26         }
27         with self.client.request(method, url, headers=header, data=json.dumps(data),
28             catch_response=True, timeout=300, verify=False) as response:
29             ##print(response.status_code)
30             ##print(response.text)
31             try:
32                 if response.status_code == 200:
33                     response.success()
34                 else:
35                     response.failure(f"Received a non-success status code: {response.status_code},{response.text}")
36             except Exception as e:
37                 response.failure(f"Failed to parse response data: {str(e)}")
38 
39     @task(1)
40     def task1(self):
41         """ get请求的url"""
42         url = 'https://111.11.11.11:1001/vp/brview'
43         #print(url)
44         self.runTest(url)
45 
46     @task(1)
47     def task2(self):
48         """ get请求的url """
49         url = 'https://111.11.11.11:1001/vp/bgerview'
50         #print(url)
51         self.runTest(url)
52 
53     @task(1)
54     def task3(self):
55         """ post请求的url """
56         url = 'https://111.11.11.11:1001/vp/rend/onDay'
57         #print(url)
58         data = {
59             "startTime":"2024-12-13 00:00:00",
60             "endTime":"2024-12-13 18:00:00",
61             "timeUnit":"HOURS",
62             "spaceType":"AREA"
63         }
64         self.runTest(url, method='POST', data=data)
65 
66     @task(1)
67     def task4(self):
68         """ post请求的url  """
69         url = 'https://111.11.11.11:1001/vp/king/road'
70         #print(url)
71         data = {"pageNo":1,"pageSize":10}
72         self.runTest(url, method='POST', data=data)

3、控制台运行,生成的链接着在浏览器中访问并运行即可

 1 locust -f test.py 

 

posted @ 2024-12-31 10:46  一直在寻找的路上  阅读(241)  评论(0)    收藏  举报