|
|
from locust import HttpUser, task, between, tag
|
|
|
import random
|
|
|
import string
|
|
|
import json
|
|
|
import io
|
|
|
from PIL import Image
|
|
|
|
|
|
|
|
|
class GradioImageUser(HttpUser):
|
|
|
wait_time = between(1, 3)
|
|
|
|
|
|
def on_start(self):
|
|
|
"""用户启动时的初始化操作"""
|
|
|
|
|
|
self.upload_id = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
|
|
|
|
|
|
|
|
|
self.test_image = self.generate_test_image()
|
|
|
|
|
|
def generate_test_image(self):
|
|
|
"""生成随机测试图片并返回字节流"""
|
|
|
|
|
|
img = Image.new('RGB', (200, 200), color=(
|
|
|
random.randint(0, 255),
|
|
|
random.randint(0, 255),
|
|
|
random.randint(0, 255)
|
|
|
))
|
|
|
|
|
|
|
|
|
img_byte_arr = io.BytesIO()
|
|
|
img.save(img_byte_arr, format='JPEG')
|
|
|
img_byte_arr.seek(0)
|
|
|
|
|
|
return img_byte_arr
|
|
|
|
|
|
@task(2)
|
|
|
@tag("upload")
|
|
|
def upload_image(self):
|
|
|
"""模拟图片上传操作"""
|
|
|
|
|
|
|
|
|
random_filename = f"test_image_{random.randint(1000, 9999)}.jpg"
|
|
|
|
|
|
files = {
|
|
|
'file': (
|
|
|
random_filename,
|
|
|
self.test_image,
|
|
|
'image/jpeg'
|
|
|
)
|
|
|
}
|
|
|
|
|
|
|
|
|
with self.client.post(
|
|
|
f"/gradio_api/upload?upload_id={self.upload_id}",
|
|
|
files=files,
|
|
|
catch_response=True
|
|
|
) as response:
|
|
|
if response.status_code != 200:
|
|
|
response.failure(f"上传失败,状态码: {response.status_code}")
|
|
|
else:
|
|
|
try:
|
|
|
|
|
|
json_response = response.json()
|
|
|
|
|
|
response.success()
|
|
|
except json.JSONDecodeError:
|
|
|
response.failure("响应不是有效的JSON格式")
|
|
|
|
|
|
@task(1)
|
|
|
@tag("queue")
|
|
|
def join_queue(self):
|
|
|
"""模拟加入队列操作"""
|
|
|
|
|
|
payload = {
|
|
|
"data": [
|
|
|
f"uploaded_file:{self.upload_id}",
|
|
|
True
|
|
|
],
|
|
|
"event_data": None,
|
|
|
"fn_index": 0,
|
|
|
"session_hash": self.upload_id
|
|
|
}
|
|
|
|
|
|
|
|
|
with self.client.post(
|
|
|
"/gradio_api/queue/join?",
|
|
|
json=payload,
|
|
|
headers={"Content-Type": "application/json"},
|
|
|
catch_response=True
|
|
|
) as response:
|
|
|
if response.status_code != 200:
|
|
|
response.failure(f"加入队列失败,状态码: {response.status_code}")
|
|
|
else:
|
|
|
try:
|
|
|
json_response = response.json()
|
|
|
response.success()
|
|
|
except json.JSONDecodeError:
|
|
|
response.failure("响应不是有效的JSON格式") |