完善: CSRF安全修复 + 后台任务管理 + 压测全模块覆盖 + 文档
This commit is contained in:
+907
@@ -0,0 +1,907 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
LiteAdmin 压力测试工具 v5.0
|
||||
- 利用 Keep-Alive 连接复用,大幅降低 TCP 开销
|
||||
- 先清除所有数据
|
||||
- 通过批量导入接口注册 2000 个测试账号(一次请求)
|
||||
- 使用 2000 个账号进行压测
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
import urllib.parse
|
||||
import random
|
||||
import argparse
|
||||
import io
|
||||
import csv
|
||||
|
||||
# ============================================================
|
||||
# Keep-Alive HTTP 客户端(连接复用)
|
||||
# ============================================================
|
||||
|
||||
class KeepAliveHttpClient:
|
||||
"""支持 Keep-Alive 的 HTTP 客户端,复用 TCP 连接"""
|
||||
def __init__(self, base_url, timeout=10):
|
||||
self.base_url = base_url.rstrip('/')
|
||||
self.timeout = timeout
|
||||
parsed = urllib.parse.urlparse(base_url)
|
||||
self.host = parsed.hostname
|
||||
self.port = parsed.port or (443 if parsed.scheme == 'https' else 80)
|
||||
self.use_ssl = parsed.scheme == 'https'
|
||||
self._session_cookie = ''
|
||||
self._csrf_token = ''
|
||||
self._sock = None
|
||||
self._buffer = b''
|
||||
|
||||
def set_cookie(self, cookie):
|
||||
self._session_cookie = cookie
|
||||
|
||||
def _get_connection(self):
|
||||
"""获取或创建 TCP 连接(Keep-Alive 复用)"""
|
||||
if self._sock is not None:
|
||||
try:
|
||||
self._sock.settimeout(0.1)
|
||||
self._sock.sendall(b'')
|
||||
self._sock.settimeout(self.timeout)
|
||||
return self._sock
|
||||
except Exception:
|
||||
try:
|
||||
self._sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._sock = None
|
||||
self._buffer = b''
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(self.timeout)
|
||||
try:
|
||||
sock.connect((self.host, self.port))
|
||||
self._sock = sock
|
||||
self._buffer = b''
|
||||
return sock
|
||||
except Exception:
|
||||
try:
|
||||
sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
def close(self):
|
||||
if self._sock:
|
||||
try:
|
||||
self._sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._sock = None
|
||||
self._buffer = b''
|
||||
|
||||
def request(self, method, path, body=None, extra_headers=None):
|
||||
headers = {'Host': self.host, 'Connection': 'keep-alive'}
|
||||
if self._session_cookie:
|
||||
headers['Cookie'] = self._session_cookie
|
||||
if body:
|
||||
if isinstance(body, dict):
|
||||
headers['Content-Type'] = 'application/x-www-form-urlencoded'
|
||||
body_bytes = urllib.parse.urlencode(body).encode()
|
||||
elif isinstance(body, bytes):
|
||||
body_bytes = body
|
||||
else:
|
||||
body_bytes = str(body).encode()
|
||||
headers['Content-Length'] = str(len(body_bytes))
|
||||
else:
|
||||
body_bytes = b''
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
|
||||
raw = '{} {} HTTP/1.1\r\n'.format(method, path)
|
||||
for k, v in sorted(headers.items()):
|
||||
raw += '{}: {}\r\n'.format(k, v)
|
||||
raw += '\r\n'
|
||||
raw = raw.encode() + body_bytes
|
||||
|
||||
try:
|
||||
sock = self._get_connection()
|
||||
sock.sendall(raw)
|
||||
return self._read_response()
|
||||
except socket.timeout:
|
||||
self.close()
|
||||
return 408, b'', 0
|
||||
except Exception as e:
|
||||
self.close()
|
||||
return 0, str(e).encode(), 0
|
||||
|
||||
def _read_response(self):
|
||||
sock = self._sock
|
||||
buf = self._buffer
|
||||
while b'\r\n\r\n' not in buf:
|
||||
try:
|
||||
chunk = sock.recv(65536)
|
||||
except socket.timeout:
|
||||
self.close()
|
||||
return 408, buf, 0
|
||||
except Exception:
|
||||
self.close()
|
||||
return 0, buf, 0
|
||||
if not chunk:
|
||||
self.close()
|
||||
return 0, buf, 0
|
||||
buf += chunk
|
||||
header_end = buf.find(b'\r\n\r\n')
|
||||
status_line = buf[:buf.find(b'\r\n')].decode('utf-8', errors='replace')
|
||||
parts = status_line.split(' ')
|
||||
status_code = int(parts[1]) if len(parts) >= 2 else 0
|
||||
header_section = buf[:header_end].decode('utf-8', errors='replace')
|
||||
body_start = header_end + 4
|
||||
for line in header_section.split('\r\n'):
|
||||
if line.lower().startswith('set-cookie:'):
|
||||
cookie_val = line[11:].strip().split(';')[0]
|
||||
if 'session_id=' in cookie_val:
|
||||
self._session_cookie = cookie_val
|
||||
content_length = 0
|
||||
for line in header_section.split('\r\n')[1:]:
|
||||
if ':' in line:
|
||||
k, v = line.split(':', 1)
|
||||
if k.strip().lower() == 'content-length':
|
||||
content_length = int(v.strip())
|
||||
break
|
||||
if content_length > 0:
|
||||
needed = body_start + content_length - len(buf)
|
||||
while needed > 0:
|
||||
try:
|
||||
chunk = sock.recv(min(65536, needed + 1024))
|
||||
except socket.timeout:
|
||||
self.close()
|
||||
return 408, buf[body_start:], 0
|
||||
except Exception:
|
||||
self.close()
|
||||
return 0, buf[body_start:], 0
|
||||
if not chunk:
|
||||
self.close()
|
||||
break
|
||||
buf += chunk
|
||||
needed = body_start + content_length - len(buf)
|
||||
body_data = buf[body_start:body_start + content_length] if content_length > 0 else b''
|
||||
self._buffer = buf[body_start + content_length:]
|
||||
return status_code, body_data, len(buf)
|
||||
|
||||
def get(self, path):
|
||||
t0 = time.time()
|
||||
code, body, size = self.request('GET', path)
|
||||
return code, body, time.time() - t0
|
||||
|
||||
def post(self, path, data=None):
|
||||
t0 = time.time()
|
||||
code, body, size = self.request('POST', path, body=data or {})
|
||||
return code, body, time.time() - t0
|
||||
|
||||
def post_multipart(self, path, fields, files):
|
||||
"""发送 multipart/form-data POST 请求"""
|
||||
boundary = '----WebKitFormBoundary' + ''.join(random.choices('0123456789abcdef', k=16))
|
||||
body_bytes = b''
|
||||
|
||||
for key, value in fields.items():
|
||||
body_bytes += b'--' + boundary.encode() + b'\r\n'
|
||||
body_bytes += b'Content-Disposition: form-data; name="' + key.encode() + b'"\r\n\r\n'
|
||||
body_bytes += value.encode() + b'\r\n'
|
||||
|
||||
for field_name, (filename, content, content_type) in files.items():
|
||||
body_bytes += b'--' + boundary.encode() + b'\r\n'
|
||||
body_bytes += b'Content-Disposition: form-data; name="' + field_name.encode() + b'"; filename="' + filename.encode() + b'"\r\n'
|
||||
body_bytes += b'Content-Type: ' + content_type.encode() + b'\r\n\r\n'
|
||||
body_bytes += content + b'\r\n'
|
||||
|
||||
body_bytes += b'--' + boundary.encode() + b'--\r\n'
|
||||
|
||||
headers = {'Content-Type': 'multipart/form-data; boundary=' + boundary}
|
||||
t0 = time.time()
|
||||
code, body, size = self.request('POST', path, body=body_bytes, extra_headers=headers)
|
||||
return code, body, time.time() - t0
|
||||
|
||||
def fetch_csrf(self):
|
||||
code, body, _ = self.get('/api/csrf-token/')
|
||||
if code == 200:
|
||||
try:
|
||||
d = json.loads(body.decode())
|
||||
self._csrf_token = d.get('csrf_token', '')
|
||||
return self._csrf_token
|
||||
except Exception:
|
||||
pass
|
||||
return ''
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 数据准备:清除 + 批量导入 2000 用户
|
||||
# ============================================================
|
||||
|
||||
def prepare_data(base_url, admin_user='admin', admin_pass='admin123'):
|
||||
"""清除数据并通过批量导入注册 2000 个测试用户"""
|
||||
admin_client = KeepAliveHttpClient(base_url, timeout=15)
|
||||
|
||||
# 1. 管理员登录
|
||||
print(' [准备] 管理员登录...')
|
||||
code, body, _ = admin_client.post('/admin/login/', {
|
||||
'username': admin_user,
|
||||
'password': admin_pass,
|
||||
})
|
||||
if code not in (200, 302):
|
||||
print(' ❌ 管理员登录失败: HTTP {}'.format(code))
|
||||
return False
|
||||
print(' ✅ 管理员登录成功')
|
||||
|
||||
if not admin_client._session_cookie:
|
||||
print(' ❌ 未能获取 session cookie')
|
||||
return False
|
||||
|
||||
# 2. 清除所有数据(复用同一连接)
|
||||
print(' [准备] 清除所有数据...')
|
||||
code, body, _ = admin_client.post('/admin/clear-data/')
|
||||
if code == 200:
|
||||
try:
|
||||
result = json.loads(body.decode())
|
||||
print(' ✅ {}'.format(result.get('message', '清除完成')))
|
||||
except Exception:
|
||||
print(' ✅ 数据已清除')
|
||||
else:
|
||||
print(' ⚠ 清除数据返回 HTTP {}'.format(code))
|
||||
|
||||
# 3. 生成 CSV 并批量导入
|
||||
print(' [准备] 批量导入 2000 个测试用户...')
|
||||
departments = ['生产部', '技术部', '质量部', '综合部', '财务部']
|
||||
prefixes = ['sc', 'js', 'zl', 'zh', 'cw']
|
||||
|
||||
output = io.StringIO()
|
||||
writer = csv.writer(output)
|
||||
writer.writerow(['账号', '密码', '真实姓名', '班组部门', '用户等级'])
|
||||
|
||||
for dept_idx in range(len(departments)):
|
||||
prefix = prefixes[dept_idx]
|
||||
dept = departments[dept_idx]
|
||||
for num in range(1, 401):
|
||||
username = '{}{}'.format(prefix, num)
|
||||
display_name = '{}{}号员工'.format(dept, num)
|
||||
level = 'lv{}'.format(random.randint(1, 5))
|
||||
writer.writerow([username, '123456', display_name, dept, level])
|
||||
|
||||
csv_content = output.getvalue().encode('utf-8-sig')
|
||||
|
||||
code, body, elapsed = admin_client.post_multipart(
|
||||
'/admin/user/import/',
|
||||
fields={},
|
||||
files={'file': ('test_users.csv', csv_content, 'text/csv')}
|
||||
)
|
||||
|
||||
if code == 200:
|
||||
body_text = body.decode('utf-8', errors='replace')
|
||||
if '导入完成' in body_text or '新增' in body_text:
|
||||
print(' ✅ 批量导入成功 (HTTP {})'.format(code))
|
||||
import re
|
||||
m = re.search(r'新增 (\d+) 个', body_text)
|
||||
if m:
|
||||
print(' 新增 {} 个用户'.format(m.group(1)))
|
||||
else:
|
||||
print(' ⚠ 导入返回: {}'.format(body_text[:200]))
|
||||
else:
|
||||
print(' ⚠ 批量导入返回 HTTP {}'.format(code))
|
||||
print(' body: {}'.format(body.decode()[:200]))
|
||||
|
||||
# 导入用户后,创建公告/知识库/任务种子数据
|
||||
seed_business_data(base_url)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def seed_business_data(base_url):
|
||||
"""在导入用户后,创建公告/知识库/任务种子数据,让三类模块有真实数据可读写"""
|
||||
print(' [准备] 创建 公告/知识库/任务 种子数据...')
|
||||
try:
|
||||
# admin 登录,建公告 + 知识库
|
||||
admin_client = KeepAliveHttpClient(base_url, timeout=15)
|
||||
code, body, _ = admin_client.post('/admin/login/', {
|
||||
'username': 'admin', 'password': 'admin123'})
|
||||
if code not in (200, 302):
|
||||
print(' ⚠ admin 登录失败: HTTP {}'.format(code))
|
||||
return False
|
||||
admin_client.fetch_csrf()
|
||||
for i in range(1, 6):
|
||||
admin_client.post('/announcement/new/', {
|
||||
'csrf_token': admin_client._csrf_token,
|
||||
'title': '压测公告种子 {}'.format(i),
|
||||
'content': ('这是压测公告种子数据 {},用于公告列表/详情的读操作。'.format(i)) * 30,
|
||||
})
|
||||
for i in range(1, 9):
|
||||
admin_client.post('/knowledge/new/', {
|
||||
'csrf_token': admin_client._csrf_token,
|
||||
'title': '压测知识库种子 {}'.format(i),
|
||||
'content': ('这是压测知识库种子数据 {},用于知识库列表/详情的读操作。'.format(i)) * 40,
|
||||
'category': '综合',
|
||||
})
|
||||
admin_client.close()
|
||||
|
||||
# 每部门各用 1 个用户建 2 个任务,保证各部门任务读/提交都命中
|
||||
dept_map = {'sc': '生产部', 'js': '技术部', 'zl': '质量部', 'zh': '综合部', 'cw': '财务部'}
|
||||
for prefix, dept in dept_map.items():
|
||||
c = KeepAliveHttpClient(base_url, timeout=15)
|
||||
c.post('/login/', {'username': prefix + '1', 'password': '123456'})
|
||||
c.fetch_csrf()
|
||||
for i in range(1, 3):
|
||||
c.post('/tasks/create/', {
|
||||
'csrf_token': c._csrf_token,
|
||||
'name': '{}{}压测任务{}'.format(prefix, i, i),
|
||||
'description': '{}压测任务{}描述,用于信息收集读/提交。'.format(dept, i),
|
||||
})
|
||||
c.close()
|
||||
print(' ✅ 种子数据创建完成(公告5 知识库8 任务10)')
|
||||
return True
|
||||
except Exception as e:
|
||||
print(' ⚠ 种子数据创建异常: {}'.format(e))
|
||||
return False
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 用户行为模拟
|
||||
# ============================================================
|
||||
|
||||
TEST_USERS = ['sc{}'.format(i) for i in range(1, 401)] + \
|
||||
['js{}'.format(i) for i in range(1, 401)] + \
|
||||
['zl{}'.format(i) for i in range(1, 401)] + \
|
||||
['zh{}'.format(i) for i in range(1, 401)] + \
|
||||
['cw{}'.format(i) for i in range(1, 401)]
|
||||
|
||||
|
||||
class VirtualUser:
|
||||
def __init__(self, base_url, user_id, read_only=False):
|
||||
self.client = KeepAliveHttpClient(base_url, timeout=15)
|
||||
self.user_id = user_id
|
||||
self.logged_in = False
|
||||
self.username = ''
|
||||
self.read_only = read_only
|
||||
self._topic_ids = []
|
||||
self._my_tasks = [] # [(task_id, creator_username), ...]
|
||||
self._ann_ids = [] # 公告详情缓存
|
||||
self._kn_ids = [] # 知识库详情缓存
|
||||
|
||||
def _ensure_login(self, username=None, password='123456'):
|
||||
# 指定用户名登录(如 admin 用 admin123),或复用当前登录
|
||||
if username is not None and self.logged_in and self.username == username:
|
||||
return True
|
||||
if username is not None:
|
||||
self.username = username
|
||||
self.logged_in = False
|
||||
if not self.logged_in:
|
||||
if username is None:
|
||||
self.username = random.choice(TEST_USERS)
|
||||
for attempt in range(3):
|
||||
try:
|
||||
code, body, _ = self.client.post('/login/', {
|
||||
'username': self.username,
|
||||
'password': password,
|
||||
})
|
||||
if code == 302:
|
||||
self.logged_in = True
|
||||
self.client.fetch_csrf()
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
# 重建全新客户端(新 socket + 清空会话),规避长连接
|
||||
# keep-alive 下残留响应字节把登录 302 误判成旧 200 的客户端解析问题
|
||||
self.client.close()
|
||||
self.client = KeepAliveHttpClient(self.client.base_url, timeout=15)
|
||||
time.sleep(0.05)
|
||||
return False
|
||||
return self.logged_in
|
||||
|
||||
def _cached_id(self, list_url, attr):
|
||||
"""从列表接口取一个有效 id(详情页读用),避免 404"""
|
||||
ids = getattr(self, attr, None)
|
||||
if not ids:
|
||||
code, body, _ = self.client.get(list_url)
|
||||
if code == 200:
|
||||
try:
|
||||
d = json.loads(body.decode())
|
||||
ids = [it['id'] for it in d.get('items', [])][:8]
|
||||
setattr(self, attr, ids)
|
||||
except Exception:
|
||||
ids = []
|
||||
return random.choice(ids) if ids else None
|
||||
|
||||
def _ensure_csrf(self):
|
||||
if not self.client._csrf_token:
|
||||
self.client.fetch_csrf()
|
||||
return bool(self.client._csrf_token)
|
||||
|
||||
def run_action(self):
|
||||
r = random.random()
|
||||
|
||||
# 读操作 ~76%(覆盖 公告/知识库/论坛/任务 及详情页)
|
||||
if r < 0.18:
|
||||
return self.client.get('/')
|
||||
if r < 0.32:
|
||||
return self.client.get('/api/home/')
|
||||
if r < 0.42:
|
||||
return self.client.get('/api/announcements/?page=1')
|
||||
if r < 0.50:
|
||||
return self._detail_ann()
|
||||
if r < 0.58:
|
||||
return self.client.get('/api/knowledge/?page=1')
|
||||
if r < 0.64:
|
||||
return self._detail_knowledge()
|
||||
if r < 0.70:
|
||||
return self.client.get('/api/forum/?page=1')
|
||||
if r < 0.74:
|
||||
return self.client.get('/api/search/?q=' + random.choice(['技术', '公告', '学习', '规范', '安全']))
|
||||
if r < 0.76:
|
||||
return self._task_list()
|
||||
|
||||
# 写操作 ~24%,需登录(覆盖 任务/公告/知识库/论坛)
|
||||
if not self._ensure_login():
|
||||
return 401, b'not logged in', 0
|
||||
if self.read_only:
|
||||
return self.client.get('/')
|
||||
|
||||
r2 = random.random()
|
||||
if r2 < 0.15:
|
||||
return self._create_task()
|
||||
if r2 < 0.28:
|
||||
return self._submit_task()
|
||||
if r2 < 0.40:
|
||||
return self._create_announcement()
|
||||
if r2 < 0.52:
|
||||
return self._create_knowledge()
|
||||
if r2 < 0.68:
|
||||
return self._create_topic()
|
||||
if r2 < 0.80:
|
||||
return self._create_reply()
|
||||
if r2 < 0.88:
|
||||
return self._edit_topic()
|
||||
if r2 < 0.94:
|
||||
return self._delete_topic()
|
||||
if r2 < 0.97:
|
||||
return self._get_csrf()
|
||||
return self._my_topics()
|
||||
|
||||
def _task_list(self):
|
||||
if not self._ensure_login():
|
||||
return 401, b'not logged in', 0
|
||||
return self.client.get('/api/tasks/?page=1')
|
||||
|
||||
def _detail_ann(self):
|
||||
aid = self._cached_id('/api/announcements/?page=1', '_ann_ids')
|
||||
if aid is None:
|
||||
return self.client.get('/api/announcements/?page=1')
|
||||
return self.client.get('/api/announcements/{}/'.format(aid))
|
||||
|
||||
def _detail_knowledge(self):
|
||||
kid = self._cached_id('/api/knowledge/?page=1', '_kn_ids')
|
||||
if kid is None:
|
||||
return self.client.get('/api/knowledge/?page=1')
|
||||
return self.client.get('/api/knowledge/{}/'.format(kid))
|
||||
|
||||
def _create_announcement(self):
|
||||
# 公告发布需 lv3 或 admin
|
||||
if not self._ensure_login('admin', 'admin123'):
|
||||
return 401, b'not logged in', 0
|
||||
# 强制重取 csrf(绑定 admin 会话,避免用旧用户 token 触发 403)
|
||||
self.client._csrf_token = ''
|
||||
self._ensure_csrf()
|
||||
code, body, elapsed = self.client.post('/announcement/new/', {
|
||||
'csrf_token': self.client._csrf_token,
|
||||
'title': '压测公告 {}'.format(random.randint(10000, 99999)),
|
||||
'content': '压测公告内容 {},用于覆盖公告写路径。'.format(random.randint(10000, 99999)),
|
||||
})
|
||||
return code, body, elapsed
|
||||
|
||||
def _create_knowledge(self):
|
||||
# 知识库发布需 lv3 或 admin
|
||||
if not self._ensure_login('admin', 'admin123'):
|
||||
return 401, b'not logged in', 0
|
||||
# 强制重取 csrf(绑定 admin 会话,避免用旧用户 token 触发 403)
|
||||
self.client._csrf_token = ''
|
||||
self._ensure_csrf()
|
||||
code, body, elapsed = self.client.post('/knowledge/new/', {
|
||||
'csrf_token': self.client._csrf_token,
|
||||
'title': '压测知识库 {}'.format(random.randint(10000, 99999)),
|
||||
'content': '压测知识库内容 {},用于覆盖知识库写路径。'.format(random.randint(10000, 99999)),
|
||||
'category': '综合',
|
||||
})
|
||||
return code, body, elapsed
|
||||
|
||||
def _create_task(self):
|
||||
if not self._ensure_login():
|
||||
return 401, b'not logged in', 0
|
||||
self._ensure_csrf()
|
||||
creator = self.username
|
||||
code, body, elapsed = self.client.post('/tasks/create/', {
|
||||
'csrf_token': self.client._csrf_token,
|
||||
'name': '压测任务 {}'.format(random.randint(10000, 99999)),
|
||||
'description': '压测任务描述 {}'.format(random.randint(10000, 99999)),
|
||||
})
|
||||
if code == 200:
|
||||
try:
|
||||
d = json.loads(body.decode())
|
||||
if d.get('success') and d.get('task') and d['task'].get('id'):
|
||||
self._my_tasks.append((d['task']['id'], creator))
|
||||
except Exception:
|
||||
pass
|
||||
return code, body, elapsed
|
||||
|
||||
def _submit_task(self):
|
||||
# 任务提交需同部门,故用创建者本人账号提交
|
||||
if not self._my_tasks:
|
||||
return self._create_task()
|
||||
task_id, creator = random.choice(self._my_tasks)
|
||||
if not self._ensure_login(creator):
|
||||
return 401, b'not logged in', 0
|
||||
self._ensure_csrf()
|
||||
code, body, elapsed = self.client.post('/tasks/{}/submit/'.format(task_id), {
|
||||
'csrf_token': self.client._csrf_token,
|
||||
'content': '压测任务提交 {}'.format(random.randint(10000, 99999)),
|
||||
})
|
||||
return code, body, elapsed
|
||||
|
||||
def _get_csrf(self):
|
||||
code, body, elapsed = self.client.get('/api/csrf-token/')
|
||||
if code == 200:
|
||||
try:
|
||||
d = json.loads(body.decode())
|
||||
self.client._csrf_token = d.get('csrf_token', '')
|
||||
except Exception:
|
||||
pass
|
||||
return code, body, elapsed
|
||||
|
||||
def _create_topic(self):
|
||||
self._ensure_csrf()
|
||||
csrf = self.client._csrf_token
|
||||
code, body, elapsed = self.client.post('/forum/new/', {
|
||||
'csrf_token': csrf,
|
||||
'title': '压测话题 {}'.format(random.randint(10000, 99999)),
|
||||
'content': '压力测试自动生成的内容。\n\n- 项目一\n- 项目二',
|
||||
'category': random.choice(['综合', '技术', '生活', '学习']),
|
||||
})
|
||||
if code == 200:
|
||||
try:
|
||||
d = json.loads(body.decode())
|
||||
if d.get('success') and d.get('id'):
|
||||
self._topic_ids.append(d['id'])
|
||||
except Exception:
|
||||
pass
|
||||
return code, body, elapsed
|
||||
|
||||
def _create_reply(self):
|
||||
if not self._topic_ids:
|
||||
return self._create_topic()
|
||||
self._ensure_csrf()
|
||||
topic_id = random.choice(self._topic_ids)
|
||||
csrf = self.client._csrf_token
|
||||
code, body, elapsed = self.client.post('/forum/{}/reply/'.format(topic_id), {
|
||||
'csrf_token': csrf,
|
||||
'content': '压测回复 {}'.format(random.randint(10000, 99999)),
|
||||
})
|
||||
return code, body, elapsed
|
||||
|
||||
def _edit_topic(self):
|
||||
if not self._topic_ids:
|
||||
return self._create_topic()
|
||||
self._ensure_csrf()
|
||||
topic_id = random.choice(self._topic_ids)
|
||||
csrf = self.client._csrf_token
|
||||
code, body, elapsed = self.client.post('/my/topics/{}/edit/'.format(topic_id), {
|
||||
'csrf_token': csrf,
|
||||
'title': '压测话题(已编辑) {}'.format(random.randint(10000, 99999)),
|
||||
'content': '编辑后内容 {}'.format(random.randint(10000, 99999)),
|
||||
'category': '综合',
|
||||
})
|
||||
return code, body, elapsed
|
||||
|
||||
def _delete_topic(self):
|
||||
if not self._topic_ids:
|
||||
return self._create_topic()
|
||||
self._ensure_csrf()
|
||||
topic_id = self._topic_ids.pop()
|
||||
csrf = self.client._csrf_token
|
||||
code, body, elapsed = self.client.post('/my/topics/{}/delete/'.format(topic_id), {
|
||||
'csrf_token': csrf,
|
||||
})
|
||||
return code, body, elapsed
|
||||
|
||||
def _my_topics(self):
|
||||
return self.client.get('/api/my/topics/')
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 测试引擎
|
||||
# ============================================================
|
||||
|
||||
class LoadTester:
|
||||
def __init__(self, base_url, concurrency=100, duration=30, read_only=False):
|
||||
self.base_url = base_url
|
||||
self.concurrency = concurrency
|
||||
self.duration = duration
|
||||
self.read_only = read_only
|
||||
self.results = []
|
||||
self.errors = 0
|
||||
self.total = 0
|
||||
self.lock = threading.Lock()
|
||||
self.running = True
|
||||
|
||||
def _worker(self, worker_id):
|
||||
user = VirtualUser(self.base_url, worker_id, self.read_only)
|
||||
while self.running:
|
||||
try:
|
||||
code, body, elapsed = user.run_action()
|
||||
with self.lock:
|
||||
self.total += 1
|
||||
if code >= 400 or code == 0:
|
||||
self.errors += 1
|
||||
if self.errors % 50 == 1 and self.errors <= 200:
|
||||
err_body = body.decode('utf-8', errors='replace')[:120] if isinstance(body, bytes) else str(body)[:120]
|
||||
print('\n [错误#{}] HTTP {} | {}'.format(self.errors, code, err_body))
|
||||
self.results.append((elapsed, code))
|
||||
if len(self.results) > 10000:
|
||||
self.results = self.results[-5000:]
|
||||
except Exception as e:
|
||||
with self.lock:
|
||||
self.total += 1
|
||||
self.errors += 1
|
||||
if self.errors % 50 == 1 and self.errors <= 200:
|
||||
print('\n [异常#{}] {}'.format(self.errors, str(e)[:120]))
|
||||
|
||||
def run(self):
|
||||
mode = '只读' if self.read_only else '完整 CRUD'
|
||||
print(' 启动 {} 个虚拟用户({}模式),测试 {} 秒...'.format(
|
||||
self.concurrency, mode, self.duration))
|
||||
print()
|
||||
|
||||
threads = []
|
||||
for i in range(self.concurrency):
|
||||
t = threading.Thread(target=self._worker, args=(i,), daemon=True)
|
||||
t.start()
|
||||
threads.append(t)
|
||||
|
||||
start = time.time()
|
||||
last_total = 0
|
||||
while time.time() - start < self.duration:
|
||||
time.sleep(1)
|
||||
elapsed = int(time.time() - start)
|
||||
with self.lock:
|
||||
current_total = self.total
|
||||
rps = current_total - last_total
|
||||
errs = self.errors
|
||||
last_total = current_total
|
||||
bar = '#' * min(rps // 5, 40)
|
||||
print(' [{:3d}s] {:>5} req/s | 总计: {:>6} | 错误: {:>4} | {}'.format(
|
||||
elapsed, rps, current_total, errs, bar))
|
||||
|
||||
self.running = False
|
||||
for t in threads:
|
||||
t.join(timeout=2)
|
||||
|
||||
total_time = time.time() - start
|
||||
return self._report(total_time)
|
||||
|
||||
def _report(self, total_time):
|
||||
with self.lock:
|
||||
total = self.total
|
||||
errors = self.errors
|
||||
times = [r[0] for r in self.results]
|
||||
|
||||
if not times:
|
||||
print('\n ❌ 无有效请求数据')
|
||||
return None
|
||||
|
||||
times.sort()
|
||||
avg = sum(times) / len(times)
|
||||
median = times[len(times) // 2]
|
||||
p95 = times[int(len(times) * 0.95)]
|
||||
p99 = times[int(len(times) * 0.99)]
|
||||
max_t = times[-1]
|
||||
rps = total / total_time
|
||||
success = total - errors
|
||||
success_rate = (success / total) * 100 if total > 0 else 0
|
||||
|
||||
print()
|
||||
print(' ╔══════════════════════════════════════╗')
|
||||
print(' ║ 压力测试结果报告 ║')
|
||||
print(' ╚══════════════════════════════════════╝')
|
||||
print()
|
||||
print(' 测试配置:')
|
||||
print(' 目标地址: {}'.format(self.base_url))
|
||||
print(' 并发用户: {}'.format(self.concurrency))
|
||||
print(' 测试时长: {:.0f} 秒'.format(total_time))
|
||||
print(' 测试模式: {}'.format('只读' if self.read_only else '完整 CRUD'))
|
||||
print()
|
||||
print(' 吞吐量:')
|
||||
print(' 总请求数: {}'.format(total))
|
||||
print(' 成功请求: {} ({:.1f}%)'.format(success, success_rate))
|
||||
print(' 失败请求: {}'.format(errors))
|
||||
print(' 吞吐量: {:.1f} req/s'.format(rps))
|
||||
print()
|
||||
print(' 响应时间 (秒):')
|
||||
print(' 平均: {:.3f}s'.format(avg))
|
||||
print(' 中位数: {:.3f}s'.format(median))
|
||||
print(' P95: {:.3f}s'.format(p95))
|
||||
print(' P99: {:.3f}s'.format(p99))
|
||||
print(' 最大: {:.3f}s'.format(max_t))
|
||||
print()
|
||||
|
||||
return {
|
||||
'total': total,
|
||||
'success': success,
|
||||
'errors': errors,
|
||||
'success_rate': success_rate,
|
||||
'rps': rps,
|
||||
'avg': avg,
|
||||
'median': median,
|
||||
'p95': p95,
|
||||
'p99': p99,
|
||||
'max': max_t,
|
||||
'concurrency': self.concurrency,
|
||||
}
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 自动寻找最大承载
|
||||
# ============================================================
|
||||
|
||||
def find_max_capacity(base_url, read_only=False):
|
||||
mode = '只读' if read_only else '完整 CRUD'
|
||||
print(' ╔══════════════════════════════════════╗')
|
||||
print(' ║ 自动寻找最大承载能力测试 ║')
|
||||
print(' ╚══════════════════════════════════════╝')
|
||||
print()
|
||||
print(' 测试模式: {}'.format(mode))
|
||||
print(' 策略: 逐步增加并发用户数,当错误率 > 5% 或')
|
||||
print(' 响应时间 P99 > 3s 时停止')
|
||||
print()
|
||||
|
||||
print(' [热身] 50 并发,10 秒...')
|
||||
tester = LoadTester(base_url, concurrency=50, duration=10, read_only=read_only)
|
||||
warmup = tester.run()
|
||||
if warmup is None:
|
||||
print(' ❌ 目标地址不可达')
|
||||
return
|
||||
|
||||
levels = [50, 100, 200, 300, 500, 800, 1000, 1500, 2000]
|
||||
results = []
|
||||
|
||||
for concurrency in levels:
|
||||
print()
|
||||
print(' ══════════════════════════════════════')
|
||||
print(' ▶ 测试 {} 并发...'.format(concurrency))
|
||||
print()
|
||||
|
||||
tester = LoadTester(base_url, concurrency=concurrency, duration=20, read_only=read_only)
|
||||
result = tester.run()
|
||||
|
||||
if result is None:
|
||||
print(' ❌ 测试中断')
|
||||
break
|
||||
|
||||
results.append(result)
|
||||
|
||||
broken = False
|
||||
reasons = []
|
||||
if result['success_rate'] < 95:
|
||||
reasons.append('错误率 {:.1f}% > 5%'.format(100 - result['success_rate']))
|
||||
broken = True
|
||||
if result['p99'] > 3.0:
|
||||
reasons.append('P99 {:.2f}s > 3s'.format(result['p99']))
|
||||
broken = True
|
||||
|
||||
if broken:
|
||||
print()
|
||||
print(' ⚠ 系统达到瓶颈!原因:')
|
||||
for r in reasons:
|
||||
print(' - {}'.format(r))
|
||||
print()
|
||||
|
||||
low = levels[levels.index(concurrency) - 1] if concurrency > levels[0] else 0
|
||||
high = concurrency
|
||||
for _ in range(3):
|
||||
mid = (low + high) // 2
|
||||
if mid <= low:
|
||||
break
|
||||
print(' ▶ 二分精确测试 {} 并发...'.format(mid))
|
||||
t2 = LoadTester(base_url, concurrency=mid, duration=15, read_only=read_only)
|
||||
r2 = t2.run()
|
||||
if r2 and r2['success_rate'] >= 95 and r2['p99'] < 3.0:
|
||||
low = mid
|
||||
else:
|
||||
high = mid
|
||||
|
||||
print()
|
||||
print(' ╔══════════════════════════════════════╗')
|
||||
print(' ║ 最大承载能力结论 ║')
|
||||
print(' ╚══════════════════════════════════════╝')
|
||||
print()
|
||||
print(' 测试模式: {}'.format(mode))
|
||||
print(' 稳定承载: 约 {} 并发用户'.format(low))
|
||||
print(' 极限承载: 约 {} 并发用户(有降级)'.format(concurrency))
|
||||
print()
|
||||
print(' 各并发级别结果:')
|
||||
print(' {:>8} {:>10} {:>8} {:>8} {:>8}'.format(
|
||||
'并发', '吞吐(r/s)', '成功率%', '平均(s)', 'P99(s)'))
|
||||
for r in results:
|
||||
print(' {:>8} {:>10.1f} {:>7.1f}% {:>8.3f} {:>8.3f}'.format(
|
||||
r['concurrency'], r['rps'], r['success_rate'],
|
||||
r['avg'], r['p99']))
|
||||
print()
|
||||
return low, concurrency
|
||||
|
||||
print()
|
||||
print(' ✅ {} 并发全部通过!系统承载能力超过测试上限。'.format(levels[-1]))
|
||||
print()
|
||||
print(' 各并发级别结果:')
|
||||
print(' {:>8} {:>10} {:>8} {:>8} {:>8}'.format(
|
||||
'并发', '吞吐(r/s)', '成功率%', '平均(s)', 'P99(s)'))
|
||||
for r in results:
|
||||
print(' {:>8} {:>10.1f} {:>7.1f}% {:>8.3f} {:>8.3f}'.format(
|
||||
r['concurrency'], r['rps'], r['success_rate'],
|
||||
r['avg'], r['p99']))
|
||||
print()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 主入口
|
||||
# ============================================================
|
||||
|
||||
def print_banner():
|
||||
print()
|
||||
print(' ╔══════════════════════════════════════╗')
|
||||
print(' ║ LiteAdmin 压力测试工具 v5.1 ║')
|
||||
print(' ║ Keep-Alive · 自动寻峰 · 压测 ║')
|
||||
print(' ╚══════════════════════════════════════╝')
|
||||
print()
|
||||
|
||||
|
||||
def main():
|
||||
print_banner()
|
||||
|
||||
parser = argparse.ArgumentParser(description='LiteAdmin 压力测试工具 v5.0')
|
||||
parser.add_argument('url', help='目标地址,如 http://192.168.1.24:8080')
|
||||
parser.add_argument('--concurrency', type=int, default=200, help='并发用户数(默认 200)')
|
||||
parser.add_argument('--duration', type=int, default=60, help='测试时长秒(默认 60)')
|
||||
parser.add_argument('--find-max', action='store_true', help='自动寻找最大承载能力')
|
||||
parser.add_argument('--read-only', action='store_true', help='仅模拟读操作')
|
||||
parser.add_argument('--skip-prepare', action='store_true', help='跳过数据准备阶段')
|
||||
parser.add_argument('--admin-user', default='admin', help='管理员用户名')
|
||||
parser.add_argument('--admin-pass', default='admin123', help='管理员密码')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# 检查目标
|
||||
print(' 检查目标 {} ...'.format(args.url))
|
||||
try:
|
||||
hc = KeepAliveHttpClient(args.url, timeout=5)
|
||||
code, body, elapsed = hc.get('/')
|
||||
if code == 200:
|
||||
print(' ✅ 目标可达 (HTTP {})'.format(code))
|
||||
else:
|
||||
print(' ⚠ 目标返回 HTTP {}'.format(code))
|
||||
except Exception as e:
|
||||
print(' ❌ 无法连接: {}'.format(e))
|
||||
sys.exit(1)
|
||||
print()
|
||||
|
||||
# 数据准备
|
||||
if not args.skip_prepare:
|
||||
ok = prepare_data(args.url, args.admin_user, args.admin_pass)
|
||||
if not ok:
|
||||
print(' ❌ 数据准备失败')
|
||||
sys.exit(1)
|
||||
print()
|
||||
else:
|
||||
print(' [跳过] 数据准备阶段')
|
||||
print()
|
||||
|
||||
# 运行压测
|
||||
if args.find_max:
|
||||
find_max_capacity(args.url, read_only=args.read_only)
|
||||
else:
|
||||
tester = LoadTester(args.url, concurrency=args.concurrency,
|
||||
duration=args.duration, read_only=args.read_only)
|
||||
tester.run()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user