""" backend/tests/test_training_api.py 用途:覆盖新人培训主链的后端接口闭环,包括个人进度读写、管理端权限、统计筛选与导出。 依赖:pytest、Flask test client、TrainingRecord/User 模型、openpyxl。 逻辑:验证“员工个人培训记录”与“HR 管理统计导出”共用同一事实源,确保培训主链在后端可落库、可筛选、可导出。 """ from __future__ import annotations from datetime import date, datetime from io import BytesIO from pathlib import Path from openpyxl import load_workbook import pytest from app import db from app.core.errors import ValidationError from app.models import Agent, TrainingRecord, User from app.services import training_service from app.services.training_service import _grade_answer_details, _normalize_question_bank from app.api.chat import preview_support def _create_user( *, username: str, role: str = "user", department: str = "生产一部", feature_permissions: dict | None = None, ) -> User: """创建训练测试用户,供 legacy header 认证读取。""" user = User( username=username, email=f"{username}@example.com", role=role, status="active", real_name=f"{username}-实名", employee_id=f"{username.upper()}-EMP", department=department, ) user.set_feature_permissions(feature_permissions) user.set_password("password123") db.session.add(user) db.session.commit() db.session.refresh(user) db.session.expunge(user) return user def _create_training_agent(*, name: str = "training_agent") -> Agent: """创建带正式题库配置的培训 Agent,供服务端判卷测试使用。""" agent = Agent( name=name, description="training agent", type="api", agent_code="training", runtime_provider="dify", conversation_mode="chat", dify_app_type="chatflow", handler_config={"content_profile": "training"}, extra_config={ "training_workspace_enabled": True, "training_config": { "pass_score": 90, "question_bank": [ { "id": "q1", "type": "single", "prompt": "题目1", "answer": "A", "options": [ {"id": "A", "label": "A. 正确答案"}, {"id": "B", "label": "B. 干扰项"}, ], }, { "id": "q2", "type": "single", "prompt": "题目2", "answer": "B", "options": [ {"id": "A", "label": "A. 干扰项"}, {"id": "B", "label": "B. 正确答案"}, ], }, { "id": "q3", "type": "single", "prompt": "题目3", "answer": "C", "options": [ {"id": "A", "label": "A. 干扰项"}, {"id": "B", "label": "B. 干扰项"}, {"id": "C", "label": "C. 正确答案"}, ], }, ], }, }, is_active=True, ) db.session.add(agent) db.session.commit() db.session.refresh(agent) db.session.expunge(agent) return agent def _json_error(response) -> dict: """提取统一错误 envelope,便于断言错误码与详情。""" body = response.get_json() assert isinstance(body, dict) assert body.get("success") is False assert isinstance(body.get("error"), dict) return body["error"] def _auth_headers(user: User) -> dict[str, str]: """生成训练接口测试鉴权头,优先显式携带 user_id 以稳定命中 legacy 用户解析。""" return { "X-User-Id": str(user.id), "X-Username": user.username, "Content-Type": "application/json", } def test_normalize_question_bank_accepts_judgment_and_qa_aliases(): """关键断言:题库历史类型别名必须映射为员工端可渲染、服务端可判卷的标准题型。""" question_bank = _normalize_question_bank([ {"id": "q1", "type": "judgment", "prompt": "安全帽必须正确佩戴。", "answer": "true"}, {"id": "q2", "type": "问答题", "prompt": "请说明发现隐患后的处理流程。", "answer": ""}, ]) assert [item["type"] for item in question_bank] == ["boolean", "essay"] def test_training_text_questions_apply_standard_answer_and_unanswered_scoring_rules(): """关键断言:文本题标准答案忽略空白与大小写;无答案题按非空 80%、超过 20 字 100% 判分。""" question_bank = _normalize_question_bank([ {"id": "q1", "type": "fill", "prompt": "填写系统名称", "answer": "OA 系统"}, {"id": "q2", "type": "essay", "prompt": "说明安全要求", "answer": "", "score_ratio": 2}, {"id": "q3", "type": "fill", "prompt": "填写电话", "answer": "", "score_ratio": 1}, ]) details, score, passed = _grade_answer_details([ {"question_id": "q1", "answer_text": " oa系统 "}, {"question_id": "q2", "answer_text": "发现安全隐患后应立即停止作业并报告负责人,确认整改完成后再恢复作业。"}, {"question_id": "q3", "answer_text": "119"}, ], question_bank, 90) assert [item["score_ratio"] for item in details] == [1.0, 1.0, 0.8] assert score == 95 assert passed is True def test_training_user_progress_round_trip_and_completion(client, app): """员工侧培训进度应支持空记录读取、过程保存、结果结算与再次读取回显。""" with app.app_context(): user = _create_user(username="trainee_roundtrip") agent = _create_training_agent(name="roundtrip_agent") headers = _auth_headers(user) empty_res = client.get("/api/user/training-record", headers=headers) assert empty_res.status_code == 200 assert empty_res.get_json() is None process_payload = { "agent_id": agent.id, "stage": "exam", "current_question_index": 3, "score": 15, "passed": False, "attempt_count": 1, "join_date": "2026-07-04", "answer_details": [ {"question_id": "q1", "selected_option_id": "A", "correct": True}, {"question_id": "q2", "selected_option_id": "B", "correct": False}, {"question_id": "q3", "selected_option_id": "A", "correct": True}, ], } save_process_res = client.put("/api/user/training-record/progress", headers=headers, json=process_payload) assert save_process_res.status_code == 200 process_body = save_process_res.get_json() assert process_body["stage"] == "exam" assert process_body["training_type"] == "onboarding" assert process_body["training_version"] == "onboarding-v1" assert process_body["exam_mode"] == "unified" assert process_body["current_question_index"] == 3 assert process_body["score"] == 67 assert process_body["passed"] is False assert process_body["status"] == "in_progress" assert process_body["employee_id"] == user.employee_id assert process_body["name"] == user.real_name assert len(process_body["answer_details"]) == 3 read_back_res = client.get("/api/user/training-record", headers=headers) assert read_back_res.status_code == 200 assert read_back_res.get_json()["current_question_index"] == 3 result_payload = { "agent_id": agent.id, "stage": "result", "current_question_index": 20, "score": 95, "passed": False, "attempt_count": 2, "join_date": "2026-07-04", "answer_details": [ {"question_id": "q1", "selected_option_id": "A", "correct": False}, {"question_id": "q2", "selected_option_id": "B", "correct": False}, {"question_id": "q3", "selected_option_id": "C", "correct": False}, ], } save_result_res = client.put("/api/user/training-record/progress", headers=headers, json=result_payload) assert save_result_res.status_code == 200 result_body = save_result_res.get_json() assert result_body["stage"] == "result" assert result_body["score"] == 100 assert result_body["passed"] is True assert result_body["status"] == "passed" assert isinstance(result_body["completion_time"], str) and result_body["completion_time"] with app.app_context(): record = db.session.query(TrainingRecord).filter_by(user_id=user.id).one() assert record.stage == "result" assert record.training_type == "onboarding" assert record.training_version == "onboarding-v1" assert record.exam_mode == "unified" assert record.score == 100 assert record.passed is True assert record.attempt_count == 2 assert record.join_date == date(2026, 7, 4) assert record.completion_time is not None def test_safety_training_progress_round_trip(client, app): """安全培训应持久化培训版本、考试模式、三级状态和级别进度。""" with app.app_context(): user = _create_user(username="safety_roundtrip") agent = _create_training_agent(name="safety_agent") headers = _auth_headers(user) progress_payload = { "agent_id": agent.id, "type": "safety", "training_version": "safety-v1", "exam_mode": "unified", "safety_stage": "team", "safety_progress": { "company": "completed", "department": "completed", "team": "active", }, "stage": "summary", "current_question_index": 0, "score": 0, "passed": False, "attempt_count": 0, "join_date": "2026-08-06", "answer_details": [], } save_res = client.put("/api/user/training-record/progress", headers=headers, json=progress_payload) assert save_res.status_code == 200 save_body = save_res.get_json() assert save_body["training_type"] == "safety" assert save_body["training_version"] == "safety-v1" assert save_body["exam_mode"] == "unified" assert save_body["safety_stage"] == "team" assert save_body["safety_progress"] == { "company": "completed", "department": "completed", "team": "active", } read_res = client.get("/api/user/training-record?type=safety", headers=headers) assert read_res.status_code == 200 read_body = read_res.get_json() assert read_body["training_type"] == "safety" assert read_body["safety_stage"] == "team" assert read_body["safety_progress"]["department"] == "completed" with app.app_context(): record = db.session.query(TrainingRecord).filter_by(user_id=user.id, training_type="safety").one() assert record.training_version == "safety-v1" assert record.exam_mode == "unified" assert record.safety_stage == "team" assert record.safety_progress == { "company": "completed", "department": "completed", "team": "active", } def test_safety_exam_requires_all_configured_learning_resources(monkeypatch): """断言安全培训缺少任一级资料完成记录时,后端拒绝直接进入考试或结算。""" monkeypatch.setattr( training_service, "get_published_config", lambda _training_type: { "resources": [ {"id": 11, "resource_type": "agent_guide", "training_level": "company"}, {"id": 12, "resource_type": "kb_document_version", "training_level": "department"}, {"id": 13, "resource_type": "kb_document_version", "training_level": "team"}, ], }, ) progress = {"resource_progress": {"11": {"completed": True}, "12": {"completed": False}}} # 关键断言:客户端伪造 exam 阶段不能跳过班组级学习资料。 with pytest.raises(ValidationError): training_service._assert_safety_exam_prerequisites("exam", progress, "safety") def test_safety_exam_accepts_all_configured_learning_resources(monkeypatch): """断言三级配置资料均完成时,后端允许安全培训进入考试阶段。""" monkeypatch.setattr( training_service, "get_published_config", lambda _training_type: { "resources": [ {"id": 11, "resource_type": "agent_guide", "training_level": "company"}, {"id": 12, "resource_type": "kb_document_version", "training_level": "department"}, {"id": 13, "resource_type": "kb_document_version", "training_level": "team"}, ], }, ) progress = {"resource_progress": {str(resource_id): {"completed": True} for resource_id in (11, 12, 13)}} # 关键断言:所有已配置资料完成后,不阻断正常开考。 training_service._assert_safety_exam_prerequisites("exam", progress, "safety") def test_training_result_is_graded_by_server_question_bank(client, app): """服务端应基于 Agent 题库重算分数与通过状态,不能信任前端伪造结果。""" with app.app_context(): user = _create_user(username="graded_by_server") agent = _create_training_agent(name="grading_agent") headers = _auth_headers(user) tampered_payload = { "agent_id": agent.id, "stage": "result", "current_question_index": 3, "score": 100, "passed": True, "attempt_count": 1, "join_date": "2026-08-06", "answer_details": [ {"question_id": "q1", "selected_option_id": "A", "correct": True}, {"question_id": "q2", "selected_option_id": "A", "correct": True}, {"question_id": "q3", "selected_option_id": "A", "correct": True}, ], } save_res = client.put("/api/user/training-record/progress", headers=headers, json=tampered_payload) assert save_res.status_code == 200 body = save_res.get_json() assert body["score"] == 33 assert body["passed"] is False assert body["status"] == "failed" assert body["answer_details"] == [ {"question_id": "q1", "selected_option_id": "A", "correct": True}, {"question_id": "q2", "selected_option_id": "A", "correct": False}, {"question_id": "q3", "selected_option_id": "A", "correct": False}, ] def test_training_user_progress_requires_auth_and_valid_payload(client, app): """培训个人接口必须拒绝未登录请求,并对非法参数返回统一校验错误。""" unauth_res = client.get("/api/user/training-record") assert unauth_res.status_code == 401 assert _json_error(unauth_res)["code"] == "AUTH.UNAUTHORIZED" with app.app_context(): user = _create_user(username="trainee_validation") headers = _auth_headers(user) invalid_stage_res = client.put( "/api/user/training-record/progress", headers=headers, json={ "stage": "invalid-stage", "current_question_index": 0, "score": 0, "attempt_count": 0, "answer_details": [], }, ) assert invalid_stage_res.status_code == 400 invalid_stage_error = _json_error(invalid_stage_res) assert invalid_stage_error["code"] == "VALIDATION.INVALID_PARAM" assert invalid_stage_error["details"]["field"] == "stage" invalid_answer_res = client.put( "/api/user/training-record/progress", headers=headers, json={ "stage": "exam", "current_question_index": 1, "score": 5, "attempt_count": 1, "answer_details": ["not-object"], }, ) assert invalid_answer_res.status_code == 400 invalid_answer_error = _json_error(invalid_answer_res) assert invalid_answer_error["code"] == "VALIDATION.INVALID_PARAM" assert invalid_answer_error["details"]["field"] == "answer_details" assert invalid_answer_error["details"]["index"] == 0 def test_training_admin_list_stats_and_export_share_one_fact_source(client, app): """HR 管理列表、统计与导出应共用同一批 TrainingRecord,并支持部门/状态筛选。""" with app.app_context(): hr_user = _create_user(username="training_hr", role="hr", department="人事部") ordinary_user = _create_user(username="training_user_denied", role="user", department="生产一部") passed_user = _create_user(username="passed_learner", department="生产一部") failed_user = _create_user(username="failed_learner", department="生产一部") progress_user = _create_user(username="progress_learner", department="品质部") db.session.add_all( [ TrainingRecord( user_id=passed_user.id, employee_id=passed_user.employee_id, name=passed_user.real_name, department=passed_user.department, join_date=date(2026, 7, 1), stage="result", current_question_index=20, score=95, passed=True, attempt_count=1, answer_details=[], started_at=datetime(2026, 7, 1, 9, 0, 0), completion_time=datetime(2026, 7, 1, 10, 0, 0), ), TrainingRecord( user_id=failed_user.id, employee_id=failed_user.employee_id, name=failed_user.real_name, department=failed_user.department, join_date=date(2026, 7, 2), stage="result", current_question_index=20, score=60, passed=False, attempt_count=2, answer_details=[], started_at=datetime(2026, 7, 2, 9, 0, 0), completion_time=datetime(2026, 7, 2, 10, 0, 0), ), TrainingRecord( user_id=progress_user.id, employee_id=progress_user.employee_id, name=progress_user.real_name, department=progress_user.department, join_date=date(2026, 7, 3), stage="exam", current_question_index=6, score=25, passed=False, attempt_count=1, answer_details=[], started_at=datetime(2026, 7, 3, 9, 0, 0), completion_time=None, ), ] ) db.session.commit() denied_headers = _auth_headers(ordinary_user) denied_res = client.get("/api/admin/training-records", headers=denied_headers) assert denied_res.status_code == 403 assert _json_error(denied_res)["code"] == "AUTH.FORBIDDEN" hr_headers = _auth_headers(hr_user) list_res = client.get( "/api/admin/training-records?department=生产一部&status=passed&page=1&page_size=10", headers=hr_headers, ) assert list_res.status_code == 200 list_body = list_res.get_json() assert list_body["total"] == 1 assert list_body["page"] == 1 assert list_body["page_size"] == 10 assert list_body["pages"] == 1 assert set(list_body["department_options"]) == {"生产一部", "品质部"} assert len(list_body["items"]) == 1 assert list_body["items"][0]["employee_id"] == passed_user.employee_id assert list_body["items"][0]["status"] == "passed" stats_res = client.get("/api/admin/training-records/stats", headers=hr_headers) assert stats_res.status_code == 200 stats_body = stats_res.get_json() assert stats_body == { "total": 3, "passed": 1, "failed": 1, "in_progress": 1, "pass_rate": 33, "average_score": 60, } export_res = client.get("/api/admin/training-records/export?department=生产一部", headers=hr_headers) assert export_res.status_code == 200 assert export_res.headers["Content-Type"].startswith( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) assert "training_records_" in export_res.headers["Content-Disposition"] workbook = load_workbook(BytesIO(export_res.data)) sheet = workbook.active rows = list(sheet.iter_rows(values_only=True)) assert rows[0] == ("入职日期", "完成日期", "部门", "姓名", "工号", "分数", "考试次数", "状态") assert len(rows) == 3 assert rows[1][2] == "生产一部" assert rows[2][2] == "生产一部" assert {rows[1][7], rows[2][7]} == {"passed", "failed"} def test_training_preview_proxy_reads_kb_storage_without_http_callback(monkeypatch, tmp_path, app): """ 培训资料预览必须直接复用知识库存储解析,不能回调前端 Nginx。 关键断言:匹配培训资料路径时,预览代理返回原始 PDF 内容,且不会调用 requests.get, 防止测试环境容器经宿主机端口回环时再次出现 502。 """ preview_file = tmp_path / "safety-training.pdf" preview_file.write_bytes(b"%PDF-training-preview") requested_version_ids: list[int] = [] def resolve_preview_path(version_id: int): requested_version_ids.append(version_id) return Path(preview_file), preview_file.name def reject_http_callback(*_args, **_kwargs): raise AssertionError("training preview must not call requests.get") monkeypatch.setattr( preview_support.document_service, "resolve_training_preview_file_path", resolve_preview_path, ) monkeypatch.setattr(preview_support.requests, "get", reject_http_callback) with app.app_context(): content, content_type, error = preview_support._fetch_preview_source_bytes( "/api/kb/document-versions/1231/training-preview-file", ) assert requested_version_ids == [1231] assert content == b"%PDF-training-preview" assert content_type == "application/pdf" assert error is None def test_non_training_preview_url_keeps_existing_http_fetch_path(monkeypatch): """ 非培训来源必须继续走原有通用预览取流逻辑。 关键断言:普通内网 URL 不会触发知识库培训文件解析,避免影响既有 Chat 来源文件预览。 """ class FakeResponse: status_code = 200 content = b"%PDF-chat-source" headers = {"content-type": "application/pdf"} def reject_training_resolver(_version_id: int): raise AssertionError("non-training URL must not resolve training preview") monkeypatch.setattr( preview_support.document_service, "resolve_training_preview_file_path", reject_training_resolver, ) monkeypatch.setattr(preview_support.requests, "get", lambda *_args, **_kwargs: FakeResponse()) content, content_type, error = preview_support._fetch_preview_source_bytes( "http://192.168.100.192:9000/chat-source.pdf", ) assert content == b"%PDF-chat-source" assert content_type == "application/pdf" assert error is None def test_training_admin_permission_can_be_granted_by_feature_permission(client, app): """培训 HR 管理能力应支持通过功能权限显式授予普通用户。""" with app.app_context(): granted_user = _create_user( username="training_perm_user", role="user", department="生产一部", feature_permissions={"training_hr_manage": True}, ) db.session.add( TrainingRecord( user_id=granted_user.id, employee_id=granted_user.employee_id, name=granted_user.real_name, department=granted_user.department, join_date=date(2026, 7, 5), stage="result", current_question_index=20, score=90, passed=True, attempt_count=1, answer_details=[], started_at=datetime(2026, 7, 5, 9, 0, 0), completion_time=datetime(2026, 7, 5, 10, 0, 0), ) ) db.session.commit() res = client.get("/api/admin/training-records", headers=_auth_headers(granted_user)) assert res.status_code == 200 body = res.get_json() assert body["total"] == 1 assert body["items"][0]["employee_id"] == granted_user.employee_id