test_celery_task.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. #!/usr/bin/env python
  2. """
  3. 测试Celery任务提交
  4. 用于诊断任务提交时的具体问题
  5. """
  6. import os
  7. import sys
  8. # 添加项目根目录到路径
  9. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  10. def test_celery_import():
  11. """测试Celery模块导入"""
  12. print("🔍 测试Celery模块导入...")
  13. try:
  14. from app import create_app
  15. app = create_app()
  16. with app.app_context():
  17. print("✅ Flask应用上下文创建成功")
  18. # 测试导入scan_tasks
  19. try:
  20. from app.tasks.scan_tasks import scan_aws_resources
  21. print("✅ scan_tasks模块导入成功")
  22. # 测试任务提交
  23. try:
  24. # 创建一个测试任务
  25. celery_task = scan_aws_resources.delay(
  26. task_id=999, # 测试ID
  27. credential_ids=[1],
  28. regions=['us-east-1'],
  29. project_metadata={'clientName': 'Test', 'projectName': 'Test'}
  30. )
  31. print(f"✅ Celery任务提交成功: {celery_task.id}")
  32. return True
  33. except Exception as e:
  34. print(f"❌ Celery任务提交失败: {e}")
  35. print(f"错误类型: {type(e).__name__}")
  36. return False
  37. except Exception as e:
  38. print(f"❌ scan_tasks模块导入失败: {e}")
  39. print(f"错误类型: {type(e).__name__}")
  40. return False
  41. except Exception as e:
  42. print(f"❌ Flask应用创建失败: {e}")
  43. return False
  44. def test_mock_import():
  45. """测试Mock模块导入"""
  46. print("\n🔍 测试Mock模块导入...")
  47. try:
  48. from app import create_app
  49. app = create_app()
  50. with app.app_context():
  51. from app.tasks.mock_tasks import scan_aws_resources
  52. print("✅ mock_tasks模块导入成功")
  53. # 测试Mock任务提交
  54. try:
  55. celery_task = scan_aws_resources.delay(
  56. task_id=999, # 测试ID
  57. credential_ids=[1],
  58. regions=['us-east-1'],
  59. project_metadata={'clientName': 'Test', 'projectName': 'Test'}
  60. )
  61. print(f"✅ Mock任务提交成功: {celery_task.id}")
  62. return True
  63. except Exception as e:
  64. print(f"❌ Mock任务提交失败: {e}")
  65. return False
  66. except Exception as e:
  67. print(f"❌ Mock模块测试失败: {e}")
  68. return False
  69. def test_celery_config():
  70. """测试Celery配置"""
  71. print("\n🔍 测试Celery配置...")
  72. try:
  73. from app.celery_app import celery_app
  74. print(f"Broker URL: {celery_app.conf.broker_url}")
  75. print(f"Result Backend: {celery_app.conf.result_backend}")
  76. # 测试连接
  77. try:
  78. inspect = celery_app.control.inspect()
  79. stats = inspect.stats()
  80. if stats:
  81. print(f"✅ Celery连接成功,Worker数量: {len(stats)}")
  82. return True
  83. else:
  84. print("⚠️ Celery连接成功,但没有Worker运行")
  85. return True
  86. except Exception as e:
  87. print(f"❌ Celery连接失败: {e}")
  88. return False
  89. except Exception as e:
  90. print(f"❌ Celery配置测试失败: {e}")
  91. return False
  92. def main():
  93. """运行所有测试"""
  94. print("="*60)
  95. print("Celery任务提交诊断")
  96. print("="*60)
  97. tests = [
  98. ("Celery配置", test_celery_config),
  99. ("Celery任务导入和提交", test_celery_import),
  100. ("Mock任务导入和提交", test_mock_import),
  101. ]
  102. results = []
  103. for test_name, test_func in tests:
  104. try:
  105. result = test_func()
  106. results.append((test_name, result))
  107. except Exception as e:
  108. print(f"❌ {test_name}测试异常: {e}")
  109. results.append((test_name, False))
  110. print("\n" + "="*60)
  111. print("诊断结果:")
  112. print("="*60)
  113. for test_name, result in results:
  114. status = "✅ 通过" if result else "❌ 失败"
  115. print(f" {test_name}: {status}")
  116. # 给出建议
  117. celery_ok = results[1][1] if len(results) > 1 else False
  118. mock_ok = results[2][1] if len(results) > 2 else False
  119. print("\n📋 建议:")
  120. if celery_ok:
  121. print(" ✅ Celery工作正常,建议启动Worker获得最佳性能")
  122. print(" celery -A app.celery_app worker --loglevel=info")
  123. elif mock_ok:
  124. print(" 🔄 Celery有问题,但Mock模式可用")
  125. print(" 💡 可以使用Mock模式进行开发测试")
  126. else:
  127. print(" ❌ 两种模式都有问题,请检查配置")
  128. print("="*60)
  129. if __name__ == '__main__':
  130. main()