"""通用意见反馈提交 API 契约测试(POST /api/user/feedback 携带图片资产)。 用途:锁定反馈提交接口外部契约——image_asset_nos 按顺序落 general_feedback_images 并把 FileAsset 置为 referenced(reference_count+1、expires_at 清空), 他人资产/非图片/已被引用/超 5 张等非法输入整单拒绝且不落任何行 (FILE_ASSET.* 与 FEEDBACK.IMAGE_* 错误码),纯文本提交保持旧契约。 依赖:app/client 夹具(create_app('testing') + create_all)、issue_local_access_token、 parse_api_error(错误 envelope 断言);前置数据直接落 User/FileAsset 行。 逻辑:校验逻辑由 handlers.submit_general_feedback 承载,本文件只测 API 壳 (鉴权/状态码/错误码/落库副作用/回归路径)。 """ from __future__ import annotations from uuid import uuid4 import pytest from app import db from app.core.auth.jwt import issue_local_access_token from app.models import FileAsset, GeneralFeedback, GeneralFeedbackImage, User from tests.conftest import parse_api_error @pytest.fixture(autouse=True) def _disable_wecom_feedback_notify(app): """测试绝不触发真实企微群通知(2026-10-26 曾因未隔离 webhook 向真实群发出消息)。""" app.config["WECOM_FEEDBACK_NOTIFY_ENABLED"] = False def _headers(user: User) -> dict: """为指定用户签发 Bearer JWT 请求头(须在 app context 内调用)。""" token = issue_local_access_token(user) return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} def _create_user(username: str, role: str = "user") -> User: """按用户名幂等落一个测试用户。""" user = db.session.query(User).filter_by(username=username).first() if not user: user = User(username=username, email=f"{username}@example.com", role=role, status="active") user.set_password("x") db.session.add(user) db.session.commit() return user @pytest.fixture def user_headers(app): """普通用户 JWT 请求头。""" with app.app_context(): return _headers(_create_user("fbuser")) @pytest.fixture def admin_headers(app): """平台管理员 JWT 请求头。""" with app.app_context(): return _headers(_create_user("fbadmin", role="admin")) def _make_asset(user_id: int, ext: str = "png", mime: str = "image/png", *, reference_count: int = 0, lifecycle: str = "temporary") -> FileAsset: """直接落一条 ready/temporary 的 FileAsset 行(不经过 MinIO)。""" asset = FileAsset( asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id), original_filename=f"screenshot.{ext}", storage_provider="minio", storage_bucket="test", storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024, mime_type=mime, extension=ext, upload_status="ready", lifecycle_status=lifecycle, reference_count=reference_count, ) db.session.add(asset) db.session.commit() return asset def _submit_payload(**overrides) -> dict: """合法反馈提交载荷基线(纯文本,不带图片)。""" payload = { "feedback_type": "问题反馈", "feedback_module": "知识库", "content": "测试反馈内容", "source_page": "workspace", } payload.update(overrides) return payload def test_submit_with_images_claims_assets(app, client, user_headers): """带图提交:两图按顺序落库,资产被引用(reference_count=1、referenced、expires_at 清空)。""" with app.app_context(): u = db.session.query(User).filter_by(username="fbuser").first() a1 = _make_asset(u.id) a2 = _make_asset(u.id, ext="jpg", mime="image/jpeg") # asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读 asset_nos = [a1.asset_no, a2.asset_no] resp = client.post("/api/user/feedback", headers=user_headers, json={ "feedback_type": "问题反馈", "feedback_module": "知识库", "content": "带上截图", "source_page": "workspace", "image_asset_nos": asset_nos, }) assert resp.status_code == 200 with app.app_context(): imgs = GeneralFeedbackImage.query.order_by(GeneralFeedbackImage.sort_order).all() assert [i.sort_order for i in imgs] == [0, 1] for i in imgs: asset = db.session.get(FileAsset, i.asset_id) assert asset.reference_count == 1 assert asset.lifecycle_status == "referenced" assert asset.expires_at is None def test_submit_rejects_foreign_asset(app, client, user_headers): """他人资产 → 403 FILE_ASSET.FORBIDDEN,反馈不落库。""" with app.app_context(): other = _create_user("fbother") foreign = _make_asset(other.id) # asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读 foreign_no = foreign.asset_no resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload( content="挂别人资产", image_asset_nos=[foreign_no], )) assert resp.status_code == 403 assert parse_api_error(resp.get_json())["code"] == "FILE_ASSET.FORBIDDEN" with app.app_context(): # 拒绝路径不落任何行:反馈与图片关联均为零 assert GeneralFeedbackImage.query.count() == 0 assert GeneralFeedback.query.count() == 0 def test_submit_rejects_non_image(app, client, user_headers): """ext='pdf' 的资产 → 400 FEEDBACK.IMAGE_INVALID。""" with app.app_context(): u = db.session.query(User).filter_by(username="fbuser").first() pdf_asset = _make_asset(u.id, ext="pdf", mime="application/pdf") # asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读 pdf_no = pdf_asset.asset_no resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload( content="挂非图片", image_asset_nos=[pdf_no], )) assert resp.status_code == 400 assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_INVALID" with app.app_context(): # 拒绝路径不落任何行 assert GeneralFeedbackImage.query.count() == 0 assert GeneralFeedback.query.count() == 0 def test_submit_rejects_referenced_asset(app, client, user_headers): """reference_count=1 的图片资产 → 400 FEEDBACK.IMAGE_INVALID(防挂已被业务引用资产)。""" with app.app_context(): u = db.session.query(User).filter_by(username="fbuser").first() used = _make_asset(u.id, reference_count=1) # asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读 used_no = used.asset_no resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload( content="挂已引用资产", image_asset_nos=[used_no], )) assert resp.status_code == 400 assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_INVALID" with app.app_context(): # 拒绝路径不落任何行 assert GeneralFeedbackImage.query.count() == 0 assert GeneralFeedback.query.count() == 0 def test_submit_rejects_too_many(app, client, user_headers): """6 个 asset_no → 400 FEEDBACK.IMAGE_TOO_MANY,反馈不落库。""" asset_nos = [f"FA-TEST-{i:04d}" for i in range(6)] resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload( content="一次挂六张", image_asset_nos=asset_nos, )) assert resp.status_code == 400 assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_TOO_MANY" with app.app_context(): # 拒绝路径不落任何行 assert GeneralFeedbackImage.query.count() == 0 assert GeneralFeedback.query.count() == 0 def test_submit_text_only_keeps_legacy(app, client, user_headers): """不带 image_asset_nos:200,general_feedback_images 零行(回归)。""" resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload()) assert resp.status_code == 200 body = resp.get_json() assert body.get("status") == "ok" assert isinstance(body.get("id"), int) with app.app_context(): assert GeneralFeedbackImage.query.count() == 0 assert GeneralFeedback.query.count() == 1 def test_report_rows_include_images(app, client, user_headers, admin_headers): """报表行含 images 元数据;无图行 images==[]。""" with app.app_context(): u = db.session.query(User).filter_by(username="fbuser").first() a1 = _make_asset(u.id) # asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读 asset_no = a1.asset_no resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload( content="带图反馈", image_asset_nos=[asset_no], )) assert resp.status_code == 200 with_image_id = resp.get_json()["id"] resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(content="纯文本反馈")) assert resp.status_code == 200 text_only_id = resp.get_json()["id"] resp = client.get("/api/admin/reports/general-feedbacks", headers=admin_headers) assert resp.status_code == 200 rows = resp.get_json() rows_by_id = {row["id"]: row for row in rows} # 有图行:images[0] 键集合恰为 5 个元数据键,asset_no 与提交资产一致 with_image_row = rows_by_id[with_image_id] assert len(with_image_row["images"]) == 1 assert set(with_image_row["images"][0].keys()) == { "image_id", "asset_no", "original_filename", "file_size", "sort_order", } assert with_image_row["images"][0]["asset_no"] == asset_no # 无图行:images 置空列表而非缺键 assert rows_by_id[text_only_id]["images"] == [] def test_admin_image_raw_streams(app, client, user_headers, admin_headers, monkeypatch): """管理员经 raw 接口取到图片字节(Content-Type 按扩展名固定 + nosniff);错配 feedback_id → 404 FEEDBACK.IMAGE_NOT_FOUND;非管理员 → 403。""" # 隔离 MinIO:读取字节走本地假实现,提交仍只落库不触对象存储 monkeypatch.setattr( "app.services.file_assets.service.file_asset_storage.get_bytes", lambda key: b"\x89PNG\r\n\x1a\nfake", ) with app.app_context(): u = db.session.query(User).filter_by(username="fbuser").first() a1 = _make_asset(u.id) asset_no = a1.asset_no resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload( content="取图反馈", image_asset_nos=[asset_no], )) assert resp.status_code == 200 fb_id = resp.get_json()["id"] with app.app_context(): img = GeneralFeedbackImage.query.filter_by(feedback_id=fb_id).first() image_id = img.id resp = client.get(f"/api/admin/reports/general-feedbacks/{fb_id}/images/{image_id}/raw", headers=admin_headers) assert resp.status_code == 200 assert resp.data == b"\x89PNG\r\n\x1a\nfake" assert resp.content_type.startswith("image/png") # 安全响应头:Content-Type 按扩展名白名单固定后,仍禁用浏览器 MIME 嗅探(防伪造内容内联渲染) assert resp.headers.get("X-Content-Type-Options") == "nosniff" # 错配 feedback_id:image 不属于该反馈 → FEEDBACK.IMAGE_NOT_FOUND(而非 FILE_ASSET.*) resp = client.get( f"/api/admin/reports/general-feedbacks/{fb_id + 99999}/images/{image_id}/raw", headers=admin_headers, ) assert resp.status_code == 404 assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_NOT_FOUND" # 非管理员访问 raw 接口 → 403 resp = client.get(f"/api/admin/reports/general-feedbacks/{fb_id}/images/{image_id}/raw", headers=user_headers) assert resp.status_code == 403