import sys import types import pytest from app import db from app.models import ScheduleRun, ScheduleTask, User from app.services.rohs_check import RoHSCheckService @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_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 == 409 data = res.get_json() assert data['error_code'] == 'check_running' 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_TOOL_API_KEY'] = 'rohs-secret' inputs = build_dify_chat_inputs() assert inputs[HXOPS_TOOLS_API_BASE_INPUT] == 'https://rohs-tool.example.com' assert inputs[HXOPS_TOOL_API_TOKEN_INPUT] == 'rohs-secret' 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_TOOL_API_BASE'] = 'https://legacy-tool.example.com' app.config.pop('ROHS_TOOL_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')