| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 测试认证修复
- 验证get_current_user返回元组的问题是否已解决
- """
- import sys
- import os
- import asyncio
- from datetime import datetime, timedelta, timezone
- # 添加src目录到Python路径
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
- from app.services.jwt_token import create_access_token
- from app.services.auth_service import AuthService
- from app.core.config import config_handler
- class MockDB:
- """模拟数据库会话"""
- async def execute(self, stmt):
- class MockResult:
- def scalar_one_or_none(self):
- return None
- return MockResult()
-
- async def commit(self):
- pass
- async def test_auth_service_methods():
- """测试AuthService的方法"""
- print("🧪 测试AuthService方法")
-
- # 创建测试token
- test_data = {
- "sub": "test_user_123",
- "username": "testuser",
- "email": "test@example.com",
- "is_superuser": False
- }
-
- token = create_access_token(test_data)
- print(f"✅ 测试Token创建成功: {token[:50]}...")
-
- # 创建AuthService实例(使用模拟数据库)
- mock_db = MockDB()
- auth_service = AuthService(mock_db)
-
- try:
- # 测试get_current_user方法(返回元组)
- print("\n🔍 测试get_current_user方法(返回元组):")
- try:
- user, new_token = await auth_service.get_current_user(token)
- print(f"❌ 预期失败但成功了: user={user}, new_token={new_token}")
- except Exception as e:
- print(f"✅ 预期的异常(因为没有真实数据库): {type(e).__name__}: {str(e)[:100]}")
-
- # 测试get_current_user_only方法(返回用户对象)
- print("\n🔍 测试get_current_user_only方法(返回用户对象):")
- try:
- user = await auth_service.get_current_user_only(token)
- print(f"❌ 预期失败但成功了: user={user}")
- except Exception as e:
- print(f"✅ 预期的异常(因为没有真实数据库): {type(e).__name__}: {str(e)[:100]}")
-
- print("\n✅ 方法签名测试通过 - 没有语法错误")
-
- except Exception as e:
- print(f"❌ 测试失败: {e}")
- import traceback
- traceback.print_exc()
- def test_return_types():
- """测试返回类型注解"""
- print("\n🧪 测试返回类型注解")
-
- # 检查方法签名
- from app.services.auth_service import AuthService
- import inspect
-
- # 检查get_current_user方法
- get_current_user_sig = inspect.signature(AuthService.get_current_user)
- print(f"✅ get_current_user签名: {get_current_user_sig}")
-
- # 检查get_current_user_only方法
- get_current_user_only_sig = inspect.signature(AuthService.get_current_user_only)
- print(f"✅ get_current_user_only签名: {get_current_user_only_sig}")
-
- # 检查返回类型注解
- get_current_user_return = get_current_user_sig.return_annotation
- get_current_user_only_return = get_current_user_only_sig.return_annotation
-
- print(f"✅ get_current_user返回类型: {get_current_user_return}")
- print(f"✅ get_current_user_only返回类型: {get_current_user_only_return}")
- def test_import_compatibility():
- """测试导入兼容性"""
- print("\n🧪 测试导入兼容性")
-
- try:
- # 测试auth_view导入
- from views.auth_view import get_user_info
- print("✅ auth_view导入成功")
-
- # 测试tag_view导入
- from views.tag_view import get_current_user_id
- print("✅ tag_view导入成功")
-
- # 测试system_view导入
- from views.system_view import get_dashboard
- print("✅ system_view导入成功")
-
- print("✅ 所有视图文件导入成功")
-
- except Exception as e:
- print(f"❌ 导入失败: {e}")
- import traceback
- traceback.print_exc()
- async def main():
- """主测试函数"""
- print("🚀 开始测试认证修复")
- print("=" * 60)
-
- try:
- # 测试返回类型
- test_return_types()
-
- # 测试AuthService方法
- await test_auth_service_methods()
-
- # 测试导入兼容性
- test_import_compatibility()
-
- print("\n" + "=" * 60)
- print("🎉 认证修复测试完成!")
- print("\n📋 修复总结:")
- print("✅ get_current_user() 返回 (user, new_token) 元组")
- print("✅ get_current_user_only() 返回 User 对象(向后兼容)")
- print("✅ auth_view.py 已修复,正确处理元组返回值")
- print("✅ tag_view.py 已修复,使用向后兼容方法")
- print("✅ 所有视图文件可以正常导入")
-
- except Exception as e:
- print(f"\n❌ 测试过程中发生错误: {e}")
- import traceback
- traceback.print_exc()
- if __name__ == "__main__":
- asyncio.run(main())
|