feat(feedback): 提交接口支持携带图片资产并校验引用

This commit is contained in:
HTEWJ\26070045 committed 2026-10-26 17:15:31 +08:00
1 parent b31e887b2a
commit 29315cab20
6 files changed
+244 -3

No files matched your search

@@ -0,0 +1,186 @@
"""通用意见反馈提交 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