feat(file-check): 增加文件检核 Excel 下载链接解析与展示功能

This commit is contained in:
hugo committed 2026-07-10 13:28:41 +08:00
1 parent 5e7e5a8717
commit f21216f81e
21 files changed
+885 -125

No files matched your search

@@ -271,3 +271,40 @@ def test_file_check_evaluate_exception_includes_error_type(monkeypatch):
assert payload["error_type"] == "http_403"
assert payload["retryable"] is False
assert payload["poll_used"] is False
def test_merge_stream_answer_text_replaces_when_terminal_contains_streamed():
streamed = "检核完成,共处理 3 个文件,全部成功。"
terminal = streamed
merged = DifyService._merge_stream_answer_text(streamed, terminal)
assert merged == streamed
assert merged != streamed + terminal
def test_merge_stream_answer_text_honors_replace_answer_flag():
streamed = "partial"
terminal = "final answer"
merged = DifyService._merge_stream_answer_text(streamed, terminal, replace_answer=True)
assert merged == "final answer"
def test_merge_stream_answer_text_appends_non_overlapping_suffix():
merged = DifyService._merge_stream_answer_text("Hello", " world")
assert merged == "Hello world"
def test_build_final_answer_text_dedupes_message_end_payload():
streamed_parts = ["检核", "完成。"]
data = {"answer": "检核完成。"}
result = DifyService._build_final_answer_text(
streamed_parts=streamed_parts,
data=data,
event_name="message_end",
)
assert result == "检核完成。"
def test_dedupe_exact_doubled_text_fixes_historical_records():
doubled = "检核完成,共处理 3 个文件。" * 2
assert DifyService._dedupe_exact_doubled_text(doubled) == "检核完成,共处理 3 个文件。"
assert DifyService._dedupe_exact_doubled_text("unique answer") == "unique answer"
+167
View File
@@ -503,6 +503,14 @@ def test_file_check_tool_requires_task_id(app, client):
assert res.status_code == 400
assert res.get_json()['error_code'] == 'task_id_required'
res_null = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': None},
)
assert res_null.status_code == 400
assert res_null.get_json()['error_code'] == 'task_id_required'
def test_file_check_tool_rejects_invalid_task_id(app, client):
with app.app_context():
@@ -517,6 +525,77 @@ def test_file_check_tool_rejects_invalid_task_id(app, client):
assert res.get_json()['error_code'] == 'task_id_invalid'
def test_file_check_tool_precheck_data_source_unavailable_on_runtime_error(app, client, monkeypatch):
"""预检连接串构建失败时返回 503 data_source_unavailable,而非 500。"""
class _SqlConfig:
fetch_sql = 'SELECT 1'
data_source = None
monkeypatch.setattr(
'app.api.file_check_tools.get_schedule_sql_config_by_task_id',
lambda _task_id: _SqlConfig(),
)
monkeypatch.setattr(
'app.api.file_check_tools._build_srm_conn_str',
lambda: (_ for _ in ()).throw(RuntimeError('SRM_SQLSERVER_HOST is not configured')),
)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task_id = _mk_check_task(admin.id).id
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'trigger_source': 'dify_chatflow', 'user_message': '立即执行检核'},
)
assert res.status_code == 503
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'data_source_unavailable'
assert '数据源不可用' in data['message']
def test_file_check_tool_precheck_data_source_unavailable_on_pyodbc_error(app, client, monkeypatch):
"""预检 ODBC 连接失败时返回 503 data_source_unavailable。"""
pyodbc = pytest.importorskip('pyodbc')
class _SqlConfig:
fetch_sql = 'SELECT 1'
data_source = None
monkeypatch.setattr(
'app.api.file_check_tools.get_schedule_sql_config_by_task_id',
lambda _task_id: _SqlConfig(),
)
monkeypatch.setattr(
'app.api.file_check_tools._build_srm_conn_str',
lambda: 'DRIVER={SQL Server};SERVER=127.0.0.1;DATABASE=test;UID=u;PWD=p',
)
monkeypatch.setattr(
'app.api.file_check_tools._fetch_records',
lambda *_args, **_kwargs: (_ for _ in ()).throw(pyodbc.InterfaceError('IM002', 'driver not found')),
)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task_id = _mk_check_task(admin.id).id
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id, 'trigger_source': 'dify_chatflow', 'user_message': '立即执行检核'},
)
assert res.status_code == 503
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'data_source_unavailable'
def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
class _Thread:
def __init__(self, *args, **kwargs):
@@ -921,6 +1000,94 @@ def test_workspace_file_check_active_run_returns_null_when_idle(app, client):
assert res.get_json()['run'] is None
def test_file_check_tool_excel_download_uses_user_facing_base_url(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
app.config['HXOPS_TOOLS_API_BASE'] = 'http://192.168.100.230:8890'
app.config['HXOPS_PUBLIC_BASE_URL'] = 'http://ai.well-trust.com:8890'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-EXCEL-DOMAIN',
schedule_task_id=task.id,
status='success',
trigger_type='manual',
excel_file_name='result.xlsx',
excel_file_data=b'xlsx-bytes',
excel_file_size=10,
)
db.session.add(run)
db.session.commit()
run_id = run.id
query_res = client.get(f'/api/file-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
download_url = query_res.get_json()['run']['excel']['download_url']
assert download_url.startswith('http://ai.well-trust.com:8890/api/file-check/tools/runs/')
assert '192.168.100.230' not in download_url
def test_file_check_tool_excel_download_works_without_tool_api_key(app, client):
"""浏览器 Excel 下载仅依赖 JWT,不应要求 INTEGRATION_API_KEY 已配置。"""
with app.app_context():
app.config['FILE_CHECK_TOOL_API_KEY'] = ''
app.config['INTEGRATION_API_KEY'] = ''
app.config['SECRET_KEY'] = 'download-signing-secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-EXCEL-NO-KEY',
schedule_task_id=task.id,
status='success',
trigger_type='manual',
excel_file_name='result.xlsx',
excel_file_data=b'xlsx-bytes',
excel_file_size=10,
)
db.session.add(run)
db.session.commit()
run_id = run.id
query_res = client.get(f'/api/file-check/tools/runs/{run_id}')
assert query_res.status_code == 503
with app.app_context():
run = db.session.get(ScheduleRun, run_id)
from app.api.file_check_tools import _build_excel_download_url
download_url = _build_excel_download_url(run)
download_path = download_url[download_url.index('/api/file-check'):]
res = client.get(download_path)
assert res.status_code == 200
assert res.data == b'xlsx-bytes'
def test_file_check_tool_excel_download_invalid_token_returns_invalid_auth(app, client):
with app.app_context():
app.config['SECRET_KEY'] = 'download-signing-secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-EXCEL-BAD-TOKEN',
schedule_task_id=task.id,
status='success',
trigger_type='manual',
excel_file_name='result.xlsx',
excel_file_data=b'xlsx-bytes',
excel_file_size=10,
)
db.session.add(run)
db.session.commit()
run_id = run.id
res = client.get(f'/api/file-check/tools/runs/{run_id}/excel?token=not-a-valid-token')
assert res.status_code == 401
assert res.get_json()['error_code'] == 'invalid_auth'
def test_file_check_tool_excel_download_uses_signed_token(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
+9 -1
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import importlib.util
import json
import os
import re
import sys
from pathlib import Path
@@ -69,9 +70,10 @@ def test_env_strips_wrapping_quotes(monkeypatch):
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
"""配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件。"""
"""配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "logs" / "worker.log"
timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ")
monkeypatch.setenv("FREIGHT_RPA_LOG_FILE", str(log_path))
original_stdout = sys.stdout
@@ -91,10 +93,16 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
assert resolved == log_path
assert "hello stdout" in captured.out
assert "hello stderr" in captured.err
assert timestamp_pattern.search(captured.out)
assert timestamp_pattern.search(captured.err)
text = log_path.read_text(encoding="utf-8")
assert "[logging] tee enabled" in text
assert "hello stdout" in text
assert "hello stderr" in text
# 断言:每行非空日志均带 YYYY-MM-DD HH:MM:SS 前缀,便于长批次排障。
for line in text.splitlines():
if line.strip():
assert timestamp_pattern.match(line)
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
@@ -122,6 +122,11 @@ def test_dsv_report_has_inventory_data_rows_false_when_table_has_only_three_rows
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is False
frame.evaluate.assert_called_once()
probe_js = frame.evaluate.call_args.args[0]
assert "#Report_table" in probe_js
assert "ReportViewerMain_ctl08" in probe_js
assert "directBodyRows" in probe_js
assert "isWarehouseCodeOnly" in probe_js
def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monkeypatch):
@@ -133,6 +138,8 @@ def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monk
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is True
frame.evaluate.assert_called_once()
probe_js = frame.evaluate.call_args.args[0]
assert "isInventoryDetailRow" in probe_js
def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch):