1247 lines
42 KiB
Python
1247 lines
42 KiB
Python
import sys
|
|
import types
|
|
|
|
import pytest
|
|
|
|
from app import db
|
|
from app.models import ChatLog, ChatSession, ScheduleRun, ScheduleTask, User
|
|
from app.services.rohs_check import RoHSCheckService
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _clear_rohs_turn_registry():
|
|
from app.services.rohs_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_non_rohs_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_rohs_service_normalizes_failed_workflow():
|
|
payload = RoHSCheckService.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_rohs_service_evaluate_degrades_on_dify_error(monkeypatch):
|
|
class _Agent:
|
|
id = 1
|
|
|
|
def _boom(**kwargs):
|
|
raise RuntimeError('dify down')
|
|
|
|
monkeypatch.setattr('app.services.rohs_check.DifyService.run_workflow_streaming', _boom)
|
|
payload = RoHSCheckService.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_rohs_service_normalizes_invalid_result():
|
|
payload = RoHSCheckService.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_rohs_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.RoHSCheckService.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('rohs_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_rohs_tool_requires_auth(app, client):
|
|
with app.app_context():
|
|
app.config['INTEGRATION_API_KEY'] = 'secret'
|
|
res = client.get('/api/rohs-check/tools/tasks')
|
|
assert res.status_code == 401
|
|
assert res.get_json()['error_code'] == 'missing_auth'
|
|
|
|
|
|
def test_rohs_tool_rejects_invalid_auth(app, client):
|
|
with app.app_context():
|
|
app.config['INTEGRATION_API_KEY'] = 'secret'
|
|
res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'wrong'})
|
|
assert res.status_code == 401
|
|
assert res.get_json()['error_code'] == 'invalid_auth'
|
|
|
|
|
|
def test_rohs_tool_lists_tasks(app, client):
|
|
with app.app_context():
|
|
app.config['INTEGRATION_API_KEY'] = 'secret'
|
|
admin = _mk_admin()
|
|
db.session.commit()
|
|
_mk_check_task(admin.id)
|
|
_mk_non_rohs_task(admin.id)
|
|
|
|
res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'secret'})
|
|
assert res.status_code == 200
|
|
data = res.get_json()
|
|
assert data['ok'] is True
|
|
assert [item['task_no'] for item in data['tasks']] == ['CHK-ROHS-001']
|
|
|
|
|
|
def test_rohs_tool_rejects_non_rohs_task(app, client):
|
|
with app.app_context():
|
|
app.config['INTEGRATION_API_KEY'] = 'secret'
|
|
admin = _mk_admin()
|
|
db.session.commit()
|
|
task = _mk_non_rohs_task(admin.id)
|
|
task_id = task.id
|
|
|
|
res = client.post(
|
|
'/api/rohs-check/tools/tasks/run',
|
|
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
|
json={'task_id': task_id},
|
|
)
|
|
assert res.status_code == 404
|
|
assert res.get_json()['error_code'] == 'task_not_found'
|
|
|
|
|
|
def test_rohs_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/rohs-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_rohs_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/rohs-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_rohs_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.rohs_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/rohs-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.rohs_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_rohs_tool_requires_task_id(app, client):
|
|
with app.app_context():
|
|
app.config['INTEGRATION_API_KEY'] = 'secret'
|
|
|
|
res = client.post(
|
|
'/api/rohs-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_rohs_tool_rejects_invalid_task_id(app, client):
|
|
with app.app_context():
|
|
app.config['INTEGRATION_API_KEY'] = 'secret'
|
|
|
|
res = client.post(
|
|
'/api/rohs-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_rohs_tool_running_conflict_is_global(app, client):
|
|
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/rohs-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 False
|
|
assert data['error_code'] == 'check_running'
|
|
assert data['run']['run_id'] == running_id
|
|
|
|
|
|
def test_rohs_tool_lists_all_rohs_runs(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_non_rohs_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/rohs-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'] == 2
|
|
assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002'}
|
|
|
|
|
|
def test_workspace_rohs_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/rohs-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_rohs_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/rohs-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/rohs-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_rohs_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/rohs-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_rohs_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/rohs-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/rohs-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_rohs_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/rohs-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_rohs_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/rohs-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_rohs_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/rohs-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_rohs_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/rohs-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_rohs_active_run_returns_null_when_idle(app, client):
|
|
with app.app_context():
|
|
_mk_admin()
|
|
db.session.commit()
|
|
|
|
res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'})
|
|
assert res.status_code == 200
|
|
assert res.get_json()['run'] is None
|
|
|
|
|
|
def test_rohs_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/rohs-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/rohs-check'):]
|
|
|
|
res = client.get(download_path)
|
|
assert res.status_code == 200
|
|
assert res.data == b'xlsx-bytes'
|
|
|
|
res = client.get('/api/rohs-check/tools/tasks?token=' + download_path.split('token=', 1)[1])
|
|
assert res.status_code == 401
|
|
|
|
|
|
def test_rohs_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.rohs_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/rohs-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"rohs-check-run-{data['run']['run_id']}"]
|
|
|
|
|
|
def test_rohs_openapi_injects_tool_api_base(app, client):
|
|
with app.app_context():
|
|
app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com'
|
|
res = client.get('/api/rohs-check/tools/openapi.json')
|
|
assert res.status_code == 200
|
|
assert res.get_json()['servers'][0]['url'] == 'https://rohs-tool.example.com'
|
|
|
|
|
|
def test_rohs_dify_chat_inputs(app):
|
|
from app.services.rohs_check_tools.dify_inputs import (
|
|
HXOPS_TOOL_API_TOKEN_INPUT,
|
|
HXOPS_TOOLS_API_BASE_INPUT,
|
|
build_dify_chat_inputs,
|
|
)
|
|
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
|
|
|
|
class _Agent:
|
|
def __init__(self, name: str):
|
|
self.name = name
|
|
|
|
assert is_rohs_check_chat_agent(_Agent('RoHS文件检核助手'))
|
|
assert not is_rohs_check_chat_agent(_Agent('货代发货通知 Agent'))
|
|
|
|
with app.app_context():
|
|
app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com'
|
|
app.config['ROHS_TOOLS_API_KEY'] = 'rohs-secret'
|
|
inputs = build_dify_chat_inputs(hxops_session_id='sess-abc')
|
|
assert inputs[HXOPS_TOOLS_API_BASE_INPUT] == 'https://rohs-tool.example.com'
|
|
assert inputs[HXOPS_TOOL_API_TOKEN_INPUT] == 'rohs-secret'
|
|
assert inputs['hxops_session_id'] == 'sess-abc'
|
|
|
|
|
|
def test_rohs_dify_chat_inputs_falls_back_to_legacy_env_key(app):
|
|
from app.services.rohs_check_tools.dify_inputs import build_dify_chat_inputs
|
|
|
|
with app.app_context():
|
|
app.config.pop('HXOPS_TOOLS_API_BASE', None)
|
|
app.config['HXOPS_TOOLS_API_BASE'] = 'https://legacy-tool.example.com'
|
|
app.config.pop('ROHS_TOOLS_API_KEY', None)
|
|
app.config['INTEGRATION_API_KEY'] = 'integration-secret'
|
|
inputs = build_dify_chat_inputs()
|
|
assert inputs['HXOPS_TOOLS_API_BASE'] == 'https://legacy-tool.example.com'
|
|
assert inputs['hxops_tool_api_token'] == 'integration-secret'
|
|
|
|
|
|
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_rohs_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.rohs_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.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn
|
|
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
|
|
|
|
register_rohs_chat_turn(
|
|
turn_id='turn-registry-001',
|
|
session_id='sess-registry-001',
|
|
user_id=1,
|
|
agent_id=1,
|
|
query='立即执行 RoHS 检核',
|
|
)
|
|
|
|
res = client.post(
|
|
'/api/rohs-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文件检核助手'})(),
|
|
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
|