1581 lines
53 KiB
Python
1581 lines
53 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 _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 _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='platform_app',
|
|
owner_user_id=owner_id,
|
|
cron_expr='0 * * * *',
|
|
wait_seconds=5,
|
|
platform_api_path='/1',
|
|
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='platform_app',
|
|
owner_user_id=owner_id,
|
|
cron_expr='0 * * * *',
|
|
wait_seconds=5,
|
|
platform_api_path='/general-check',
|
|
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'
|
|
|
|
|
|
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',
|
|
}
|
|
|
|
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 (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
|
|
|
|
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
|
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
|
|
|
|
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
|
|
|
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_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'
|
|
|
|
|
|
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_running_conflict_is_per_task(app, client, monkeypatch):
|
|
class _Thread:
|
|
def __init__(self, *args, **kwargs):
|
|
pass
|
|
|
|
def start(self):
|
|
return None
|
|
|
|
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
|
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='platform_app',
|
|
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_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_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='platform_app',
|
|
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'] == 'chat_log'
|
|
|
|
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_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):
|
|
started_threads = []
|
|
|
|
class _Thread:
|
|
def __init__(self, *, target, daemon, name):
|
|
self.target = target
|
|
self.daemon = daemon
|
|
self.name = name
|
|
|
|
def start(self):
|
|
started_threads.append(self.name)
|
|
|
|
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
|
|
|
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 started_threads == [f"file-check-run-{data['run']['run_id']}"]
|
|
|
|
|
|
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):
|
|
from app.services.file_check_tools.dify_inputs import (
|
|
FILE_CHECK_TASK_ID_INPUT,
|
|
build_file_check_dify_inputs,
|
|
)
|
|
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
|
|
|
|
class _Agent:
|
|
def __init__(self, name: str, *, extra_config=None):
|
|
self.name = name
|
|
self.extra_config = extra_config or {}
|
|
|
|
assert is_file_check_chat_agent(_Agent(
|
|
'RoHS文件检核助手',
|
|
extra_config={
|
|
'capabilities': ['tool_run_progress'],
|
|
'tool_run_progress': {'schedule_task_id': 12},
|
|
},
|
|
))
|
|
assert not is_file_check_chat_agent(_Agent('RoHS文件检核助手'))
|
|
assert not is_file_check_chat_agent(_Agent('货代发货通知 Agent'))
|
|
|
|
agent = _Agent(
|
|
'RoHS文件检核助手',
|
|
extra_config={
|
|
'capabilities': ['tool_run_progress'],
|
|
'tool_run_progress': {'schedule_task_id': 12},
|
|
},
|
|
)
|
|
with app.app_context():
|
|
inputs = build_file_check_dify_inputs(agent)
|
|
assert inputs[FILE_CHECK_TASK_ID_INPUT] == '12'
|
|
assert 'hxops_session_id' not in inputs
|
|
assert 'hxops_turn_id' not in inputs
|
|
|
|
|
|
def test_file_check_dify_chat_inputs_without_extra_task_id(app):
|
|
import pytest
|
|
|
|
from app.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.errors import ValidationError
|
|
from app.services.file_check_tools.agent_resolver import (
|
|
agent_declares_file_check_progress,
|
|
is_file_check_chat_agent,
|
|
)
|
|
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.extra_config = {
|
|
'capabilities': ['tool_run_progress'],
|
|
'tool_run_progress': {'type': 'file_check'},
|
|
}
|
|
|
|
agent = _Agent()
|
|
assert agent_declares_file_check_progress(agent)
|
|
assert not is_file_check_chat_agent(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_chat_completions_rejects_missing_file_check_task_id(app, client, mocker):
|
|
"""声明了文件检核能力但未配置 schedule_task_id 时,/completions 应立即 400 而非挂死。"""
|
|
from flask import g
|
|
|
|
from app.models import Agent, User
|
|
|
|
misconfigured = Agent(
|
|
id=26,
|
|
name='RoHS文件检核助手',
|
|
dify_api_key='app-key',
|
|
api_base_url='http://dify.example/v1',
|
|
type='api',
|
|
extra_config={
|
|
'capabilities': ['tool_run_progress'],
|
|
'tool_run_progress': {'type': 'file_check'},
|
|
},
|
|
is_active=True,
|
|
)
|
|
user = User(id=1, username='admin', status='active', role='admin')
|
|
user.agents = [misconfigured]
|
|
|
|
def mock_get_user():
|
|
g.current_user = user
|
|
return user
|
|
|
|
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
|
|
mocker.patch('app.models.Agent.query').get.return_value = misconfigured
|
|
mock_post = mocker.patch('requests.post')
|
|
mock_post.side_effect = AssertionError('Dify must not be called when task_id is missing')
|
|
|
|
res = client.post(
|
|
'/api/chat/completions',
|
|
json={'query': '立即执行RoHS文件检核', 'agent_id': 26},
|
|
headers={'Content-Type': 'application/json'},
|
|
)
|
|
|
|
assert res.status_code == 400
|
|
body = res.get_json()
|
|
assert body['error']['code'] == 'VALIDATION.INVALID_PARAM'
|
|
assert body['error']['details']['error_code'] == 'file_check_task_id_required'
|
|
mock_post.assert_not_called()
|
|
|
|
|
|
def test_chat_agent_proxy_passes_extra_config_for_task_id_injection():
|
|
"""chat.py agent_proxy 须携带 extra_config,否则 is_file_check_chat_agent / task_id 注入失效。"""
|
|
from types import SimpleNamespace
|
|
|
|
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
|
|
from app.services.file_check_tools.dify_inputs import (
|
|
FILE_CHECK_TASK_ID_INPUT,
|
|
build_file_check_dify_inputs,
|
|
)
|
|
|
|
agent_proxy = SimpleNamespace(
|
|
id=26,
|
|
name='RoHS文件检核助手',
|
|
dify_api_key='app-key',
|
|
api_base_url='http://dify.example/v1',
|
|
extra_config={
|
|
'capabilities': ['tool_run_progress'],
|
|
'tool_run_progress': {'schedule_task_id': 12},
|
|
},
|
|
)
|
|
assert is_file_check_chat_agent(agent_proxy)
|
|
assert build_file_check_dify_inputs(agent_proxy)[FILE_CHECK_TASK_ID_INPUT] == '12'
|
|
|
|
bare_proxy = SimpleNamespace(
|
|
id=26,
|
|
name='RoHS文件检核助手',
|
|
dify_api_key='app-key',
|
|
api_base_url='http://dify.example/v1',
|
|
)
|
|
assert not is_file_check_chat_agent(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: {'document': {'id': 'remote-doc-001', 'name': name}},
|
|
)
|
|
|
|
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
|
|
|
|
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
|
|
|
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.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=type('AgentProxy', (), {
|
|
'id': 1,
|
|
'name': 'RoHS文件检核助手',
|
|
'extra_config': {
|
|
'capabilities': ['tool_run_progress'],
|
|
'tool_run_progress': {'schedule_task_id': 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'
|