以下是一个 Python 程序示例,用于对 API 接口进行 POST 请求(JSON 格式)的压力测试,逐渐递增并发请求数量并记录相关的性能指标。这个例子使用了 threading
模块来实现并发请求,并且记录了每次测试的总耗时、每次请求耗时、每秒承载的请求数以及错误数量。
安装必备库
确保您已安装 requests
库,如果没有,可以通过以下命令进行安装:
pip install requests
示例代码
下面是用于压力测试的示例代码:
import requests
import threading
import time
import collections
import json
# 定义请求的 URL 和请求体
url = 'http://your_api_endpoint_here' # 将这里替换为你的 API 地址
payload = {
'key1': 'value1',
'key2': 'value2'
# 根据你的 API 需求添加更多字段
}
# 用于保存测试结果
results = collections.defaultdict(list)
def send_request(request_number):
error_count = 0
request_times = []
# 记录开始时间
start_time = time.time()
try:
response = requests.post(url, json=payload)
response.raise_for_status() # 确保响应状态为 200
except requests.RequestException:
error_count += 1
request_times.append(time.time() - start_time)
return request_times, error_count
def pressure_test(max_concurrent, increment):
for concurrency in range(increment, max_concurrent + 1, increment):
print(f'Starting test with {concurrency} concurrent requests...')
# 创建存储线程和结果的列表
threads = []
total_request_times = []
total_errors = 0
# 启动线程
for _ in range(concurrency):
thread = threading.Thread(target=lambda lst: lst.append(send_request(1)), args=(total_request_times,))
threads.append(thread)
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
# 汇总数据
for times, errors in total_request_times:
total_errors += errors
total_time = sum(times for times, _ in total_request_times)
rps = concurrency / total_time if total_time > 0 else 0 # 每秒请求数
average_request_time = total_time / concurrency if concurrency > 0 else 0 # 平均请求时间
print(f'Concurrent Requests: {concurrency}')
print(f'Total Time: {total_time:.2f}s')
print(f'Average Request Time: {average_request_time:.2f}s')
print(f'Requests Per Second: {rps:.2f}')
print(f'Error Count: {total_errors}')
print('-' * 40)
if __name__ == '__main__':
max_concurrent_requests = 100 # 最大并发请求数
increment = 10 # 并发增加量
pressure_test(max_concurrent_requests, increment)
代码说明
-
URL 和请求体:
- 将
url
替换为您要测试的 API 地址,并根据需要调整payload
中的内容。
- 将
-
send_request(request_number)
:- 该函数负责发送单个 POST 请求并记录请求耗时和错误数量。
-
pressure_test(max_concurrent, increment)
:- 该函数控制并发请求的数量,并输出每次测试的结果。
- 每次测试开始前创建指定数量的线程,发送请求,并在所有线程完成后汇总结果。
-
结果统计:
- 计算每次测试的总耗时、平均请求耗时、每秒处理的请求数量及错误数量,并打印输出。
注意事项
- 在进行压力测试前,请确认目标 API 能处理高并发请求,以免给其带来不必要的负担。
- 根据您的需求调整
max_concurrent_requests
和increment
的值。 - 针对具体的 API,您可能需要更复杂的请求体、头部设置等,请根据需求进行修改。