Files
syops/backend/tests/test_file_check_tools.py
T
2026-09-28 14:52:28 +08:00

2468 lines
84 KiB
Python

import sys
import types
import pytest
from app import db
from app.models import ChatLog, ChatSession, ScheduleRun, ScheduleTask, User
from app.services.file_check import FileCheckService
@pytest.fixture(autouse=True)
def _file_check_tool_auth_config(app):
"""避免本机 .env 中 FILE_CHECK_TOOL_API_KEY 覆盖测试用 INTEGRATION_API_KEY。"""
with app.app_context():
app.config['FILE_CHECK_TOOL_API_KEY'] = ''
app.config.setdefault('INTEGRATION_API_KEY', 'secret')
yield
@pytest.fixture(autouse=True)
def _clear_file_check_turn_registry():
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
clear_registry_for_tests()
yield
clear_registry_for_tests()
@pytest.fixture(autouse=True)
def _clear_chat_tool_runs(app):
from app.services.file_check_tools.chat_tool_run_binding import clear_chat_tool_runs_for_tests
with app.app_context():
clear_chat_tool_runs_for_tests()
yield
with app.app_context():
clear_chat_tool_runs_for_tests()
@pytest.fixture(autouse=True)
def _stub_minio(monkeypatch):
minio_module = types.ModuleType('minio')
minio_error_module = types.ModuleType('minio.error')
class DummyMinio:
def __init__(self, *args, **kwargs):
pass
def bucket_exists(self, *args, **kwargs):
return True
class DummyS3Error(Exception):
pass
minio_module.Minio = DummyMinio
minio_error_module.S3Error = DummyS3Error
monkeypatch.setitem(sys.modules, 'minio', minio_module)
monkeypatch.setitem(sys.modules, 'minio.error', minio_error_module)
def _mk_admin():
admin = User(username='admin', email='admin-rohs@example.com', role='admin', status='active')
admin.set_password('x')
db.session.add(admin)
return admin
def _mk_check_task(owner_id: int, *, enabled=True):
task = ScheduleTask(
schedule_no='CHK-ROHS-001',
name='RoHS 自动检核',
schedule_type='data_pipeline',
data_source_type='database',
owner_user_id=owner_id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path=None,
enabled=enabled,
)
db.session.add(task)
db.session.commit()
return task
def _mk_other_check_task(owner_id: int):
task = ScheduleTask(
schedule_no='CHK-GENERAL-001',
name='通用检核',
schedule_type='data_pipeline',
data_source_type='database',
owner_user_id=owner_id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path=None,
enabled=True,
)
db.session.add(task)
db.session.commit()
return task
def test_file_check_service_normalizes_failed_workflow():
payload = FileCheckService.normalize_workflow_result({
'status': 'failed',
'error': 'workflow timeout',
'workflow_run_id': 'wf-2',
})
assert payload['dify_result'] == '人工判定'
assert 'Dify执行失败' in payload['dify_message']
assert payload['workflow_run_id'] == 'wf-2'
assert payload['manual_reason_type'] == 'dify_failed'
assert payload['is_system_error'] is True
def test_file_check_service_evaluate_degrades_on_dify_error(monkeypatch):
class _Agent:
id = 1
def _boom(**kwargs):
raise RuntimeError('dify down')
monkeypatch.setattr('app.services.file_check.DifyService.run_workflow_streaming', _boom)
payload = FileCheckService.evaluate(
agent=_Agent(),
run_no='RUN-1',
record='Pb: 100ppm',
)
assert payload['dify_result'] == '人工判定'
assert 'Dify执行失败' in payload['dify_message']
assert payload['error'] == 'dify down'
def test_file_check_service_normalizes_invalid_result():
payload = FileCheckService.normalize_workflow_result({
'status': 'succeeded',
'outputs': {'dify_result': 'OK', 'dify_message': 'bad enum'},
'workflow_run_id': 'wf-1',
})
assert payload['dify_result'] == '人工判定'
assert '返回值异常' in payload['dify_message']
assert payload['workflow_run_id'] == 'wf-1'
def test_file_check_loop_splits_processing_and_judgement_counts(app, monkeypatch):
from app.services.schedule.srm_service import _run_check_job_loop
class _Agent:
id = 1
dify_api_key = 'secret'
def _evaluate(**kwargs):
return {
'dify_result': '人工判定',
'dify_message': 'Dify执行失败:workflow timeout',
'workflow_run_id': 'wf-failed',
'error': 'workflow timeout',
'manual_reason_type': 'dify_failed',
'is_system_error': True,
}
writebacks = []
monkeypatch.setattr('app.services.schedule.srm_service.FileCheckService.evaluate', _evaluate)
with app.app_context():
admin = _mk_admin()
db.session.flush()
task = _mk_check_task(admin.id)
run = ScheduleRun(run_no='RUN-JUDGEMENT-SPLIT', schedule_task_id=task.id, status='running', trigger_type='manual')
db.session.add(run)
db.session.commit()
run_id = run.id
total, success, failed, skipped, details, errors, step_logs = _run_check_job_loop(
conn_str='',
run_no='RUN-1',
agent=_Agent(),
user='tester',
wait_seconds=5,
run_id=run_id,
fetch_fn=lambda _conn: [{'id': 'R1'}],
build_record_fn=lambda _conn, item, row_id: ('record text', None),
writeback_fn=lambda _conn, **kwargs: writebacks.append(kwargs),
row_id_key='id',
log_prefix='row',
)
db.session.refresh(run)
judgement = (run.response_summary_json or {}).get('file_judgement') or {}
assert total == 1
assert success == 1
assert failed == 0
assert skipped == 0
assert writebacks
assert details[0]['writeback_srm'] is True
assert errors == []
assert judgement['manual_count'] == 1
assert judgement['dify_error_count'] == 1
assert judgement['system_error_count'] == 1
assert (run.response_summary_json or {}).get('current_step', {}).get('step') == 'completed'
assert any(log['step'] == 'call_dify' and log['status'] == 'success' for log in step_logs)
def test_srm_sql_operations_apply_configured_timeout(app, monkeypatch):
from app.services.schedule import srm_service
observed = {'connect_timeout': None, 'cursor_timeout': None}
class _Cursor:
description = [('id',)]
def __setattr__(self, name, value):
if name == 'timeout':
observed['cursor_timeout'] = value
object.__setattr__(self, name, value)
def execute(self, *_args):
return None
def fetchall(self):
return [(1,)]
class _Conn:
def cursor(self):
return _Cursor()
def commit(self):
return None
def close(self):
return None
class _Pyodbc:
@staticmethod
def connect(_conn_str, timeout):
observed['connect_timeout'] = timeout
return _Conn()
monkeypatch.setattr(srm_service, 'pyodbc', _Pyodbc)
with app.app_context():
app.config['SRM_SQLSERVER_TIMEOUT'] = 7
srm_service._execute_writeback('conn', 'update table set col=?', ('x',))
assert observed == {'connect_timeout': 7, 'cursor_timeout': 7}
def test_file_check_tool_requires_auth(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/file-check/tools/tasks')
assert res.status_code == 401
assert res.get_json()['error_code'] == 'missing_auth'
def test_file_check_tool_rejects_invalid_auth(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/file-check/tools/tasks', headers={'X-Integration-Key': 'wrong'})
assert res.status_code == 401
assert res.get_json()['error_code'] == 'invalid_auth'
def test_file_check_tool_lists_tasks_requires_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/file-check/tools/tasks', headers={'X-Integration-Key': 'secret'})
assert res.status_code == 400
assert res.get_json()['error_code'] == 'task_id_required'
def test_file_check_tool_lists_task_by_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
_mk_check_task(admin.id)
other_task = _mk_other_check_task(admin.id)
task_id = other_task.id
res = client.get(
f'/api/file-check/tools/tasks?task_id={task_id}',
headers={'X-Integration-Key': 'secret'},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert len(data['tasks']) == 1
assert data['tasks'][0]['task_id'] == task_id
assert data['tasks'][0]['task_no'] == 'CHK-GENERAL-001'
def test_file_check_tool_accepts_any_valid_task(app, client, monkeypatch):
class _Thread:
def __init__(self, *args, **kwargs):
pass
def start(self):
return None
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_other_check_task(admin.id)
task_id = task.id
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
assert res.status_code == 200
assert res.get_json()['ok'] is True
def test_file_check_tool_running_conflict(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
run = ScheduleRun(run_no='RUN-ROHS-001', schedule_task_id=task.id, status='running', trigger_type='manual')
db.session.add(run)
db.session.commit()
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'check_running'
def test_file_check_tool_check_running_records_chat_log_bind_context(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-BIND-CONFLICT',
schedule_task_id=task.id,
status='running',
trigger_type='manual',
)
db.session.add(run)
db.session.commit()
task_id = task.id
running_run_id = run.id
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'bind-on-conflict',
'user_message': '立即执行检核',
},
)
assert res.status_code == 200
assert res.get_json()['error_code'] == 'check_running'
with app.app_context():
bound = db.session.get(ScheduleRun, running_run_id)
req = bound.api_request_json or {}
assert req.get('bind_session_id') == 'bind-on-conflict'
assert req.get('bind_user_message') == '立即执行检核'
def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkeypatch):
class _Thread:
def __init__(self, *, target, daemon, name):
self.target = target
self.daemon = daemon
self.name = name
def start(self):
return None
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'bind-on-start',
'hxops_turn_id': 'turn-abc-001',
'user_message': '执行 RoHS 检核',
},
)
assert res.status_code == 200
run_id = res.get_json()['run']['run_id']
with app.app_context():
run = db.session.get(ScheduleRun, run_id)
req = run.api_request_json or {}
assert req.get('bind_session_id') == 'bind-on-start'
assert req.get('bind_turn_id') == 'turn-abc-001'
assert req.get('bind_user_message') == '执行 RoHS 检核'
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
assert resolve_run_id_for_chat_log(turn_id='turn-abc-001') == run_id
assert resolve_run_id_for_chat_log(session_id='bind-on-start', query='执行 RoHS 检核') == run_id
def test_file_check_tool_no_data_creates_bound_completed_run_with_full_progress(app, client, monkeypatch):
"""无待检资料也要给本轮对话一条可展示 100% 进度的完成批次。"""
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
before_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
monkeypatch.setattr('app.api.tools.file_check._precheck_no_data', lambda _task: {
'ok': False,
'error_code': 'no_data_to_check',
'message': '目前没有资料需要检核',
'task': {'task_id': _task.id, 'task_name': _task.name},
})
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'no-data-session',
'hxops_turn_id': 'no-data-turn',
'user_message': '立即执行检核',
},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'no_data_to_check'
run_id = data['run']['run_id']
with app.app_context():
after_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
assert after_count == before_count + 1
run = db.session.get(ScheduleRun, run_id)
assert run.status == 'success'
assert run.total_count == 0
assert run.success_count == 0
assert run.failed_count == 0
assert run.skipped_count == 0
assert run.finished_at is not None
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
assert resolve_run_id_for_chat_log(turn_id='no-data-turn') == run_id
assert resolve_run_id_for_chat_log(session_id='no-data-session', query='立即执行检核') == run_id
progress_res = client.get(
f'/api/workspace/file-check/runs/{run_id}',
headers={'X-Username': 'admin'},
)
assert progress_res.status_code == 200
assert progress_res.get_json()['run']['progress_percent'] == 100
def test_file_check_tool_no_data_keeps_existing_running_conflict_priority(app, client, monkeypatch):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-NO-DATA-CONFLICT',
schedule_task_id=task.id,
status='running',
trigger_type='manual',
)
db.session.add(run)
db.session.commit()
task_id = task.id
monkeypatch.setattr('app.api.tools.file_check._precheck_no_data', lambda _task: {
'ok': False,
'error_code': 'no_data_to_check',
'message': '目前没有资料需要检核',
'task': {'task_id': _task.id, 'task_name': _task.name},
})
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
assert res.status_code == 200
data = res.get_json()
assert data['error_code'] == 'check_running'
assert data.get('run', {}).get('run_id')
def test_file_check_tool_requires_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={},
)
assert res.status_code == 400
assert res.get_json()['error_code'] == 'task_id_required'
res_null = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': None},
)
assert res_null.status_code == 400
assert res_null.get_json()['error_code'] == 'task_id_required'
def test_file_check_tool_rejects_invalid_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': 'abc'},
)
assert res.status_code == 400
assert res.get_json()['error_code'] == 'task_id_invalid'
def test_file_check_tool_precheck_data_source_unavailable_on_runtime_error(app, client, monkeypatch):
"""预检连接串构建失败时返回 503 data_source_unavailable,而非 500。"""
class _SqlConfig:
fetch_sql = 'SELECT 1'
data_source = None
monkeypatch.setattr(
'app.api.tools.file_check.get_schedule_sql_config_by_task_id',
lambda _task_id: _SqlConfig(),
)
monkeypatch.setattr(
'app.api.tools.file_check._build_srm_conn_str',
lambda: (_ for _ in ()).throw(RuntimeError('SRM_SQLSERVER_HOST is not configured')),
)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task_id = _mk_check_task(admin.id).id
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'trigger_source': 'dify_chatflow', 'user_message': '立即执行检核'},
)
assert res.status_code == 503
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'data_source_unavailable'
assert '数据源不可用' in data['message']
def test_file_check_tool_precheck_data_source_unavailable_on_pyodbc_error(app, client, monkeypatch):
"""预检 ODBC 连接失败时返回 503 data_source_unavailable。"""
pyodbc = pytest.importorskip('pyodbc')
class _SqlConfig:
fetch_sql = 'SELECT 1'
data_source = None
monkeypatch.setattr(
'app.api.tools.file_check.get_schedule_sql_config_by_task_id',
lambda _task_id: _SqlConfig(),
)
monkeypatch.setattr(
'app.api.tools.file_check._build_srm_conn_str',
lambda: 'DRIVER={SQL Server};SERVER=127.0.0.1;DATABASE=test;UID=u;PWD=p',
)
monkeypatch.setattr(
'app.api.tools.file_check._fetch_records',
lambda *_args, **_kwargs: (_ for _ in ()).throw(pyodbc.InterfaceError('IM002', 'driver not found')),
)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task_id = _mk_check_task(admin.id).id
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'trigger_source': 'dify_chatflow', 'user_message': '立即执行检核'},
)
assert res.status_code == 503
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'data_source_unavailable'
def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
class _Thread:
def __init__(self, *args, **kwargs):
pass
def start(self):
return None
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
running_task = _mk_check_task(admin.id)
second_task = ScheduleTask(
schedule_no='CHK-ROHS-002',
name='RoHS 文件检核备用',
schedule_type='data_pipeline',
owner_user_id=admin.id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path='/2',
enabled=True,
)
db.session.add(second_task)
db.session.flush()
running = ScheduleRun(run_no='RUN-ROHS-RUNNING', schedule_task_id=running_task.id, status='running', trigger_type='manual')
db.session.add(running)
db.session.commit()
second_task_id = second_task.id
running_id = running.id
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': second_task_id},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['run']['task_id'] == second_task_id
def test_file_check_tool_lists_runs_without_task_filter(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
rohs_task = _mk_check_task(admin.id)
other_task = _mk_other_check_task(admin.id)
db.session.add_all([
ScheduleRun(run_no='RUN-ROHS-001', schedule_task_id=rohs_task.id, status='success', trigger_type='manual', total_count=3, success_count=3),
ScheduleRun(run_no='RUN-ROHS-002', schedule_task_id=rohs_task.id, status='partial_failed', trigger_type='manual', total_count=4, success_count=3, failed_count=1),
ScheduleRun(run_no='RUN-OTHER-001', schedule_task_id=other_task.id, status='success', trigger_type='manual', total_count=9, success_count=9),
])
db.session.commit()
res = client.get('/api/file-check/tools/runs?limit=10', headers={'X-Integration-Key': 'secret'})
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['count'] == 3
assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002', 'RUN-OTHER-001'}
def test_latest_file_check_run_binds_existing_run_to_query_turn(app, client):
"""查询最近批次只绑定当前对话,不得改写定时任务的原始执行上下文。"""
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-CRON-EMPTY',
schedule_task_id=task.id,
status='success',
trigger_type='cron',
total_count=0,
api_request_json={'trigger_source': 'cron'},
)
db.session.add(run)
db.session.commit()
task_id = task.id
run_id = run.id
from app.models import ChatToolRun
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
register_file_check_chat_turn(
turn_id='turn-query-latest',
session_id='session-query-latest',
user_id=admin.id,
agent_id=1,
query='查看最近执行记录',
)
register_pending_turn(
turn_id='turn-query-latest',
session_id='session-query-latest',
user_id=admin.id,
agent_id=1,
user_message='查看最近执行记录',
schedule_task_id=task_id,
)
res = client.get(
f'/api/file-check/tools/tasks/{task_id}/latest-run',
query_string={
'hxops_turn_id': 'turn-query-latest',
'conversation_id': 'session-query-latest',
'user_message': '查看最近执行记录',
},
headers={'X-Integration-Key': 'secret'},
)
assert res.status_code == 200
assert res.get_json()['run']['run_id'] == run_id
with app.app_context():
binding = ChatToolRun.query.filter_by(turn_id='turn-query-latest').first()
rebound_run = db.session.get(ScheduleRun, run_id)
assert binding.schedule_run_id == run_id
assert rebound_run.api_request_json == {'trigger_source': 'cron'}
def test_workspace_file_check_active_run_returns_progress(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-ACTIVE',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
total_count=10,
success_count=3,
failed_count=1,
skipped_count=1,
response_summary_json={
'current_step': {
'step': 'writeback_srm',
'label': '写回 SRM',
'row_id': 'ROW-16',
'started_at': '2026-06-11T10:00:00',
'processed_count': 4,
'success_count': 3,
'failed_count': 1,
'skipped_count': 0,
},
},
)
db.session.add(run)
db.session.commit()
res = client.get('/api/workspace/file-check/runs/active', headers={'X-Username': 'admin'})
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['run']['run_no'] == 'RUN-ROHS-ACTIVE'
assert data['run']['processed_count'] == 5
assert data['run']['progress_percent'] == 50
assert data['run']['current_step']['step'] == 'writeback_srm'
assert data['run']['current_step']['row_id'] == 'ROW-16'
def test_workspace_file_check_successful_empty_run_reports_complete_progress(app, client):
"""已完成的空批次应展示 100% 进度,避免被误解为尚未执行。"""
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-EMPTY',
schedule_task_id=task.id,
status='success',
trigger_type='cron',
total_count=0,
success_count=0,
failed_count=0,
skipped_count=0,
)
db.session.add(run)
db.session.commit()
run_id = run.id
res = client.get(
f'/api/workspace/file-check/runs/{run_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
assert res.get_json()['run']['progress_percent'] == 100
def test_workspace_file_check_active_run_filters_by_task_id(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
task_a = _mk_check_task(admin.id)
task_b = ScheduleTask(
schedule_no='CHK-ROHS-002',
name='RoHS 文件检核 B',
schedule_type='data_pipeline',
owner_user_id=admin.id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path='/2',
enabled=True,
)
db.session.add(task_b)
db.session.commit()
run_a = ScheduleRun(
run_no='RUN-ROHS-TASK-A',
schedule_task_id=task_a.id,
status='running',
trigger_type='manual',
total_count=10,
success_count=1,
)
run_b = ScheduleRun(
run_no='RUN-ROHS-TASK-B',
schedule_task_id=task_b.id,
status='running',
trigger_type='manual',
total_count=8,
success_count=2,
)
db.session.add_all([run_a, run_b])
db.session.commit()
task_a_id = task_a.id
task_b_id = task_b.id
hit = client.get(
f'/api/workspace/file-check/runs/active?task_id={task_a_id}',
headers={'X-Username': 'admin'},
)
assert hit.status_code == 200
assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-A'
miss = client.get(
f'/api/workspace/file-check/runs/active?task_id={task_b_id}',
headers={'X-Username': 'admin'},
)
assert miss.status_code == 200
assert miss.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-B'
def test_workspace_file_check_active_run_ignores_conversation_when_task_id_set(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-TASK-CONV-MISMATCH',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
total_count=10,
success_count=1,
api_request_json={'conversation_id': 'dify-conv-uuid'},
)
db.session.add(run)
db.session.commit()
task_id = task.id
res = client.get(
f'/api/workspace/file-check/runs/active?task_id={task_id}&conversation_id=hxops-session-id',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
assert res.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-CONV-MISMATCH'
def test_workspace_file_check_active_run_filters_by_conversation_id(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-ACTIVE-CONV',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
total_count=10,
success_count=2,
api_request_json={'conversation_id': 'conv-a'},
)
db.session.add(run)
db.session.commit()
miss = client.get('/api/workspace/file-check/runs/active?conversation_id=conv-b', headers={'X-Username': 'admin'})
assert miss.status_code == 200
assert miss.get_json()['run'] is None
hit = client.get('/api/workspace/file-check/runs/active?conversation_id=conv-a', headers={'X-Username': 'admin'})
assert hit.status_code == 200
assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-ACTIVE-CONV'
def test_workspace_file_check_run_for_log_returns_null_when_unbound(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
log = ChatLog(
user_id=admin.id,
agent_id=1,
query='查询最新结果',
answer='查询结果',
session_id='sess-query-only',
)
db.session.add(log)
db.session.commit()
task_id = task.id
chat_log_id = log.id
res = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
payload = res.get_json()
assert payload['run'] is None
assert payload.get('match_source') is None
def test_workspace_file_check_run_for_log_lazy_binds_via_session_query(app, client):
"""chat_log 尚无 run_id 时,for-log 应按 session/query 兜底匹配并回写。"""
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-LAZY',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
api_request_json={
'bind_session_id': 'sess-lazy-bind',
'bind_user_message': '立即执行文件检核',
},
)
db.session.add(run)
db.session.commit()
log = ChatLog(
user_id=admin.id,
agent_id=1,
query='立即执行文件检核',
answer='检核已启动',
session_id='sess-lazy-bind',
)
db.session.add(log)
db.session.commit()
task_id = task.id
chat_log_id = log.id
run_id = run.id
res = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
payload = res.get_json()
assert payload['run']['run_id'] == run_id
assert payload['match_source'] == 'legacy'
with app.app_context():
rebound = db.session.get(ChatLog, chat_log_id)
assert rebound.run_id == run_id
def test_workspace_file_check_run_for_log_reads_bound_run_id(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-BOUND',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
total_count=5,
success_count=1,
)
db.session.add(run)
db.session.commit()
log = ChatLog(
user_id=admin.id,
agent_id=1,
query='立即执行检核',
answer='检核已启动',
session_id='hxops-sess-002',
run_id=run.id,
)
db.session.add(log)
db.session.commit()
task_id = task.id
chat_log_id = log.id
res = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
payload = res.get_json()
assert payload['run']['run_no'] == 'RUN-ROHS-BOUND'
assert payload['match_source'] == 'chat_log'
def test_workspace_file_check_run_for_log_allows_different_user(app, client):
with app.app_context():
owner = User(username='rohs-owner', email='owner-rohs@example.com', role='admin', status='active')
owner.set_password('x')
viewer = User(username='rohs-viewer', email='viewer-rohs@example.com', role='user', status='active')
viewer.set_password('x')
db.session.add_all([owner, viewer])
db.session.commit()
task = _mk_check_task(owner.id)
run = ScheduleRun(
run_no='RUN-ROHS-CROSS-USER',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
total_count=3,
success_count=1,
)
db.session.add(run)
db.session.commit()
log = ChatLog(
user_id=owner.id,
agent_id=1,
query='立即执行检核',
answer='检核已启动',
session_id='hxops-sess-cross-user',
run_id=run.id,
)
db.session.add(log)
db.session.commit()
task_id = task.id
chat_log_id = log.id
res = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'rohs-viewer'},
)
assert res.status_code == 200
assert res.get_json()['run']['run_no'] == 'RUN-ROHS-CROSS-USER'
def test_workspace_file_check_run_for_log_returns_null_when_task_mismatch(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-OTHER-TASK',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
)
db.session.add(run)
db.session.commit()
log = ChatLog(
user_id=admin.id,
agent_id=1,
query='立即执行检核',
answer='检核已启动',
session_id='hxops-sess-empty',
run_id=run.id,
)
db.session.add(log)
db.session.commit()
chat_log_id = log.id
res = client.get(
f'/api/workspace/file-check/runs/for-log?task_id=99999&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
assert res.get_json()['run'] is None
def test_workspace_file_check_active_run_returns_null_when_idle(app, client):
with app.app_context():
_mk_admin()
db.session.commit()
res = client.get('/api/workspace/file-check/runs/active', headers={'X-Username': 'admin'})
assert res.status_code == 200
assert res.get_json()['run'] is None
def test_file_check_tool_excel_download_uses_user_facing_base_url(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
app.config['HXOPS_TOOLS_API_BASE'] = 'http://192.168.100.230:8890'
app.config['HXOPS_PUBLIC_BASE_URL'] = 'http://ai.well-trust.com:8890'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-EXCEL-DOMAIN',
schedule_task_id=task.id,
status='success',
trigger_type='manual',
excel_file_name='result.xlsx',
excel_file_data=b'xlsx-bytes',
excel_file_size=10,
)
db.session.add(run)
db.session.commit()
run_id = run.id
query_res = client.get(f'/api/file-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
download_url = query_res.get_json()['run']['excel']['download_url']
assert download_url.startswith('http://ai.well-trust.com:8890/api/file-check/tools/runs/')
assert '192.168.100.230' not in download_url
def test_file_check_tool_excel_download_works_without_tool_api_key(app, client):
"""浏览器 Excel 下载仅依赖 JWT,不应要求 INTEGRATION_API_KEY 已配置。"""
with app.app_context():
app.config['FILE_CHECK_TOOL_API_KEY'] = ''
app.config['INTEGRATION_API_KEY'] = ''
app.config['SECRET_KEY'] = 'download-signing-secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-EXCEL-NO-KEY',
schedule_task_id=task.id,
status='success',
trigger_type='manual',
excel_file_name='result.xlsx',
excel_file_data=b'xlsx-bytes',
excel_file_size=10,
)
db.session.add(run)
db.session.commit()
run_id = run.id
query_res = client.get(f'/api/file-check/tools/runs/{run_id}')
assert query_res.status_code == 503
with app.app_context():
run = db.session.get(ScheduleRun, run_id)
from app.api.tools.file_check import _build_excel_download_url
download_url = _build_excel_download_url(run)
download_path = download_url[download_url.index('/api/file-check'):]
res = client.get(download_path)
assert res.status_code == 200
assert res.data == b'xlsx-bytes'
def test_file_check_tool_excel_download_invalid_token_returns_invalid_auth(app, client):
with app.app_context():
app.config['SECRET_KEY'] = 'download-signing-secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-EXCEL-BAD-TOKEN',
schedule_task_id=task.id,
status='success',
trigger_type='manual',
excel_file_name='result.xlsx',
excel_file_data=b'xlsx-bytes',
excel_file_size=10,
)
db.session.add(run)
db.session.commit()
run_id = run.id
res = client.get(f'/api/file-check/tools/runs/{run_id}/excel?token=not-a-valid-token')
assert res.status_code == 401
assert res.get_json()['error_code'] == 'invalid_auth'
def test_file_check_tool_excel_download_uses_signed_token(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-EXCEL',
schedule_task_id=task.id,
status='success',
trigger_type='manual',
excel_file_name='result.xlsx',
excel_file_data=b'xlsx-bytes',
excel_file_size=10,
)
db.session.add(run)
db.session.commit()
run_id = run.id
query_res = client.get(f'/api/file-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
token_url = query_res.get_json()['run']['excel']['download_url']
download_path = token_url[token_url.index('/api/file-check'):]
res = client.get(download_path)
assert res.status_code == 200
assert res.data == b'xlsx-bytes'
res = client.get('/api/file-check/tools/tasks?token=' + download_path.split('token=', 1)[1])
assert res.status_code == 401
def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
enqueued = []
def _enqueue(*args, **kwargs):
enqueued.append({"args": args, "kwargs": kwargs})
return 1
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id, enabled=False)
task_id = task.id
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['run']['task_id'] == task_id
assert data['run']['status'] == 'running'
assert enqueued and enqueued[0]['kwargs'].get('domain') == 'file_check'
def test_serialize_file_judgement_reads_file_key():
from app.api.workspace.file_check import serialize_file_judgement
payload = {
"response_summary_json": {
"file_judgement": {
"qualified_count": 2,
"unqualified_count": 1,
"manual_count": 0,
"dify_error_count": 0,
"invalid_result_count": 0,
}
}
}
result = serialize_file_judgement(payload)
assert result["qualified_count"] == 2
assert result["unqualified_count"] == 1
def test_file_check_openapi_injects_tool_api_base(app, client):
with app.app_context():
app.config['HXOPS_TOOLS_API_BASE'] = 'https://file-check-tool.example.com'
res = client.get('/api/file-check/tools/openapi.json')
assert res.status_code == 200
assert res.get_json()['servers'][0]['url'] == 'https://file-check-tool.example.com'
def test_file_check_dify_chat_inputs(app):
import json
from app.services.agent_registry.resolver import is_file_check_runtime_ready
from app.services.agent_runtime_context import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_SCHEDULE_TASK_REF,
FILE_CHECK_TURN_REF,
build_file_check_dify_inputs,
)
class _Agent:
def __init__(self, name: str, *, agent_code='file_check', capabilities=None, bound_schedule_task_id=None):
self.name = name
self.agent_code = agent_code
self.capabilities = capabilities or {'task_progress': True}
self.bound_schedule_task_id = bound_schedule_task_id
self.extra_config = {}
assert is_file_check_runtime_ready(_Agent(
'RoHS文件检核助手',
bound_schedule_task_id=12,
))
assert not is_file_check_runtime_ready(_Agent('RoHS文件检核助手'))
assert not is_file_check_runtime_ready(_Agent(
'货代发货通知 Agent',
agent_code='shipping_notice',
capabilities={},
))
agent = _Agent(
'RoHS文件检核助手',
bound_schedule_task_id=12,
)
with app.app_context():
inputs = build_file_check_dify_inputs(
agent,
session_id='conv-file-check-001',
request_id='req-turn-001',
)
assert set(inputs.keys()) == {AGENT_RUNTIME_CONTEXT_INPUT}
payload = json.loads(inputs[AGENT_RUNTIME_CONTEXT_INPUT])
assert payload['refs'][FILE_CHECK_SCHEDULE_TASK_REF] == '12'
assert FILE_CHECK_TURN_REF not in payload['refs']
with app.app_context():
inputs_with_turn = build_file_check_dify_inputs(
agent,
session_id='conv-file-check-001',
request_id='req-turn-001',
hxops_turn_id='turn-file-check-001',
)
assert set(inputs_with_turn.keys()) == {AGENT_RUNTIME_CONTEXT_INPUT}
runtime_context = json.loads(inputs_with_turn[AGENT_RUNTIME_CONTEXT_INPUT])
assert runtime_context['refs'][FILE_CHECK_SCHEDULE_TASK_REF] == '12'
assert runtime_context['refs'][FILE_CHECK_TURN_REF] == 'turn-file-check-001'
def test_file_check_dify_chat_inputs_without_extra_task_id(app):
import pytest
from app.core.errors import ValidationError
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_MISSING_CODE,
build_file_check_dify_inputs,
)
class _Agent:
id = 26
name = 'RoHS文件检核助手'
extra_config = {}
with app.app_context():
assert build_file_check_dify_inputs(_Agent()) == {}
with pytest.raises(ValidationError) as exc:
build_file_check_dify_inputs(_Agent(), required=True)
assert exc.value.details.get('error_code') == FILE_CHECK_TASK_ID_MISSING_CODE
def test_file_check_dify_inputs_raises_when_capability_without_schedule_task_id(app):
import pytest
from app.core.errors import ValidationError
from app.services.agent_registry.resolver import (
agent_declares_task_progress,
is_file_check_runtime_ready,
)
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_MISSING_CODE,
build_file_check_dify_inputs,
)
class _Agent:
def __init__(self):
self.id = 26
self.name = 'RoHS文件检核助手'
self.agent_code = 'file_check'
self.capabilities = {'task_progress': True}
self.bound_schedule_task_id = None
self.extra_config = {}
agent = _Agent()
assert agent_declares_task_progress(agent)
assert not is_file_check_runtime_ready(agent)
with app.app_context():
with pytest.raises(ValidationError) as exc:
build_file_check_dify_inputs(agent, required=True)
assert exc.value.details.get('error_code') == FILE_CHECK_TASK_ID_MISSING_CODE
assert 'schedule_task_id' in exc.value.message
def test_file_check_executor_rejects_missing_schedule_task_id(app, monkeypatch):
"""未配置 bound_schedule_task_id 时,Executor 构建 inputs 应立即 ValidationError,不调用 Dify。"""
from types import SimpleNamespace
import pytest
from app.core.errors import ValidationError
from app.services.agent_registry.handlers.base import ChatStreamContext
from app.services.agent_registry.handlers.bootstrap import load_handlers
from app.services.chat.executors import stream_chat_via_executor
dify_called = {'value': False}
def fake_stream_chat(*args, **kwargs):
dify_called['value'] = True
yield 'data: {"event":"message_end"}\n\n'
monkeypatch.setattr(
'app.services.chat.executors.dify_chat.DifyService.stream_chat',
staticmethod(fake_stream_chat),
)
with app.app_context():
load_handlers()
ctx = ChatStreamContext(
query='立即执行RoHS文件检核',
display_query='立即执行RoHS文件检核',
user=SimpleNamespace(id=1, role='admin'),
agent=SimpleNamespace(
id=26,
name='RoHS文件检核助手',
agent_code='file_check',
runtime_provider='dify',
conversation_mode='task_chat',
dify_app_type='chatflow',
capabilities={'task_progress': True},
bound_schedule_task_id=None,
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'type': 'file_check'},
},
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
),
session=SimpleNamespace(session_id='conv-missing-task-001'),
external_conversation_id=None,
request_id='req-missing-task-001',
)
with pytest.raises(ValidationError) as exc:
list(stream_chat_via_executor(ctx))
assert exc.value.details.get('error_code') == 'file_check_task_id_required'
assert dify_called['value'] is False
def test_chat_agent_proxy_passes_registry_columns_for_task_id_injection():
"""chat.py agent_proxy 须携带 Registry 列,否则 agent_runtime_context.refs 注入失效。"""
import json
from types import SimpleNamespace
from app.services.agent_registry.resolver import is_file_check_runtime_ready
from app.services.agent_runtime_context import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_SCHEDULE_TASK_REF,
build_file_check_dify_inputs,
)
agent_proxy = SimpleNamespace(
id=26,
name='RoHS文件检核助手',
agent_code='file_check',
capabilities={'task_progress': True},
bound_schedule_task_id=12,
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
extra_config={},
)
assert is_file_check_runtime_ready(agent_proxy)
inputs = build_file_check_dify_inputs(agent_proxy, session_id='conv-proxy-001')
payload = json.loads(inputs[AGENT_RUNTIME_CONTEXT_INPUT])
assert payload['refs'][FILE_CHECK_SCHEDULE_TASK_REF] == '12'
bare_proxy = SimpleNamespace(
id=26,
name='RoHS文件检核助手',
agent_code='generic',
capabilities={},
bound_schedule_task_id=None,
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
)
assert not is_file_check_runtime_ready(bare_proxy)
assert build_file_check_dify_inputs(bare_proxy) == {}
def test_kb_sync_skips_failed_run(app):
from app.models import KbGroup
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
with app.app_context():
admin = _mk_admin()
group = KbGroup(name='RoHS KB', is_active=True)
db.session.add(group)
db.session.commit()
task = _mk_check_task(admin.id)
task.kb_sync_enabled = True
task.kb_group_id = group.id
run = ScheduleRun(
run_no='RUN-KB-SKIP',
schedule_task_id=task.id,
status='failed',
trigger_type='manual',
excel_file_data=b'xlsx',
excel_file_name='result.xlsx',
)
db.session.add(run)
db.session.commit()
sync_schedule_run_excel_to_kb(task, run)
assert run.kb_sync_status == 'skipped'
def test_kb_sync_repairs_document_id_sequence_on_pkey_conflict(app, monkeypatch, tmp_path):
from app.models import KbDocument, KbGroup
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
from sqlalchemy.exc import IntegrityError
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
original_flush = db.session.flush
failed = {'value': False}
def _flush_with_one_pkey_failure(*args, **kwargs):
if not failed['value'] and any(isinstance(item, KbDocument) for item in db.session.new):
failed['value'] = True
raise IntegrityError('insert', {}, Exception('duplicate key value violates unique constraint "kb_documents_pkey"'))
return original_flush(*args, **kwargs)
monkeypatch.setattr(db.session, 'flush', _flush_with_one_pkey_failure)
repaired: list[str] = []
monkeypatch.setattr(
'app.services.db_sequence.repair_pg_id_sequence',
lambda table_name: repaired.append(table_name),
)
with app.app_context():
admin = _mk_admin()
group = KbGroup(name='RoHS KB Seq', is_active=True)
db.session.add(group)
db.session.commit()
task = _mk_check_task(admin.id)
task.kb_sync_enabled = True
task.kb_group_id = group.id
run = ScheduleRun(
run_no='TEST-RUN-KB-SEQ',
schedule_task_id=task.id,
status='success',
trigger_type='test',
triggered_by_user_id=admin.id,
excel_file_data=b'fake-xlsx',
excel_file_name='result.xlsx',
)
db.session.add(run)
db.session.commit()
sync_schedule_run_excel_to_kb(task, run, process_inline=False)
assert repaired == ['kb_documents']
assert run.kb_document_id is not None
assert run.kb_sync_status == 'queued'
def test_kb_sync_repairs_version_id_sequence_without_losing_document(app, monkeypatch, tmp_path):
from app.models import KbDocumentVersion, KbGroup
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
from sqlalchemy.exc import IntegrityError
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
original_flush = db.session.flush
failed = {'value': False}
def _flush_with_version_pkey_failure(*args, **kwargs):
if not failed['value'] and any(isinstance(item, KbDocumentVersion) for item in db.session.new):
failed['value'] = True
raise IntegrityError('insert', {}, Exception('duplicate key value violates unique constraint "kb_document_versions_pkey"'))
return original_flush(*args, **kwargs)
monkeypatch.setattr(db.session, 'flush', _flush_with_version_pkey_failure)
repaired: list[str] = []
monkeypatch.setattr(
'app.services.db_sequence.repair_pg_id_sequence',
lambda table_name: repaired.append(table_name),
)
with app.app_context():
admin = _mk_admin()
group = KbGroup(name='RoHS KB Version Seq', is_active=True)
db.session.add(group)
db.session.commit()
task = _mk_check_task(admin.id)
task.kb_sync_enabled = True
task.kb_group_id = group.id
run = ScheduleRun(
run_no='TEST-RUN-KB-VERSION-SEQ',
schedule_task_id=task.id,
status='success',
trigger_type='test',
triggered_by_user_id=admin.id,
excel_file_data=b'fake-xlsx',
excel_file_name='result.xlsx',
)
db.session.add(run)
db.session.commit()
sync_schedule_run_excel_to_kb(task, run, process_inline=False)
assert repaired == ['kb_document_versions']
assert run.kb_document_id is not None
assert run.kb_document_version_id is not None
assert run.kb_sync_status == 'queued'
def test_dify_sync_repairs_sync_record_id_sequence_on_pkey_conflict(app, monkeypatch, tmp_path):
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
from sqlalchemy.exc import IntegrityError
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'ensure_dataset',
lambda self, group: ('ds-001', group.name),
)
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'create_document_by_text',
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name, 'indexing_status': 'completed'}},
)
with app.app_context():
admin = _mk_admin()
group = KbGroup(name='RoHS KB Dify', is_active=True, dify_dataset_id='ds-001')
document = KbDocument(
group_id=None,
title='RoHS sync seq',
status='ready',
source_type='schedule',
created_by_id=admin.id,
updated_by_id=admin.id,
)
db.session.add(group)
db.session.flush()
document.group_id = group.id
db.session.add(document)
db.session.flush()
cleaned = tmp_path / 'cleaned.md'
cleaned.write_text('# RoHS report', encoding='utf-8')
version = KbDocumentVersion(
document_id=document.id,
version_no=1,
status='ready',
is_current=True,
source_file_name='report.xlsx',
source_file_path=str(cleaned),
cleaned_file_path=str(cleaned),
uploaded_by_id=admin.id,
)
db.session.add(version)
db.session.commit()
original_flush = db.session.flush
repaired: list[str] = []
failed = {'value': False}
def _flush_with_one_pkey_failure(*args, **kwargs):
if not failed['value'] and any(isinstance(item, KbDifySyncRecord) for item in db.session.new):
failed['value'] = True
raise IntegrityError(
'insert',
{},
Exception(
'duplicate key value violates unique constraint "kb_dify_sync_records_pkey"'
),
)
return original_flush(*args, **kwargs)
monkeypatch.setattr(db.session, 'flush', _flush_with_one_pkey_failure)
monkeypatch.setattr(
'app.services.db_sequence.repair_pg_id_sequence',
lambda table_name: repaired.append(table_name),
)
result = dify_sync_module.sync_document_version_to_dify(version.id, synced_by_id=admin.id)
assert repaired == ['kb_dify_sync_records']
assert result['remote_document_id'] == 'remote-doc-001'
def test_kb_sync_queues_test_run_excel(app, monkeypatch, tmp_path):
from app.models import KbGroup
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
enqueued: list[int] = []
monkeypatch.setattr(
'app.services.schedule.kb_sync.enqueue_clean_job',
lambda job_id: enqueued.append(job_id),
)
with app.app_context():
admin = _mk_admin()
group = KbGroup(name='RoHS KB Test', is_active=True)
db.session.add(group)
db.session.commit()
task = _mk_check_task(admin.id)
task.kb_sync_enabled = True
task.kb_group_id = group.id
run = ScheduleRun(
run_no='TEST-RUN-KB-001',
schedule_task_id=task.id,
status='success',
trigger_type='test',
triggered_by_user_id=admin.id,
excel_file_data=b'fake-xlsx',
excel_file_name='result.xlsx',
)
db.session.add(run)
db.session.commit()
sync_schedule_run_excel_to_kb(task, run, process_inline=False)
assert run.kb_sync_status == 'queued'
assert run.kb_document_id is not None
assert run.kb_sync_job_id is not None
assert enqueued == [run.kb_sync_job_id]
def test_kb_sync_inline_processes_clean_and_sync_jobs(app, monkeypatch, tmp_path):
from app.models import KbGroup, KbJob
from app.services.schedule.kb_sync import process_schedule_kb_jobs_inline, sync_schedule_run_excel_to_kb
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
clean_calls: list[int] = []
sync_calls: list[int] = []
def _fake_clean(job_id: int):
clean_calls.append(job_id)
job = db.session.get(KbJob, job_id)
sync_job = KbJob(
job_type='sync_dify',
status='queued',
group_id=job.group_id,
document_id=job.document_id,
document_version_id=job.document_version_id,
progress=0,
message='pending',
payload_json={'document_version_id': job.document_version_id},
created_by_id=job.created_by_id,
)
db.session.add(sync_job)
db.session.flush()
run = db.session.get(ScheduleRun, (job.payload_json or {}).get('schedule_run_id'))
if run:
run.kb_sync_job_id = sync_job.id
run.kb_sync_status = 'syncing'
job.status = 'success'
db.session.commit()
return True, 'ok'
def _fake_sync(job_id: int):
sync_calls.append(job_id)
job = db.session.get(KbJob, job_id)
job.status = 'success'
db.session.commit()
return True, 'ok'
monkeypatch.setattr('app.services.knowledge_cleaning.tasks.run_clean_job', _fake_clean)
monkeypatch.setattr('app.services.knowledge_cleaning.tasks.run_sync_job', _fake_sync)
with app.app_context():
admin = _mk_admin()
group = KbGroup(name='RoHS KB Inline', is_active=True)
db.session.add(group)
db.session.commit()
task = _mk_check_task(admin.id)
task.kb_sync_enabled = True
task.kb_group_id = group.id
run = ScheduleRun(
run_no='TEST-RUN-KB-INLINE',
schedule_task_id=task.id,
status='success',
trigger_type='test',
triggered_by_user_id=admin.id,
excel_file_data=b'fake-xlsx',
excel_file_name='result.xlsx',
)
db.session.add(run)
db.session.commit()
sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=False)
clean_job_id = run.kb_sync_job_id
process_schedule_kb_jobs_inline(run)
db.session.refresh(run)
assert run.kb_document_id is not None
assert clean_calls == [clean_job_id]
assert sync_calls
assert run.kb_sync_status in ('success', 'ready', 'syncing')
def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, monkeypatch):
"""Dify HTTP 仅传 task_id + user_message 时,仍应通过 turn 注册表回写 run_id。"""
class _Thread:
def __init__(self, *, target, daemon, name):
self.target = target
self.daemon = daemon
self.name = name
def start(self):
return None
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
admin_id = admin.id
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
register_file_check_chat_turn(
turn_id='turn-registry-001',
session_id='sess-registry-001',
user_id=1,
agent_id=1,
query='立即执行 RoHS 检核',
)
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'user_message': '立即执行 RoHS 检核',
},
)
assert res.status_code == 200
run_id = res.get_json()['run']['run_id']
with app.app_context():
run = db.session.get(ScheduleRun, run_id)
req = run.api_request_json or {}
assert req.get('bind_session_id') == 'sess-registry-001'
assert req.get('bind_turn_id') == 'turn-registry-001'
assert resolve_run_id_for_chat_log(turn_id='turn-registry-001') == run_id
assert resolve_run_id_for_chat_log(
session_id='sess-registry-001',
query='立即执行 RoHS 检核',
) == run_id
chat_log_id = None
from app.services.integrations.dify import DifyService
result = DifyService._persist_stream_chat_record(
data={'conversation_id': 'sess-registry-001'},
event_name='message_end',
request_id='req-bind-test',
user_id=admin_id,
agent=_file_check_agent_proxy(task_id),
session_id='sess-registry-001',
hxops_turn_id='turn-registry-001',
normalized_conversation_id='sess-registry-001',
query='立即执行 RoHS 检核',
answer_text='检核已启动',
latency=10,
retriever_resources=[],
attribution_parts=[],
)
chat_log_id = result.get('chat_log_id')
assert chat_log_id
log = db.session.get(ChatLog, chat_log_id)
assert log.run_id == run_id
def test_history_search_normalizes_dify_records():
from app.services.file_check_tools.history_search_service import normalize_retrieve_records
payload = normalize_retrieve_records({
'records': [
{
'score': 0.91,
'segment': {
'content': 'Pb 超标',
'document_name': 'RoHS检核_RUN202606090001',
'metadata': {'run_no': 'RUN202606090001'},
},
},
],
})
assert len(payload) == 1
assert payload[0]['content'] == 'Pb 超标'
assert payload[0]['run_no'] == 'RUN202606090001'
assert payload[0]['document_title'] == 'RoHS检核_RUN202606090001'
def test_history_search_tool_requires_query(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
res = client.post(
'/api/file-check/tools/history/search',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'query': ' '},
)
assert res.status_code == 400
assert res.get_json()['error_code'] == 'query_required'
def test_history_search_tool_requires_kb_config(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
res = client.post(
'/api/file-check/tools/history/search',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'query': '上周有哪些不合格'},
)
assert res.status_code == 400
assert res.get_json()['error_code'] == 'kb_not_configured'
def test_history_search_tool_success(app, client, monkeypatch):
from app.models import KbGroup
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
group = KbGroup(name='RoHS KB Search', is_active=True, dify_dataset_id='ds-search-001')
db.session.add(group)
db.session.flush()
task.kb_sync_enabled = True
task.kb_group_id = group.id
db.session.commit()
task_id = task.id
def _fake_retrieve(self, **kwargs):
assert kwargs['dataset_id'] == 'ds-search-001'
assert kwargs['query'] == '上周有哪些不合格'
return {
'records': [
{
'score': 0.88,
'segment': {
'content': '供应商 A 铅含量不合格',
'document_name': f'RoHS 自动检核_RUN-TEST-001',
},
},
],
}
monkeypatch.setattr(
'app.services.knowledge_cleaning.dify_sync_service.KbDifySyncService.retrieve_dataset',
_fake_retrieve,
)
res = client.post(
'/api/file-check/tools/history/search',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'query': '上周有哪些不合格', 'top_k': 3},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['task_id'] == task_id
assert data['count'] == 1
assert data['segments'][0]['content'] == '供应商 A 铅含量不合格'
assert data['dify_dataset_id'] == 'ds-search-001'
def _stub_file_check_thread(monkeypatch):
class _Thread:
def __init__(self, *, target, daemon, name):
self.target = target
self.daemon = daemon
self.name = name
def start(self):
return None
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.tools.file_check.enqueue', _enqueue)
def _file_check_agent_proxy(task_id: int):
return type('AgentProxy', (), {
'id': 1,
'name': 'RoHS文件检核助手',
'agent_code': 'file_check',
'capabilities': {'task_progress': True},
'bound_schedule_task_id': task_id,
'extra_config': {},
})()
def test_chat_tool_runs_tool_first_then_chat_log(app, client, monkeypatch):
"""Tool 先启动、ChatLog 后落库时,chat_tool_runs 应能绑定进度。"""
_stub_file_check_thread(monkeypatch)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
admin_id = admin.id
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
with app.app_context():
register_pending_turn(
turn_id='turn-tool-first',
session_id='sess-tool-first',
user_id=admin_id,
agent_id=1,
user_message='立即执行 RoHS 检核',
schedule_task_id=task_id,
)
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'sess-tool-first',
'hxops_turn_id': 'turn-tool-first',
'user_message': '立即执行 RoHS 检核',
},
)
assert res.status_code == 200
run_id = res.get_json()['run']['run_id']
from app.services.integrations.dify import DifyService
with app.app_context():
result = DifyService._persist_stream_chat_record(
data={'conversation_id': 'sess-tool-first'},
event_name='message_end',
request_id='req-tool-first',
user_id=admin_id,
agent=_file_check_agent_proxy(task_id),
session_id='sess-tool-first',
hxops_turn_id='turn-tool-first',
normalized_conversation_id='sess-tool-first',
query='立即执行 RoHS 检核',
answer_text='检核已启动',
latency=10,
retriever_resources=[],
attribution_parts=[],
)
chat_log_id = result['chat_log_id']
log = db.session.get(ChatLog, chat_log_id)
assert log.run_id == run_id
poll = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert poll.status_code == 200
payload = poll.get_json()
assert payload['run']['run_id'] == run_id
assert payload['match_source'] == 'chat_log'
def test_chat_tool_runs_chat_log_first_then_tool(app, client, monkeypatch):
"""ChatLog 先落库、Tool 后启动时,for-log 应通过 chat_tool_runs 懒绑定。"""
_stub_file_check_thread(monkeypatch)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
admin_id = admin.id
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
from app.services.integrations.dify import DifyService
with app.app_context():
register_pending_turn(
turn_id='turn-log-first',
session_id='sess-log-first',
user_id=admin_id,
agent_id=1,
user_message='立即执行 RoHS 检核',
schedule_task_id=task_id,
)
with app.app_context():
result = DifyService._persist_stream_chat_record(
data={'conversation_id': 'sess-log-first'},
event_name='message_end',
request_id='req-log-first',
user_id=admin_id,
agent=_file_check_agent_proxy(task_id),
session_id='sess-log-first',
hxops_turn_id='turn-log-first',
normalized_conversation_id='sess-log-first',
query='立即执行 RoHS 检核',
answer_text='检核已启动',
latency=10,
retriever_resources=[],
attribution_parts=[],
)
chat_log_id = result['chat_log_id']
log = db.session.get(ChatLog, chat_log_id)
assert log.run_id is None
miss = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert miss.status_code == 200
assert miss.get_json()['run'] is None
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'sess-log-first',
'hxops_turn_id': 'turn-log-first',
'user_message': '立即执行 RoHS 检核',
},
)
assert res.status_code == 200
run_id = res.get_json()['run']['run_id']
poll = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert poll.status_code == 200
payload = poll.get_json()
assert payload['run']['run_id'] == run_id
assert payload['match_source'] == 'chat_log'
with app.app_context():
rebound = db.session.get(ChatLog, chat_log_id)
assert rebound.run_id == run_id
def test_chat_tool_runs_same_message_does_not_cross_runs(app, client, monkeypatch):
"""同文案多轮触发时,应按 turn_id 区分 run,避免串批次。"""
_stub_file_check_thread(monkeypatch)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
admin_id = admin.id
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
with app.app_context():
register_pending_turn(
turn_id='turn-same-msg-a',
session_id='sess-same-msg',
user_id=admin_id,
agent_id=1,
user_message='立即执行检核',
schedule_task_id=task_id,
)
res_a = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'sess-same-msg',
'hxops_turn_id': 'turn-same-msg-a',
'user_message': '立即执行检核',
},
)
run_a = res_a.get_json()['run']['run_id']
with app.app_context():
register_pending_turn(
turn_id='turn-same-msg-b',
session_id='sess-same-msg',
user_id=admin_id,
agent_id=1,
user_message='立即执行检核',
schedule_task_id=task_id,
)
res_b = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'sess-same-msg',
'hxops_turn_id': 'turn-same-msg-b',
'user_message': '立即执行检核',
},
)
assert res_b.status_code == 200
assert res_b.get_json().get('error_code') == 'check_running'
run_b = res_b.get_json()['run']['run_id']
assert run_b == run_a
from app.services.integrations.dify import DifyService
with app.app_context():
result_b = DifyService._persist_stream_chat_record(
data={'conversation_id': 'sess-same-msg'},
event_name='message_end',
request_id='req-same-msg-b',
user_id=admin_id,
agent=_file_check_agent_proxy(task_id),
session_id='sess-same-msg',
hxops_turn_id='turn-same-msg-b',
normalized_conversation_id='sess-same-msg',
query='立即执行检核',
answer_text='检核已启动',
latency=10,
retriever_resources=[],
attribution_parts=[],
)
chat_log_b = result_b['chat_log_id']
log_b = db.session.get(ChatLog, chat_log_b)
assert log_b.run_id == run_a
result_a = DifyService._persist_stream_chat_record(
data={'conversation_id': 'sess-same-msg'},
event_name='message_end',
request_id='req-same-msg-a',
user_id=admin_id,
agent=_file_check_agent_proxy(task_id),
session_id='sess-same-msg',
hxops_turn_id='turn-same-msg-a',
normalized_conversation_id='sess-same-msg',
query='立即执行检核',
answer_text='检核已启动',
latency=8,
retriever_resources=[],
attribution_parts=[],
)
chat_log_a = result_a['chat_log_id']
log_a = db.session.get(ChatLog, chat_log_a)
assert log_a.run_id == run_a
assert log_a.id != log_b.id
def test_chat_tool_runs_without_turn_id_same_message_skips_ambiguous_bind(app, client, monkeypatch):
"""
无 hxops_turn_id 且存在多个同文案 pending turn 时,不得绑定到任一 turn(宁可未绑定)。
"""
_stub_file_check_thread(monkeypatch)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
admin_id = admin.id
from app.models import ChatToolRun
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
from app.services.integrations.dify import DifyService
with app.app_context():
register_pending_turn(
turn_id='turn-ambig-a',
session_id='sess-ambig',
user_id=admin_id,
agent_id=1,
user_message='立即执行检核',
schedule_task_id=task_id,
)
register_pending_turn(
turn_id='turn-ambig-b',
session_id='sess-ambig',
user_id=admin_id,
agent_id=1,
user_message='立即执行检核',
schedule_task_id=task_id,
)
clear_registry_for_tests()
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'sess-ambig',
'user_message': '立即执行检核',
},
)
assert res.status_code == 200
run_id = res.get_json()['run']['run_id']
with app.app_context():
row_a = ChatToolRun.query.filter_by(turn_id='turn-ambig-a').first()
row_b = ChatToolRun.query.filter_by(turn_id='turn-ambig-b').first()
assert row_a.schedule_run_id is None
assert row_b.schedule_run_id is None
result_a = DifyService._persist_stream_chat_record(
data={'conversation_id': 'sess-ambig'},
event_name='message_end',
request_id='req-ambig-a',
user_id=admin_id,
agent=_file_check_agent_proxy(task_id),
session_id='sess-ambig',
hxops_turn_id='turn-ambig-a',
normalized_conversation_id='sess-ambig',
query='立即执行检核',
answer_text='检核已启动',
latency=10,
retriever_resources=[],
attribution_parts=[],
)
log_a = db.session.get(ChatLog, result_a['chat_log_id'])
assert log_a.run_id is None
poll = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={log_a.id}',
headers={'X-Username': 'admin'},
)
assert poll.status_code == 200
assert poll.get_json()['run'] is None
def test_chat_tool_runs_with_turn_id_binds_exact_pending_turn(app, client, monkeypatch):
"""显式 hxops_turn_id 时必须准确绑定对应 turn。"""
_stub_file_check_thread(monkeypatch)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
admin_id = admin.id
from app.models import ChatToolRun
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
with app.app_context():
register_pending_turn(
turn_id='turn-explicit-a',
session_id='sess-explicit',
user_id=admin_id,
agent_id=1,
user_message='立即执行检核',
schedule_task_id=task_id,
)
register_pending_turn(
turn_id='turn-explicit-b',
session_id='sess-explicit',
user_id=admin_id,
agent_id=1,
user_message='立即执行检核',
schedule_task_id=task_id,
)
clear_registry_for_tests()
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'sess-explicit',
'hxops_turn_id': 'turn-explicit-a',
'user_message': '立即执行检核',
},
)
assert res.status_code == 200
run_id = res.get_json()['run']['run_id']
with app.app_context():
row_a = ChatToolRun.query.filter_by(turn_id='turn-explicit-a').first()
row_b = ChatToolRun.query.filter_by(turn_id='turn-explicit-b').first()
assert row_a.schedule_run_id == run_id
assert row_b.schedule_run_id is None
def test_chat_tool_runs_for_log_lazy_resolves_from_binding_table(app, client):
"""chat_logs.run_id 为空但 chat_tool_runs 已绑定时,for-log 应走 chat_tool_runs 并回写。"""
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-BIND-TABLE',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
)
db.session.add(run)
db.session.commit()
log = ChatLog(
user_id=admin.id,
agent_id=1,
query='立即执行检核',
answer='检核已启动',
session_id='sess-bind-table',
)
db.session.add(log)
db.session.commit()
from app.models import ChatToolRun
row = ChatToolRun(
tool_name='run_file_check',
session_id='sess-bind-table',
turn_id='turn-bind-table',
chat_log_id=log.id,
schedule_task_id=task.id,
schedule_run_id=run.id,
user_message='立即执行检核',
status='complete',
bind_source='tool_start',
)
db.session.add(row)
db.session.commit()
task_id = task.id
chat_log_id = log.id
run_id = run.id
res = client.get(
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
payload = res.get_json()
assert payload['run']['run_id'] == run_id
assert payload['match_source'] == 'chat_tool_runs'
with app.app_context():
rebound = db.session.get(ChatLog, chat_log_id)
assert rebound.run_id == run_id