Files
python-template/backend/test_json_export.py
T
gaoandQwen-Coder 1701472642 feat: Enhanced PDF parsing and question extraction system
- Implemented enhanced PDF parsing with V2 parser for better question extraction
- Added improved question formatting and display components
- Integrated question navigation and progress tracking features
- Added JSON export functionality for paper questions
- Enhanced image extraction and association with questions
- Improved database configuration with environment variables
- Updated UI with responsive question cards and navigation sidebar
- Added mathematical symbol rendering and question type detection

Co-authored-by: Qwen-Coder <[email protected]>
2025-11-02 15:54:43 +08:00

175 lines
6.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
测试JSON导出功能
"""
import os
import sys
import json
from utils.question_formatter import QuestionFormatter
def test_question_formatter():
"""测试题目格式化器"""
print("🧪 测试题目格式化器...")
# 创建测试数据
test_questions = [
{
"id": 1,
"number": "1",
"question_type": "single_choice",
"subject": "数学",
"grade": "grade8",
"difficulty": 3,
"question_content": "1. 解方程:(1) 2x² - 4x - 5 = 0;(2) (x - 3)(x - 1) = (x - 2)(x - 1) 5分",
"options": {
"A": "x₁ = 2 + √7, x₂ = 2 - √7",
"B": "x₁ = 1, x₂ = 5",
"C": "x₁ = 3, x₂ = -1",
"D": "无解"
},
"correct_answer": "A",
"explanation": "对于方程(1),使用求根公式可得解。对于方程(2),两边同时除以(x-1)可得x-3 = x-2,此方程无解。",
"knowledge_points": ["一元二次方程", "求根公式"],
"score": 5,
"images": [
{
"url": "/images/eq1.png",
"alt": "方程图片"
}
],
"created_at": "2024-01-15T10:30:00"
},
{
"id": 2,
"number": "2",
"question_type": "essay",
"subject": "数学",
"grade": "grade8",
"difficulty": 4,
"question_content": "2. 如图,在△ABC 中,AB = AC,D、E 分别是AB、BC 的中点,BF ∥ DE,EF ∥ DB。求证:四边形BDEF 是菱形;若 BE = 4,AC = 5,求DM 的长。",
"options": {},
"correct_answer": "证明:由于D、E是中点,BF∥DE,EF∥DB,可得四边形BDEF是平行四边形。又因为BF=EF(中位线相等),所以是菱形。DM = 3",
"explanation": "本题考查中位线定理和菱形的判定与性质。",
"knowledge_points": ["中位线定理", "菱形的判定", "勾股定理"],
"score": 8,
"images": [],
"created_at": "2024-01-15T10:31:00"
}
]
test_paper_info = {
"id": 1,
"title": "2025年9月2日初中数学作业",
"subject": "数学",
"grade": "grade8"
}
# 创建格式化器
formatter = QuestionFormatter()
# 测试单个题目格式化
print("\n📝 测试单个题目格式化...")
for i, question in enumerate(test_questions):
print(f"\n--- 题目 {i+1} ---")
formatted = formatter.format_question(question, test_paper_info)
print(f"题号: {formatted['number']}")
print(f"类型: {formatted['type']}")
print(f"学科: {formatted['subject']}")
print(f"难度: {formatted['difficulty']['label']}")
print(f"分值: {formatted['score']['formatted']}")
print(f"题干: {formatted['stem'][:50]}...")
print(f"选项数量: {len(formatted['options'])}")
print(f"知识点: {[kp['name'] for kp in formatted['knowledge_points']]}")
print(f"验证状态: {'✅' if formatted['validation']['is_valid'] else '❌'}")
print(f"完整性分数: {formatted['validation']['completeness_score']:.2f}")
# 测试试卷格式化
print("\n📚 测试试卷格式化...")
paper_data = {
"paper_id": 1,
"title": "2025年9月2日初中数学作业",
"subject": "数学",
"grade": "grade8",
"questions": test_questions
}
formatted_paper = formatter.format_paper_questions(paper_data)
print(f"试卷标题: {formatted_paper['paper_info']['title']}")
print(f"题目总数: {formatted_paper['statistics']['total_questions']}")
print(f"总用时: {formatted_paper['statistics']['estimated_time_formatted']}")
print(f"题目类型分布: {formatted_paper['statistics']['question_types']}")
print(f"难度分布: {formatted_paper['statistics']['difficulty_distribution']}")
print(f"知识点列表: {formatted_paper['statistics']['knowledge_points']}")
print(f"包含图片题目: {formatted_paper['statistics']['has_images']}个")
# 导出JSON文件
print("\n💾 导出JSON文件...")
output_file = "test_output.json"
if formatter.export_to_json_file(formatted_paper, output_file):
print(f"✅ 成功导出到: {output_file}")
# 验证文件大小
if os.path.exists(output_file):
file_size = os.path.getsize(output_file)
print(f"文件大小: {file_size} 字节")
# 读取并验证JSON
with open(output_file, 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print(f"JSON验证: ✅ 格式正确")
print(f"加载的题目数量: {len(loaded_data['questions'])}")
else:
print("❌ 导出失败")
# 测试JSON字符串导出
print("\n📄 测试JSON字符串导出...")
json_string = formatter.export_to_json_string(formatted_paper)
print(f"JSON字符串长度: {len(json_string)} 字符")
# 验证JSON字符串
try:
parsed = json.loads(json_string)
print("✅ JSON字符串格式正确")
except json.JSONDecodeError as e:
print(f"❌ JSON字符串格式错误: {e}")
print("\n🎉 格式化器测试完成!")
def test_error_handling():
"""测试错误处理"""
print("\n🔧 测试错误处理...")
formatter = QuestionFormatter()
# 测试空数据
empty_question = {}
formatted = formatter.format_question(empty_question)
print(f"空数据处理: {'✅' if not formatted['validation']['is_valid'] else '❌'}")
# 测试缺失重要字段
incomplete_question = {
"id": 1,
"question_content": "这是一个不完整的题目"
}
formatted = formatter.format_question(incomplete_question)
print(f"不完整数据处理: {'✅' if formatted['validation']['warnings'] else '❌'}")
print("错误处理测试完成!")
if __name__ == "__main__":
print("=" * 60)
print("🧪 JSON导出功能测试")
print("=" * 60)
try:
test_question_formatter()
test_error_handling()
print("\n🎉 所有测试通过!")
except Exception as e:
print(f"\n❌ 测试失败: {e}")
import traceback
traceback.print_exc()
sys.exit(1)