test_difficulty_fix.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 测试difficulty字段修复情况
  5. 验证数据库中题目的difficulty字段是否正确设置
  6. """
  7. import requests
  8. import json
  9. import time
  10. import jaydebeapi
  11. import os
  12. # 配置
  13. BASE_URL = "http://localhost:8080/api"
  14. # H2数据库配置(内存数据库)
  15. H2_URL = "jdbc:h2:mem:testdb"
  16. H2_USER = "sa"
  17. H2_PASSWORD = ""
  18. H2_DRIVER = "org.h2.Driver"
  19. # 下载H2驱动(如果不存在)
  20. H2_JAR_PATH = "h2.jar"
  21. def download_h2_driver():
  22. """下载H2数据库驱动"""
  23. if not os.path.exists(H2_JAR_PATH):
  24. print("正在下载H2数据库驱动...")
  25. import urllib.request
  26. try:
  27. urllib.request.urlretrieve(
  28. "https://repo1.maven.org/maven2/com/h2database/h2/2.2.224/h2-2.2.224.jar",
  29. H2_JAR_PATH
  30. )
  31. print("✓ H2驱动下载成功")
  32. except Exception as e:
  33. print(f"✗ H2驱动下载失败: {e}")
  34. return False
  35. return True
  36. def test_h2_console_access():
  37. """测试H2控制台访问"""
  38. try:
  39. response = requests.get("http://localhost:8080/h2-console", timeout=5)
  40. if response.status_code == 200:
  41. print("✓ H2控制台可访问")
  42. print(" 访问地址: http://localhost:8080/h2-console")
  43. print(" JDBC URL: jdbc:h2:mem:testdb")
  44. print(" 用户名: sa")
  45. print(" 密码: (空)")
  46. return True
  47. else:
  48. print(f"✗ H2控制台访问失败,状态码: {response.status_code}")
  49. return False
  50. except Exception as e:
  51. print(f"✗ H2控制台访问错误: {e}")
  52. return False
  53. def test_database_connection():
  54. """测试数据库连接(通过H2控制台信息)"""
  55. print("\n=== H2内存数据库信息 ===")
  56. print("由于H2是内存数据库,只能在应用运行时访问")
  57. return test_h2_console_access()
  58. def check_existing_difficulty_data(connection):
  59. """检查现有数据的difficulty字段"""
  60. try:
  61. cursor = connection.cursor()
  62. # 查询goal_detail表中的difficulty字段
  63. query = """
  64. SELECT id, goal_id, question, difficulty, created_at
  65. FROM goal_detail
  66. ORDER BY created_at DESC
  67. LIMIT 10
  68. """
  69. cursor.execute(query)
  70. results = cursor.fetchall()
  71. print("\n=== 现有题目difficulty字段检查 ===")
  72. if results:
  73. for row in results:
  74. id_val, goal_id, question, difficulty, created_at = row
  75. question_preview = question[:50] + "..." if len(question) > 50 else question
  76. print(f"ID: {id_val}, Goal: {goal_id}, Difficulty: {difficulty}, Question: {question_preview}")
  77. else:
  78. print("数据库中没有找到题目数据")
  79. # 统计difficulty字段的分布
  80. stats_query = """
  81. SELECT difficulty, COUNT(*) as count
  82. FROM goal_detail
  83. GROUP BY difficulty
  84. """
  85. cursor.execute(stats_query)
  86. stats = cursor.fetchall()
  87. print("\n=== Difficulty字段统计 ===")
  88. for difficulty, count in stats:
  89. print(f"Difficulty: {difficulty if difficulty else 'NULL'}, Count: {count}")
  90. cursor.close()
  91. return True
  92. except Exception as e:
  93. print(f"✗ 查询数据库失败: {e}")
  94. return False
  95. def test_generate_new_question():
  96. """测试生成新题目"""
  97. print("\n=== 测试生成新题目 ===")
  98. # 准备测试数据
  99. test_data = {
  100. "goalId": 1,
  101. "subject": "数学",
  102. "type": "选择题",
  103. "difficulty": "简单",
  104. "totalQuantity": 1,
  105. "knowledgePoint": "基础运算"
  106. }
  107. try:
  108. # 调用生成题目API
  109. response = requests.post(
  110. f"{BASE_URL}/ai-question/generate",
  111. json=test_data,
  112. headers={'Content-Type': 'application/json'},
  113. timeout=30
  114. )
  115. if response.status_code == 200:
  116. result = response.json()
  117. print(f"✓ 题目生成成功: {result}")
  118. return True
  119. else:
  120. print(f"✗ 题目生成失败,状态码: {response.status_code}")
  121. print(f"响应内容: {response.text}")
  122. return False
  123. except requests.exceptions.RequestException as e:
  124. print(f"✗ 请求失败: {e}")
  125. return False
  126. def check_new_difficulty_data(connection):
  127. """检查新生成题目的difficulty字段"""
  128. try:
  129. cursor = connection.cursor()
  130. # 查询最新生成的题目(H2语法)
  131. query = """
  132. SELECT id, goal_id, question, difficulty, created_at
  133. FROM goal_detail
  134. WHERE created_at >= DATEADD('MINUTE', -5, NOW())
  135. ORDER BY created_at DESC
  136. """
  137. cursor.execute(query)
  138. results = cursor.fetchall()
  139. print("\n=== 新生成题目difficulty字段检查 ===")
  140. if results:
  141. for row in results:
  142. id_val, goal_id, question, difficulty, created_at = row
  143. question_preview = question[:50] + "..." if len(question) > 50 else question
  144. status = "✓" if difficulty is not None else "✗"
  145. print(f"{status} ID: {id_val}, Goal: {goal_id}, Difficulty: {difficulty}, Created: {created_at}")
  146. print(f" Question: {question_preview}")
  147. else:
  148. print("没有找到最近5分钟内生成的题目")
  149. cursor.close()
  150. return len(results) > 0
  151. except Exception as e:
  152. print(f"✗ 查询新数据失败: {e}")
  153. return False
  154. def test_api_endpoints():
  155. """测试相关API端点"""
  156. print("\n=== 测试API端点 ===")
  157. # 测试健康检查
  158. try:
  159. response = requests.get(f"{BASE_URL}/health", timeout=5)
  160. print(f"健康检查: {response.status_code}")
  161. except:
  162. print("健康检查: API不可用")
  163. # 测试获取目标列表
  164. try:
  165. response = requests.get(f"{BASE_URL}/goals", timeout=5)
  166. if response.status_code == 200:
  167. goals = response.json()
  168. print(f"✓ 目标列表获取成功,共{len(goals)}个目标")
  169. if goals:
  170. print(f" 示例目标ID: {goals[0].get('id', 'N/A')}")
  171. return goals[0].get('id', 1)
  172. else:
  173. print(f"✗ 目标列表获取失败: {response.status_code}")
  174. except Exception as e:
  175. print(f"✗ 目标列表获取错误: {e}")
  176. return 1 # 默认使用目标ID 1
  177. def main():
  178. """主测试函数"""
  179. print("开始测试difficulty字段修复情况...")
  180. # 1. 测试数据库连接信息
  181. test_database_connection()
  182. # 2. 测试API端点
  183. goal_id = test_api_endpoints()
  184. # 3. 测试生成新题目
  185. print("\n=== 测试生成新题目 ===")
  186. test_data = {
  187. "goalId": goal_id,
  188. "subject": "数学",
  189. "type": "选择题",
  190. "difficulty": "简单",
  191. "totalQuantity": 1,
  192. "knowledgePoint": "基础运算"
  193. }
  194. try:
  195. response = requests.post(
  196. f"{BASE_URL}/ai-question/generate",
  197. json=test_data,
  198. headers={'Content-Type': 'application/json'},
  199. timeout=30
  200. )
  201. if response.status_code == 200:
  202. result = response.json()
  203. print(f"✓ 题目生成成功")
  204. print(f" 响应数据: {json.dumps(result, ensure_ascii=False, indent=2)}")
  205. # 检查响应中是否包含difficulty字段
  206. if isinstance(result, list) and result:
  207. for i, question in enumerate(result):
  208. difficulty = question.get('difficulty')
  209. print(f" 题目{i+1} difficulty字段: {difficulty}")
  210. if difficulty is None:
  211. print(f" ⚠️ 题目{i+1}的difficulty字段为null")
  212. else:
  213. print(f" ✓ 题目{i+1}的difficulty字段正常: {difficulty}")
  214. else:
  215. print(f"✗ 题目生成失败,状态码: {response.status_code}")
  216. print(f" 响应内容: {response.text}")
  217. except Exception as e:
  218. print(f"✗ 题目生成请求失败: {e}")
  219. print("\n=== 数据库检查说明 ===")
  220. print("由于使用H2内存数据库,请通过以下方式手动检查:")
  221. print("1. 访问 http://localhost:8080/h2-console")
  222. print("2. 使用连接信息: jdbc:h2:mem:testdb, 用户名: sa, 密码: (空)")
  223. print("3. 执行SQL: SELECT id, goal_id, question, difficulty, created_at FROM goal_detail ORDER BY created_at DESC LIMIT 10")
  224. print("4. 检查difficulty字段是否为null")
  225. print("\n=== 测试完成 ===")
  226. if __name__ == "__main__":
  227. main()