test_credential_update.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env python
  2. """
  3. 测试凭证更新功能
  4. 验证:
  5. 1. Account ID 字段是否可空
  6. 2. Access Key 类型凭证创建逻辑
  7. 3. 数据库模型更新
  8. """
  9. import os
  10. import sys
  11. # 添加项目根目录到路径
  12. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  13. from app import create_app, db
  14. from app.models import AWSCredential
  15. from sqlalchemy import text
  16. def test_database_schema():
  17. """测试数据库模式更新"""
  18. print("测试数据库模式...")
  19. app = create_app('testing')
  20. with app.app_context():
  21. # 创建测试表
  22. db.create_all()
  23. # 检查 account_id 字段是否可空
  24. try:
  25. # 尝试创建一个没有 account_id 的凭证
  26. test_credential = AWSCredential(
  27. name="Test Access Key",
  28. credential_type="access_key",
  29. account_id=None, # 测试可空
  30. access_key_id="AKIATEST123456789",
  31. is_active=True
  32. )
  33. test_credential.set_secret_access_key("test-secret-key")
  34. db.session.add(test_credential)
  35. db.session.commit()
  36. print("✓ account_id 字段可空测试通过")
  37. # 清理测试数据
  38. db.session.delete(test_credential)
  39. db.session.commit()
  40. except Exception as e:
  41. print(f"❌ account_id 字段可空测试失败: {e}")
  42. return False
  43. return True
  44. def test_model_methods():
  45. """测试模型方法"""
  46. print("测试模型方法...")
  47. app = create_app('testing')
  48. with app.app_context():
  49. db.create_all()
  50. try:
  51. # 测试 Assume Role 类型
  52. assume_role_cred = AWSCredential(
  53. name="Test Assume Role",
  54. credential_type="assume_role",
  55. account_id="123456789012",
  56. role_arn="arn:aws:iam::123456789012:role/TestRole",
  57. external_id="test-external-id",
  58. is_active=True
  59. )
  60. # 测试 Access Key 类型(无 account_id)
  61. access_key_cred = AWSCredential(
  62. name="Test Access Key",
  63. credential_type="access_key",
  64. account_id=None,
  65. access_key_id="AKIATEST123456789",
  66. is_active=True
  67. )
  68. access_key_cred.set_secret_access_key("test-secret-key")
  69. # 测试 to_dict 方法
  70. assume_role_dict = assume_role_cred.to_dict()
  71. access_key_dict = access_key_cred.to_dict()
  72. print("✓ Assume Role 凭证字典:", assume_role_dict)
  73. print("✓ Access Key 凭证字典:", access_key_dict)
  74. # 验证字段
  75. assert assume_role_dict['credential_type'] == 'assume_role'
  76. assert assume_role_dict['account_id'] == '123456789012'
  77. assert access_key_dict['credential_type'] == 'access_key'
  78. assert access_key_dict['account_id'] is None
  79. print("✓ 模型方法测试通过")
  80. except Exception as e:
  81. print(f"❌ 模型方法测试失败: {e}")
  82. return False
  83. return True
  84. def test_api_validation():
  85. """测试API验证逻辑"""
  86. print("测试API验证逻辑...")
  87. from app.api.credentials import validate_account_id, validate_role_arn
  88. try:
  89. # 测试 account_id 验证
  90. assert validate_account_id("123456789012") == True
  91. assert validate_account_id("12345678901") == False # 11位
  92. assert validate_account_id("1234567890123") == False # 13位
  93. assert validate_account_id("12345678901a") == False # 包含字母
  94. assert validate_account_id("") == False # 空字符串
  95. assert validate_account_id(None) == False # None
  96. # 测试 role_arn 验证
  97. assert validate_role_arn("arn:aws:iam::123456789012:role/TestRole") == True
  98. assert validate_role_arn("arn:aws:iam::123456789012:user/TestUser") == False # 不是role
  99. assert validate_role_arn("invalid-arn") == False # 无效格式
  100. assert validate_role_arn("") == False # 空字符串
  101. assert validate_role_arn(None) == False # None
  102. print("✓ API验证逻辑测试通过")
  103. except Exception as e:
  104. print(f"❌ API验证逻辑测试失败: {e}")
  105. return False
  106. return True
  107. def main():
  108. """运行所有测试"""
  109. print("="*50)
  110. print("凭证更新功能测试")
  111. print("="*50)
  112. tests = [
  113. ("数据库模式", test_database_schema),
  114. ("模型方法", test_model_methods),
  115. ("API验证", test_api_validation),
  116. ]
  117. results = []
  118. for test_name, test_func in tests:
  119. print(f"\n{test_name}测试:")
  120. try:
  121. result = test_func()
  122. results.append((test_name, result))
  123. except Exception as e:
  124. print(f"❌ {test_name}测试异常: {e}")
  125. results.append((test_name, False))
  126. print("\n" + "="*50)
  127. print("测试结果:")
  128. print("="*50)
  129. all_passed = True
  130. for test_name, result in results:
  131. status = "✓ 通过" if result else "❌ 失败"
  132. print(f" {test_name}: {status}")
  133. if not result:
  134. all_passed = False
  135. if all_passed:
  136. print("\n🎉 所有测试通过! 凭证更新功能正常。")
  137. else:
  138. print("\n⚠️ 部分测试失败,请检查问题。")
  139. print("="*50)
  140. if __name__ == '__main__':
  141. main()