import sys import traceback from fastapi import FastAPI from fastapi.testclient import TestClient from app.core.database import get_db from app.services.user_service import UserService from app.schemas.auth import UserRegister def test_api_exception(): """测试API异常处理""" try: print("=== 测试API异常处理 ===") # 导入应用 import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) from main import app # 创建测试客户端 client = TestClient(app) # 测试重复邮箱注册 print("1. 测试重复邮箱注册...") response = client.post("/api/v1/auth/register", json={ "username": "test_api", "email": "user@example.com", # 重复邮箱 "password": "TestPass123!", "confirm_password": "TestPass123!" }) print(f" HTTP状态码: {response.status_code}") print(f" 响应内容: {response.json()}") if response.status_code == 400: print(" ✓ 正确返回400错误") detail = response.json().get("detail", {}) if detail.get("code") == "EMAIL_EXISTS": print(" ✓ 正确返回EMAIL_EXISTS错误码") else: print(f" ✗ 错误码不正确: {detail.get('code')}") else: print(f" ✗ 状态码不正确,期望400,实际{response.status_code}") except Exception as e: print(f"测试过程出错: {e}") traceback.print_exc() if __name__ == "__main__": test_api_exception()