Files
syops/backend/tests/test_tasks_0304_chat_features.py
T
hugo 1f3ecb87b7 feat(shipping_notice): 新增货代订单全流程业务模块及配套基建
本次提交新增货代订单处理全流程的完整业务能力、数据库迁移与测试用例:
1.  统一追加式审计事件体系,支持全链路不可篡改的业务追溯
2.  货代任务撤销、版本替代管控逻辑,规范已上传订单的合规版本更替
3.  订单抽取路由审计、模板自动冻结资格、路由计数等核心业务基建
4.  EML订单补充表解析契约与合并逻辑,完善订单补全能力
5.  Chatflow只读能力令牌校验机制,保障工具调用安全
6.  人工复核证据校验服务,规范人工审核的证据留存
所有变更均配套完整的单元测试与迁移契约测试,支持受控回退
2026-07-28 08:56:58 +08:00

218 lines
7.5 KiB
Python

import pytest
from datetime import datetime
from app import create_app, db
from app.models import Agent, User, ChatLog
@pytest.fixture
def client():
app = create_app('testing')
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create user and agent
user = User(username='testuser', role='user', email='test@example.com')
db.session.add(user)
agent = Agent(name='Test Agent', type='api')
db.session.add(agent)
user.agents.append(agent)
db.session.flush()
# Add some chat logs
log1 = ChatLog(
user_id=user.id, agent_id=agent.id,
conversation_id='conv1',
query='Hi', answer='Hello',
created_at=datetime(2026, 1, 1)
)
db.session.add(log1)
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def get_headers(client):
return {
'X-User-Id': '1',
'X-Username': 'testuser',
'X-Role': 'user',
'Content-Type': 'application/json'
}
def test_chat_history_with_query_param(client):
"""
Verify that /api/chat/sessions accepts agent_id as query parameter
(This tests the fix in decorators.py)
"""
headers = get_headers(client)
# 1. Test without agent_id (Should fail with 400)
res = client.get('/api/chat/sessions', headers=headers)
assert res.status_code == 400
assert res.get_json()['error']['message'] == 'agent_id is required'
# 2. Test with agent_id in query string (Should succeed)
res = client.get('/api/chat/sessions?agent_id=1', headers=headers)
assert res.status_code == 200
data = res.get_json()
assert len(data) == 1
assert data[0]['conversation_id'] == 'conv1'
# 3. Test with agent_id in JSON body (Should still work if GET allows body, but requests/fetch usually don't)
# Flask test client allows GET with body
res = client.get('/api/chat/sessions', headers=headers, json={'agent_id': 1})
assert res.status_code == 200
assert len(res.get_json()) == 1
def test_chat_messages_history(client):
"""
Verify getting messages for a conversation
"""
headers = get_headers(client)
# Need agent_id now
res = client.get('/api/chat/messages?conversation_id=conv1&agent_id=1', headers=headers)
assert res.status_code == 200
msgs = res.get_json()
assert len(msgs) == 2 # User + Assistant
assert msgs[0]['content'] == 'Hi'
assert msgs[1]['content'] == 'Hello'
def test_chat_messages_restore_user_attachments_without_leaking_into_assistant_payload(client):
"""历史回放应把附件放回用户消息,并从助手 payload 中剥离内部 user_attachments。"""
headers = get_headers(client)
with client.application.app_context():
user = User.query.filter_by(username='testuser').first()
agent = Agent.query.filter_by(name='Test Agent').first()
db.session.add(ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id='conv-attachments',
query='总结附件',
answer='已完成总结',
payload={
'existing_key': 'kept',
'user_attachments': [{
'name': 'purchase-order.pdf',
'size': 144456,
'extension': 'pdf',
'type': 'document',
'source': 'local',
'url': 'https://example.com/secret',
}],
},
))
db.session.commit()
res = client.get('/api/chat/messages?conversation_id=conv-attachments&agent_id=1', headers=headers)
assert res.status_code == 200
messages = res.get_json()
assert messages[0] == {
'role': 'user',
'content': '总结附件',
'attachments': [{
'name': 'purchase-order.pdf',
'size': 144456,
'extension': 'pdf',
'type': 'document',
'source': 'local',
}],
}
assert messages[1]['payload'] == {'existing_key': 'kept'}
def test_chat_messages_do_not_create_empty_assistant_for_attachment_only_payload(client):
"""仅含用户附件 payload 且无回答时,不应额外回放空助手消息。"""
headers = get_headers(client)
with client.application.app_context():
user = User.query.filter_by(username='testuser').first()
agent = Agent.query.filter_by(name='Test Agent').first()
db.session.add(ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id='conv-attachment-only',
query='',
answer='',
payload={'user_attachments': [{
'name': 'notice.eml',
'type': 'document',
'source': 'shipping_notice',
}]},
))
db.session.commit()
res = client.get('/api/chat/messages?conversation_id=conv-attachment-only&agent_id=1', headers=headers)
assert res.status_code == 200
messages = res.get_json()
assert len(messages) == 1
assert messages[0]['role'] == 'user'
assert messages[0]['content'] == ''
assert messages[0]['attachments'][0]['name'] == 'notice.eml'
def test_local_assistant_message_query_does_not_duplicate_user_bubble(client):
"""助手本地消息即使误传 query,历史回放也不能多生成一条用户确认。"""
headers = get_headers(client)
user_res = client.post('/api/chat/messages/local?agent_id=1', headers=headers, json={
'conversation_id': 'conv-local-confirm',
'role': 'user',
'type': 'text',
'content': '确认\n任务编号:SN-001',
'query': '确认',
})
assert user_res.status_code == 200
assistant_res = client.post('/api/chat/messages/local?agent_id=1', headers=headers, json={
'conversation_id': 'conv-local-confirm',
'role': 'assistant',
'type': 'text',
'content': '已确认,进入下一步。',
'query': '确认',
})
assert assistant_res.status_code == 200
res = client.get('/api/chat/messages?conversation_id=conv-local-confirm&agent_id=1', headers=headers)
assert res.status_code == 200
msgs = res.get_json()
user_messages = [item for item in msgs if item['role'] == 'user']
assert len(user_messages) == 1
assert user_messages[0]['content'] == '确认'
assert msgs[-1]['role'] == 'assistant'
assert msgs[-1]['content'] == '已确认,进入下一步。'
def test_chat_sessions_keep_latest_non_empty_query_as_title(client):
headers = get_headers(client)
with client.application.app_context():
user = User.query.filter_by(username='testuser').first()
agent = Agent.query.filter_by(name='Test Agent').first()
db.session.add(ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id='conv1',
query='',
answer='请填写请假表单',
message_type='leave-form',
created_at=datetime(2026, 1, 2),
))
db.session.commit()
res = client.get('/api/chat/sessions?agent_id=1', headers=headers)
assert res.status_code == 200
data = res.get_json()
assert len(data) == 1
assert data[0]['conversation_id'] == 'conv1'
assert data[0]['title'] == 'Hi'