Files
syops/backend/tests/test_chat_turn_runtime.py
T
hugoandCursor 39fe3c05f2 feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 10:46:06 +08:00

225 lines
7.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/tests/test_chat_turn_runtime.py
覆盖 Chat Turn Runtime 平台层:SSE 生命周期、action 路由、ChatLog 落库与权限校验。
"""
from __future__ import annotations
import json
import pytest
from app import db
from app.models import Agent, ChatLog, User
def _parse_sse_events(raw: str) -> list[dict]:
events: list[dict] = []
for frame in raw.split("\n\n"):
for line in frame.split("\n"):
if not line.startswith("data: "):
continue
payload = line[6:].strip()
if payload:
events.append(json.loads(payload))
return events
def _create_shipping_agent() -> Agent:
agent = Agent(
name="货代发货通知 Agent",
description="test",
dify_api_key="test-key",
api_base_url="http://example.com",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
)
db.session.add(agent)
db.session.commit()
return agent
def _create_user() -> User:
user = User(username="chat_turn_user", email="chat_turn_user@example.com", role="admin", status="active")
user.set_password("password")
db.session.add(user)
db.session.commit()
return user
def _create_task_for_user(user_id: int) -> str:
"""创建无 batch 绑定的最小 ShippingNotice(co8 后 shipping_batches 已 DROP)。"""
from app.models import ShippingNotice
task = ShippingNotice(
task_no="SN-20260706-ABCD1234",
user_id=user_id,
source_type="manual",
)
db.session.add(task)
db.session.commit()
return task.task_no
def test_chat_turn_rejects_legacy_fulfillment_action(app, client):
user = _create_user()
agent = _create_shipping_agent()
task_no = _create_task_for_user(user.id)
res = client.post(
"/api/chat/turns/stream",
headers={
"X-Username": user.username,
"X-Role": user.role,
"Content-Type": "application/json",
},
json={
"agent_id": agent.id,
"input": {
"type": "action",
"display_text": "确认",
"action_type": "shipping.match_inventory",
"payload": {"task_no": task_no, "decision": "confirm"},
},
},
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
event_names = [item.get("event") for item in events]
assert "run.started" in event_names
assert "run.failed" in event_names
assert "run.completed" not in event_names
def test_chat_turn_unknown_action_returns_failed(app, client):
user = _create_user()
agent = _create_shipping_agent()
res = client.post(
"/api/chat/turns/stream",
headers={"X-Username": user.username, "X-Role": user.role, "Content-Type": "application/json"},
json={
"agent_id": agent.id,
"input": {
"type": "action",
"display_text": "未知动作",
"action_type": "shipping.not_exists",
"payload": {},
},
},
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
assert any(item.get("event") == "run.failed" for item in events)
def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
user = _create_user()
agent = Agent(name="通用入口", description="test", dify_api_key="k", api_base_url="http://example.com")
db.session.add(agent)
db.session.commit()
res = client.post(
"/api/chat/turns/stream",
headers={"X-Username": user.username, "X-Role": user.role, "Content-Type": "application/json"},
json={
"agent_id": agent.id,
"input": {
"type": "action",
"display_text": "确认",
"action_type": "shipping.match_inventory",
"payload": {"task_no": "SN-20260706-ABCD1234", "decision": "confirm"},
},
},
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
assert any(item.get("event") == "run.failed" for item in events)
def test_chat_turn_multipart_upload_rejects_removed_batch_action(app, client, tmp_path):
"""
multipart 上传时 agent_id 应从 form 字段解析;旧建批 action 不再注册。
关键断言:form 带 agent_id 时 run 能启动;旧 action 作为未知 action 失败。
"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
res = client.post(
"/api/chat/turns/stream",
headers={"X-Username": user.username, "X-Role": user.role},
data={
"agent_id": str(agent.id),
"input": json.dumps(
{
"type": "upload_followup",
"display_text": "上传发货通知:notice.txt",
"action_type": "shipping.create_batch_from_notices",
"payload": {},
},
ensure_ascii=False,
),
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"),
},
content_type="multipart/form-data",
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
event_names = [item.get("event") for item in events]
assert "run.started" in event_names
assert "run.failed" in event_names
assert "run.completed" not in event_names
failed = next(item for item in events if item.get("event") == "run.failed")
assert failed.get("code") == "RESOURCE.NOT_FOUND"
def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, client, monkeypatch):
"""任务级库存附件必须进入 formal upload handler,而不是临时对话库存会话。"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
task_no = _create_task_for_user(user.id)
captured: dict[str, object] = {}
def fake_upload_inventory(received_task_no, upload):
captured['task_no'] = received_task_no
captured['filename'] = upload.filename
captured['content'] = upload.read()
return {
'status': 'ok', 'message': '库存文件已按发布方案解析。',
'data': {'schema_preview': {'headers': ['Supplier Sku']}, 'inventory_file_no': 'SIF-TURN-001'},
}
monkeypatch.setattr(
'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_onhand_file',
fake_upload_inventory,
)
res = client.post(
'/api/chat/turns/stream',
headers={'X-Username': user.username, 'X-Role': user.role},
data={
'agent_id': str(agent.id),
'input': json.dumps({
'type': 'upload_followup', 'display_text': '上传库存文件:task.xls',
'action_type': 'shipping.upload_inventory', 'payload': {'task_no': task_no},
}, ensure_ascii=False),
'files': (BytesIO(b'legacy-inventory'), 'task.xls'),
},
content_type='multipart/form-data',
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
assert 'run.failed' not in [item.get('event') for item in events]
assert captured == {'task_no': task_no, 'filename': 'task.xls', 'content': b'legacy-inventory'}
assistant_payloads = [item.get('data', {}).get('payload', {}) for item in events if item.get('event') == 'message.completed']
assert all('schema_preview' not in payload for payload in assistant_payloads)