| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- """
- 测试动态路由发现功能
- 执行示例: `pytest tests/test_discover.py` 或 `pytest tests/`
- """
- import pytest
- from fastapi import APIRouter
- from app.core.discover import get_dynamic_router
- def test_get_dynamic_router_basic():
- """
- 测试基本的动态路由发现功能
- """
- # 调用函数获取路由
- router = get_dynamic_router()
-
- # 验证返回值是 APIRouter 实例
- assert isinstance(router, APIRouter)
-
- # 验证路由对象的基本属性
- assert hasattr(router, 'routes')
- assert isinstance(router.routes, list)
- def test_get_dynamic_router_error_handling():
- """
- 测试错误处理功能
- """
- # 即使发生错误,函数也应该返回一个空的 APIRouter 实例
- router = get_dynamic_router()
- assert isinstance(router, APIRouter)
- def test_route_count():
- """
- 测试路由数量并打印详细信息
- """
- router = get_dynamic_router()
- # 打印路由信息,方便调试
- print(f"\n=== 路由信息 ===")
- print(f"总路由数: {len(router.routes)}")
-
- # 遍历所有路由并打印
- for i, route in enumerate(router.routes):
- if hasattr(route, 'path'):
- print(f"路由 {i+1}: {route.path}")
- elif hasattr(route, 'routes'):
- print(f"子路由组: {len(route.routes)} 个路由")
- for j, sub_route in enumerate(route.routes):
- if hasattr(sub_route, 'path'):
- print(f" - 子路由 {j+1}: {sub_route.path}")
- print("================\n")
- def test_module_scanning():
- """
- 测试模块扫描功能
- """
- router = get_dynamic_router()
-
- # 验证路由是否包含预期的模块前缀
- expected_prefixes = [
- '/ai', # module_ai
- '/example', # module_example
- '/generator', # module_generator
- '/task', # module_task
- '/commerce' # module_commerce
- ]
-
- print(f"\n=== 验证模块前缀 ===")
- found_prefixes = []
-
- for route in router.routes:
- if hasattr(route, 'prefix'):
- prefix = route.prefix
- found_prefixes.append(prefix)
- print(f"发现模块前缀: {prefix}")
-
- # 检查是否在预期列表中
- if prefix in expected_prefixes:
- print(f" ✓ 预期前缀: {prefix}")
- else:
- print(f" ⚠ 未预期的前缀: {prefix}")
-
- print(f"\n预期前缀: {expected_prefixes}")
- print(f"发现前缀: {found_prefixes}")
- print("================\n")
- # 运行所有测试
- if __name__ == "__main__":
- pytest.main(["-v", "tests/test_discover.py"])
|