Files
full-stack-doc/backend/test_upload_download_api.py
2025-10-14 20:05:29 +08:00

114 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
接口级上传下载测试
"""
import requests
import json
import sys
import io
# 设置stdout编码为utf-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
BASE_URL = "http://localhost:8000/api/v1"
def test_upload_download():
print("=== 测试文件上传下载 ===")
# 1. 先创建测试用户
print("1. 创建测试用户...")
register_data = {
"username": "testuser456",
"email": "test456@example.com",
"password": "Test123456!",
"confirm_password": "Test123456!"
}
try:
response = requests.post(f"{BASE_URL}/auth/register", json=register_data)
print(f"注册响应状态: {response.status_code}")
print(f"注册响应内容: {response.text}")
if response.status_code == 201:
user_id = response.json()["data"]["user"]["id"]
print(f"[OK] 用户创建成功ID: {user_id}")
else:
# 创建另一个用户
register_data = {
"username": f"testuser{hash('test') % 10000}",
"email": f"test{hash('test') % 10000}@example.com",
"password": "Test123456!",
"confirm_password": "Test123456!"
}
response = requests.post(f"{BASE_URL}/auth/register", json=register_data)
if response.status_code == 201:
user_id = response.json()["data"]["user"]["id"]
print(f"[OK] 新用户创建成功ID: {user_id}")
else:
print(f"[ERROR] 用户创建失败")
return
except Exception as e:
print(f"[ERROR] 请求异常: {e}")
return
# 2. 上传文件
print("\n2. 上传测试文件...")
test_content = "这是测试文件内容\nTest file content\n你好世界!"
files = {'file': ('test.txt', test_content, 'text/plain')}
data = {
'user_id': str(user_id),
'description': '测试文件',
'tags': 'test',
'is_public': 'false'
}
try:
upload_resp = requests.post(f"{BASE_URL}/files/upload", files=files, data=data)
print(f"上传状态码: {upload_resp.status_code}")
print(f"上传响应: {upload_resp.text}")
if upload_resp.status_code == 201:
file_id = upload_resp.json()["data"]["file"]["id"]
print(f"[OK] 上传成功文件ID: {file_id}")
else:
print("[ERROR] 上传失败")
return
except Exception as e:
print(f"[ERROR] 上传异常: {e}")
return
# 3. 下载文件
print(f"\n3. 下载文件 ID: {file_id}...")
download_data = {
"file_id": file_id,
"user_id": user_id
}
try:
download_resp = requests.post(f"{BASE_URL}/files/download", json=download_data)
print(f"下载状态码: {download_resp.status_code}")
print(f"下载响应头: {dict(download_resp.headers)}")
if download_resp.status_code == 200:
downloaded_content = download_resp.text
print(f"[OK] 下载成功")
print(f"下载内容: {downloaded_content}")
print(f"内容长度: {len(downloaded_content)}")
# 验证内容
if test_content == downloaded_content:
print("[OK] 内容一致")
else:
print("[ERROR] 内容不一致")
print(f"原始: {repr(test_content)}")
print(f"下载: {repr(downloaded_content)}")
else:
print(f"[ERROR] 下载失败: {download_resp.text}")
except Exception as e:
print(f"[ERROR] 下载异常: {e}")
if __name__ == "__main__":
test_upload_download()