test_discover.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. """
  2. 测试动态路由发现功能
  3. 执行示例: `pytest tests/test_discover.py` 或 `pytest tests/`
  4. """
  5. import pytest
  6. from fastapi import APIRouter
  7. from app.core.discover import get_dynamic_router
  8. def test_get_dynamic_router_basic():
  9. """
  10. 测试基本的动态路由发现功能
  11. """
  12. # 调用函数获取路由
  13. router = get_dynamic_router()
  14. # 验证返回值是 APIRouter 实例
  15. assert isinstance(router, APIRouter)
  16. # 验证路由对象的基本属性
  17. assert hasattr(router, 'routes')
  18. assert isinstance(router.routes, list)
  19. def test_get_dynamic_router_error_handling():
  20. """
  21. 测试错误处理功能
  22. """
  23. # 即使发生错误,函数也应该返回一个空的 APIRouter 实例
  24. router = get_dynamic_router()
  25. assert isinstance(router, APIRouter)
  26. def test_route_count():
  27. """
  28. 测试路由数量并打印详细信息
  29. """
  30. router = get_dynamic_router()
  31. # 打印路由信息,方便调试
  32. print(f"\n=== 路由信息 ===")
  33. print(f"总路由数: {len(router.routes)}")
  34. # 遍历所有路由并打印
  35. for i, route in enumerate(router.routes):
  36. if hasattr(route, 'path'):
  37. print(f"路由 {i+1}: {route.path}")
  38. elif hasattr(route, 'routes'):
  39. print(f"子路由组: {len(route.routes)} 个路由")
  40. for j, sub_route in enumerate(route.routes):
  41. if hasattr(sub_route, 'path'):
  42. print(f" - 子路由 {j+1}: {sub_route.path}")
  43. print("================\n")
  44. def test_module_scanning():
  45. """
  46. 测试模块扫描功能
  47. """
  48. router = get_dynamic_router()
  49. # 验证路由是否包含预期的模块前缀
  50. expected_prefixes = [
  51. '/ai', # module_ai
  52. '/example', # module_example
  53. '/generator', # module_generator
  54. '/task', # module_task
  55. '/commerce' # module_commerce
  56. ]
  57. print(f"\n=== 验证模块前缀 ===")
  58. found_prefixes = []
  59. for route in router.routes:
  60. if hasattr(route, 'prefix'):
  61. prefix = route.prefix
  62. found_prefixes.append(prefix)
  63. print(f"发现模块前缀: {prefix}")
  64. # 检查是否在预期列表中
  65. if prefix in expected_prefixes:
  66. print(f" ✓ 预期前缀: {prefix}")
  67. else:
  68. print(f" ⚠ 未预期的前缀: {prefix}")
  69. print(f"\n预期前缀: {expected_prefixes}")
  70. print(f"发现前缀: {found_prefixes}")
  71. print("================\n")
  72. # 运行所有测试
  73. if __name__ == "__main__":
  74. pytest.main(["-v", "tests/test_discover.py"])