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

+1 -1
View File
@@ -1002,7 +1002,7 @@ def get_chat_messages():
continue
assistant_msg = {
'role': 'assistant',
'content': log.answer,
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
'chat_log_id': log.id,
'retriever_resources': log.retriever_resources or [],
'attribution_parts': log.attribution_parts or [],
+68 -22
View File
@@ -27,13 +27,19 @@ from app.core.errors import (
)
from app.models import ScheduleRun, ScheduleTask
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
from app.services.schedule import _build_srm_conn_str
from app.services.schedule.query_service import get_run, serialize_run
from app.services.schedule.srm_service import _fetch_records
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
try:
import pyodbc # type: ignore
except Exception: # pragma: no cover
pyodbc = None
file_check_bp = Blueprint("file_check_tools", __name__)
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
@@ -41,13 +47,13 @@ _RUN_START_LOCK = threading.Lock()
_TASK_LOCK_KEY_BASE = 8700000000
def _tool_token_secret() -> str:
return str(
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or current_app.config.get("SECRET_KEY")
or "default-secret"
).strip()
def _download_token_secret() -> str:
"""
Excel 下载 JWT 签名密钥。
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
"""
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
def _decode_download_token(token: str | None) -> dict | None:
@@ -57,7 +63,7 @@ def _decode_download_token(token: str | None) -> dict | None:
try:
import jwt
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
return payload if isinstance(payload, dict) else None
except Exception as exc:
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
@@ -65,6 +71,20 @@ def _decode_download_token(token: str | None) -> dict | None:
def _require_tool_auth() -> None:
"""
校验 Tool API 访问权限。
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
"""
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
if request.path.endswith("/excel"):
query_token = str(request.args.get("token") or "").strip()
if query_token:
if _decode_download_token(query_token):
return
raise UnauthorizedError("invalid_auth")
# [STEP 2] Dify / RPA 服务端调用
configured = str(
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
@@ -77,13 +97,11 @@ def _require_tool_auth() -> None:
)
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
if configured in {api_token, integration_key}:
return
if request.path.endswith("/excel") and _decode_download_token(request.args.get("token")):
return
if not token and not integration_key:
if not api_token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
@@ -104,6 +122,8 @@ def _tool_error_code(exc: AppError) -> str:
"dify_retrieve_failed",
}:
return message
if exc.code == "data_source_unavailable":
return "data_source_unavailable"
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
@@ -128,7 +148,8 @@ def _handle_tool_app_error(exc: AppError):
def _public_base_url() -> str:
return resolve_HXOPS_TOOLS_API_BASE()
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
return resolve_hxops_user_facing_base_url()
def _acquire_task_start_lock(task_id: int) -> None:
@@ -148,7 +169,7 @@ def _build_excel_download_url(run: ScheduleRun) -> str:
"run_id": run.id,
"exp": int(time.time()) + 600,
}
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
@@ -309,12 +330,30 @@ def _build_no_data_response(task: ScheduleTask) -> dict:
}
def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
"""
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
"""
current_app.logger.warning(
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
task.id,
exc,
exc_info=True,
)
raise ServiceUnavailableError(
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
code="data_source_unavailable",
) from exc
def _precheck_no_data(task: ScheduleTask) -> dict | None:
"""
启动前预检当前任务是否存在待检资料。
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
避免创建空批次并向 ChatLog 回写 run_id。
避免创建空批次并向 ChatLog 回写 run_id。数据源连接失败时抛 503 data_source_unavailable。
"""
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
return None
@@ -323,12 +362,19 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
if not cfg or not str(cfg.fetch_sql or "").strip():
return None
if cfg.data_source and not cfg.data_source.is_empty():
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
try:
if cfg.data_source and not cfg.data_source.is_empty():
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
rows = _fetch_records(conn_str, cfg.fetch_sql)
except RuntimeError as exc:
_raise_data_source_unavailable(task, exc)
except Exception as exc:
if pyodbc is not None and isinstance(exc, pyodbc.Error):
_raise_data_source_unavailable(task, exc)
raise
rows = _fetch_records(conn_str, cfg.fetch_sql)
if rows:
return None
return _build_no_data_response(task)
+4 -1
View File
@@ -119,9 +119,12 @@ class Config:
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠,应为域名)
HXOPS_PUBLIC_BASE_URL = os.getenv('HXOPS_PUBLIC_BASE_URL')
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
+97 -19
View File
@@ -134,6 +134,98 @@ class DifyService:
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
@staticmethod
def _merge_stream_answer_text(
streamed_text: str,
terminal_answer: str | None,
*,
replace_answer: bool = False,
) -> str:
"""
合并流式增量文本与终态 answer,避免 Dify 结束事件重复携带整段正文导致落库翻倍。
核心逻辑:与前端 useChat.ts 终态事件去重策略保持一致。
Args:
streamed_text: message 事件累积的增量文本。
terminal_answer: message_end / workflow_finished 携带的 answer。
replace_answer: 为 True 时仅使用终态 answer。
Returns:
去重后的最终正文。
"""
current_content = str(streamed_text or '')
terminal = str(terminal_answer or '')
if replace_answer and terminal.strip():
return terminal.strip()
if not terminal:
return current_content.strip()
if not current_content.strip():
return terminal.strip()
current_stripped = current_content.strip()
terminal_stripped = terminal.strip()
if (
terminal_stripped
and current_stripped
and len(terminal_stripped) >= len(current_stripped)
and current_stripped in terminal_stripped
):
return terminal_stripped
if terminal_stripped and current_stripped and terminal_stripped in current_stripped:
return current_stripped
return (current_content + terminal).strip()
@staticmethod
def _build_final_answer_text(
*,
streamed_parts: list[str],
data: dict,
event_name: str,
) -> str:
"""
根据流式片段与终态事件组装最终落库 answer。
核心逻辑:先走 _merge_stream_answer_text 去重;workflow_finished 无 answer 时回退 outputs。
"""
streamed_text = ''.join(streamed_parts)
terminal = str(data.get('answer') or '') if data.get('answer') else ''
answer_text = DifyService._merge_stream_answer_text(
streamed_text,
terminal or None,
replace_answer=bool(data.get('replace_answer')),
)
if not answer_text and event_name == 'workflow_finished':
wf_data = data.get('data') or {}
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
if isinstance(outputs, dict):
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
value = outputs.get(key)
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
if not answer_text:
for value in outputs.values():
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
return answer_text
@staticmethod
def _dedupe_exact_doubled_text(text: str) -> str:
"""
修复历史落库时将同一段正文原样拼接两次的记录。
核心逻辑:仅当整段文本可被均分为两段完全相同子串时才裁剪。
"""
normalized = str(text or '')
stripped = normalized.strip()
if len(stripped) < 2:
return normalized
half = len(stripped) // 2
if len(stripped) % 2 == 0 and stripped[:half] == stripped[half:]:
return stripped[:half]
return normalized
@staticmethod
def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None:
if not isinstance(data, dict):
@@ -896,25 +988,11 @@ class DifyService:
return result
def build_final_answer_text(data: dict, event_name: str) -> str:
answer_text = ''.join(full_answer).strip()
if data.get('answer'):
answer_text = (answer_text + str(data.get('answer') or '')).strip()
if not answer_text and event_name == 'workflow_finished':
wf_data = data.get('data') or {}
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
if isinstance(outputs, dict):
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
value = outputs.get(key)
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
if not answer_text:
for value in outputs.values():
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
return answer_text
return DifyService._build_final_answer_text(
streamed_parts=full_answer,
data=data,
event_name=event_name,
)
max_retries = 3
@@ -108,6 +108,9 @@
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
},
"503": {
"$ref": "#/components/responses/DataSourceUnavailable"
}
}
}
@@ -533,7 +536,8 @@
"properties": {
"task_id": {
"type": "integer",
"example": 12
"example": 12,
"description": "检核任务 ID(ScheduleTask.id);绑定 解析运行态上下文.task_id_int(Number),勿绑意图识别.task_id"
},
"trigger_source": {
"type": "string",
@@ -561,7 +565,7 @@
"required": [
"task_id"
],
"description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
},
"RunCheckSuccessResponse": {
"type": "object",
@@ -887,6 +891,21 @@
}
}
}
},
"DataSourceUnavailable": {
"description": "检核数据源不可用(ODBC/SQL Server 连接失败或 SRM 环境变量未配置)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "data_source_unavailable",
"message": "检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动"
}
}
}
}
}
}
+53 -11
View File
@@ -1,23 +1,42 @@
"""
backend/app/services/hxops_tool_api.py
文件用途:解析 HXOPS 对外 Tool API 基地址(Dify Chatflow / OpenAPI / 签名下载链接)。
用途:解析 HXOPS 两类对外基地址——Dify Tool API(服务端)与用户浏览器访问(下载链等)。
依赖:Flask current_app / request。
逻辑:Dify/RPA 调 Tool API 走 resolve_HXOPS_TOOLS_API_BASE;用户可见下载链走 resolve_hxops_user_facing_base_url。
"""
from __future__ import annotations
from flask import current_app, has_request_context, request
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
"""返回无尾斜杠的 hxops 对外根地址,如 http://192.168.100.192:8891。"""
cfg = config
if cfg is None and current_app:
cfg = current_app.config
cfg = cfg or {}
def _resolve_config(config: dict | None = None) -> dict:
"""读取 Flask config 或空 dict。"""
if config is not None:
return config
if current_app:
return current_app.config
return {}
for key in ("HXOPS_TOOLS_API_BASE", "HXOPS_TOOLS_API_BASE", "PUBLIC_BASE_URL"):
configured = str(cfg.get(key) or "").strip().rstrip("/")
if configured:
return configured
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
"""
返回 Dify / RPA 等服务端调用 Tool API 时使用的根地址(无尾斜杠)。
核心逻辑:仅读 HXOPS_TOOLS_API_BASE(常为内网 IP),与浏览器下载链、PUBLIC_BASE_URL 分离。
Args:
config: 可选配置字典;缺省时读 current_app.config。
request_host: 可选请求 host_url;缺省且在请求上下文中时取 request.host_url。
Returns:
无尾斜杠的根地址,如 http://192.168.100.192:8890。
"""
cfg = _resolve_config(config)
configured = str(cfg.get("HXOPS_TOOLS_API_BASE") or "").strip().rstrip("/")
if configured:
return configured
host = request_host
if host is None and has_request_context():
@@ -25,3 +44,26 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
return host or ""
def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
"""
返回浏览器侧可访问的根地址,用于 Excel 签名下载等用户可见链接。
核心逻辑:仅读 HXOPS_PUBLIC_BASE_URL / WECOM_PUBLIC_BASE_URL,不复用 Tool API 内网地址或通知地址。
Args:
config: 可选配置字典;缺省时读 current_app.config。
Returns:
无尾斜杠的根地址,如 https://ai.example.com。
"""
cfg = _resolve_config(config)
for key in ("HXOPS_PUBLIC_BASE_URL", "WECOM_PUBLIC_BASE_URL"):
configured = str(cfg.get(key) or "").strip().rstrip("/")
if configured:
return configured
if has_request_context():
return request.host_url.rstrip("/")
return resolve_HXOPS_TOOLS_API_BASE(config=cfg)
@@ -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):