""" 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, AgentGuide, TrainingConfig, TrainingConfigResource, TrainingRecord, User from app.services import lean_training_service, training_config_service, 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_overseas_regulations_video_completion_creates_passed_result(client, app): """关键断言:自定义编码的出国规章培训完整观看视频后无需题库作答,也必须落库为一次完成。""" with app.app_context(): user = _create_user(username="overseas_video_completion") agent = _create_training_agent(name="overseas_video_agent") db.session.add(TrainingConfig( training_type="overseas_policy_v2", name="出国规章培训", version="v1", status="published", )) db.session.commit() response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json={ "agent_id": agent.id, "type": "overseas_policy_v2", "stage": "result", "score": 100, "passed": True, "attempt_count": 0, "answer_details": [], }) assert response.status_code == 200 body = response.get_json() assert body["training_type"] == "overseas_policy_v2" assert body["stage"] == "result" assert body["passed"] is True assert body["status"] == "passed" assert isinstance(body["completion_time"], str) and body["completion_time"] def test_overseas_regulations_video_completion_sends_wecom_notice_each_time(client, app, monkeypatch): """关键断言:每次出国规章视频完成都必须生成一次泰国出差准则企微通知,不能按历史完成记录去重。""" sent_messages = [] monkeypatch.setattr( training_service, "send_wecom_event_message", lambda **kwargs: sent_messages.append(kwargs) or {"ok": True, "trace_id": "training-notice-trace"}, ) with app.app_context(): user = _create_user(username="overseas_wecom_notice") db.session.add(TrainingConfig( training_type="overseas_notice_v1", name="出国规章培训", version="v1", status="published", )) db.session.commit() payload = { "type": "overseas_notice_v1", "stage": "result", "score": 100, "passed": True, "attempt_count": 0, "answer_details": [], } first_response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json=payload) second_response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json=payload) assert first_response.status_code == 200 assert second_response.status_code == 200 assert len(sent_messages) == 2 assert all(message["event_type"] == "training_overseas_thailand_guidelines" for message in sent_messages) assert all(message["title"] == "中国员工出差泰国的行为准则" for message in sent_messages) assert all(message["content"] == "中国员工出差泰国的行为准则" for message in sent_messages) def test_overseas_regulations_wecom_notice_jumps_to_generic_entrance_chat(client, app, monkeypatch): """关键断言:出国规章完成的企微通知必须跳转「通用入口」聊天页(/chat/),不得落入 /workspace 应用管理页。""" sent_messages = [] monkeypatch.setattr( training_service, "send_wecom_event_message", lambda **kwargs: sent_messages.append(kwargs) or {"ok": True, "trace_id": "training-notice-trace"}, ) with app.app_context(): user = _create_user(username="overseas_wecom_jump") entrance_agent = Agent( name="通用入口", type="api", agent_code="generic", runtime_provider="dify", conversation_mode="chat", dify_app_type="chatflow", handler_config={"content_profile": "generic_entrance"}, ) db.session.add(entrance_agent) db.session.add(TrainingConfig( training_type="overseas_jump_v1", name="出国规章培训", version="v1", status="published", )) db.session.commit() entrance_agent_id = entrance_agent.id response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json={ "type": "overseas_jump_v1", "stage": "result", "score": 100, "passed": True, "attempt_count": 0, "answer_details": [], }) assert response.status_code == 200 assert len(sent_messages) == 1 # [ASSERT] 卡片跳转路径必须指向通用入口聊天页,员工点击后进入图二页面而非应用管理工作台 assert sent_messages[0]["jump_path"] == f"/chat/{entrance_agent_id}" 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_update_training_config_preserves_existing_resource_ids(app): """ 保存未替换的安全培训资料时必须保留资源绑定 ID。 用途:防止员工的 resource_progress 因管理端保存配置而失去与三级资料的关联。 """ with app.app_context(): agent = _create_training_agent(name="config_resource_stability_agent") guide = AgentGuide( agent_id=agent.id, file_name="safety.mp4", file_type="video/mp4", file_path="guides/safety.mp4", guide_usage="training_safety_company_video", status=1, ) db.session.add(guide) db.session.flush() config = TrainingConfig( training_type="safety", name="安全培训", version="v1.0", status="published", ) config.resources = [ TrainingConfigResource( resource_type="agent_guide", training_level="company", agent_guide_id=guide.id, title="公司级安全培训", required_duration=10, sort_order=0, ), ] db.session.add_all([guide, config]) db.session.commit() resource_id = config.resources[0].id updated = training_config_service.update_config( config.id, { "training_type": "safety", "name": "安全培训", "version": "v1.0", "status": "published", "pass_score": 90, "settings": {"exam_mode": "unified", "questions": []}, "resources": [ { "id": resource_id, "resource_type": "agent_guide", "training_level": "company", "agent_guide_id": guide.id, "title": "公司级安全培训(已更新)", "required_duration": 15, "sort_order": 0, }, ], }, user_id=None, ) # 关键断言:配置保存不得重建未替换的资料绑定,否则员工已完成进度无法匹配。 assert updated["resources"][0]["id"] == resource_id assert db.session.get(TrainingConfigResource, resource_id).title == "公司级安全培训(已更新)" 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="人事部", feature_permissions={"training_hr_manage": True}, ) 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][3] == "生产一部" assert rows[2][3] == "生产一部" assert {rows[1][8], rows[2][8]} == {"已通过", "未通过"} def test_lean_dashboard_export_uses_page_time_and_status_labels(monkeypatch): """精益看板 Excel 必须复用页面的分钟级时间格式与中文状态文案。""" monkeypatch.setattr( lean_training_service, "list_dashboard", lambda task_id: { "task": {"week_index": 2, "week_key": "2026-09-14", "due_at": "2026-09-20T23:59:59"}, "completed": [{"employee_id": "EMP-001", "name": "张三", "department": "生产部", "videos": [{"name": "精益视频", "watched_at": "2026-09-15T08:30:45"}], "status": "completed", "summary_text": "已完成学习", "completed_at": "2026-09-15T09:00:12"}], "incomplete": [{"employee_id": "EMP-002", "name": "李四", "department": "品质部", "videos": [], "status": "overdue", "summary_text": None, "completed_at": None}], "periods": [], }, ) file_data, _ = lean_training_service.export_dashboard_excel(1) rows = list(load_workbook(BytesIO(file_data)).active.iter_rows(values_only=True)) assert rows[1][2] == "2026-09-20 23:59" assert rows[1][7] == "2026-09-15 08:30" assert rows[1][8] == "已完成" assert rows[1][10] == "2026-09-15 09:00" assert rows[2][8] == "已延期" 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_dynamic_training_type_code_title_cleanup_and_published_type_list(client, app): """自定义类型编码应动态可用,资料标题去除首尾空白,列表仅返回已发布类型。""" with app.app_context(): admin = _create_user(username="training_type_admin", role="admin") draft = training_config_service.create_config( { "training_type": "compliance_training", "name": "合规培训", "version": "v1.0", "status": "draft", "resources": [], }, user_id=admin.id, ) published = training_config_service.create_config( { "training_type": "quality-training", "name": "质量培训", "version": "v1.0", "status": "published", "resources": [ { "resource_type": "inline_questions", "title": " 质量考试 ", "inline_questions": [{"id": "q1"}], }, ], }, user_id=admin.id, ) # 关键断言:类型编码被规范化,标题不保留录入空白。 assert draft["training_type"] == "compliance_training" assert published["training_type"] == "quality_training" assert published["resources"][0]["title"] == "质量考试" headers = _auth_headers(admin) response = client.get("/api/user/training-types", headers=headers) # 关键断言:发布类型列表可供前端动态选择,草稿不得暴露。 assert response.status_code == 200 assert response.get_json() == [{"code": "quality_training", "name": "质量培训"}] """培训 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