#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 测试答题页面提交按钮API调用 """ import requests import json import time # 服务器配置 BASE_URL = "http://localhost:8080" SUBMIT_URL = f"{BASE_URL}/api/user-answers/submit" def test_submit_answer(): """ 测试提交答案接口 """ print("=== 测试答题提交接口 ===") # 模拟提交答案的请求数据 submit_data = { "userId": 1, "goalId": 1, # 使用已存在的目标ID "contentId": 1, # 使用已存在的题目ID "userAnswer": "y = x² + 2x + 1", # 使用正确答案 "answerDuration": 30 # 答题时长30秒 } print(f"请求URL: {SUBMIT_URL}") print(f"请求数据: {json.dumps(submit_data, ensure_ascii=False, indent=2)}") try: # 发送POST请求 response = requests.post( SUBMIT_URL, json=submit_data, headers={ 'Content-Type': 'application/json' }, timeout=10 ) print(f"\n响应状态码: {response.status_code}") print(f"响应头: {dict(response.headers)}") if response.text: try: response_json = response.json() print(f"响应内容: {json.dumps(response_json, ensure_ascii=False, indent=2)}") # 判断是否成功 if response.status_code == 200: if response_json.get('code') == 200: print("\n✅ 提交答案成功!") return True else: print(f"\n❌ 提交失败: {response_json.get('message', '未知错误')}") return False else: print(f"\n❌ HTTP请求失败: {response.status_code}") return False except json.JSONDecodeError: print(f"响应内容(非JSON): {response.text}") return False else: print("响应内容为空") return False except requests.exceptions.ConnectionError: print("\n❌ 连接失败: 服务器未启动或无法访问") return False except requests.exceptions.Timeout: print("\n❌ 请求超时") return False except Exception as e: print(f"\n❌ 请求异常: {str(e)}") return False def test_multiple_submissions(): """ 测试多次提交(模拟连续答题) """ print("\n=== 测试多次提交 ===") test_cases = [ { "userId": 1, "goalId": 3, "contentId": 1, "userAnswer": "选项A", "answerDuration": 25 }, { "userId": 1, "goalId": 3, "contentId": 2, "userAnswer": "选项B", "answerDuration": 35 }, { "userId": 1, "goalId": 3, "contentId": 3, "userAnswer": "选项C", "answerDuration": 40 } ] success_count = 0 for i, test_data in enumerate(test_cases, 1): print(f"\n--- 测试用例 {i} ---") print(f"题目ID: {test_data['contentId']}, 答案: {test_data['userAnswer']}") try: response = requests.post( SUBMIT_URL, json=test_data, headers={'Content-Type': 'application/json'}, timeout=10 ) if response.status_code == 200: response_json = response.json() if response_json.get('code') == 200: print(f"✅ 测试用例 {i} 成功") success_count += 1 else: print(f"❌ 测试用例 {i} 失败: {response_json.get('message')}") else: print(f"❌ 测试用例 {i} HTTP错误: {response.status_code}") except Exception as e: print(f"❌ 测试用例 {i} 异常: {str(e)}") # 间隔1秒 time.sleep(1) print(f"\n总结: {success_count}/{len(test_cases)} 个测试用例成功") return success_count == len(test_cases) if __name__ == "__main__": print("开始测试答题提交功能...\n") # 测试单次提交 single_success = test_submit_answer() # 如果单次提交成功,继续测试多次提交 if single_success: multiple_success = test_multiple_submissions() if multiple_success: print("\n🎉 所有测试通过!提交按钮功能正常") else: print("\n⚠️ 部分测试失败,请检查服务器日志") else: print("\n❌ 基础提交测试失败,请检查服务器状态") print("\n测试完成。")