Merge branch 'hugo-shipping-notice' into test

This commit is contained in:
hugo committed 2026-09-19 16:08:52 +08:00
commit 76583c4e5a
98 files changed
+2202 -1475

No files matched your search

+19 -4
View File
@@ -154,6 +154,21 @@ def _require_formal_notice(task: Any) -> ShippingNotice:
return task
def _require_editable_task(task: Any) -> Any:
"""订单编辑写接口的实体守卫:正式 Notice 或建单前 OT 均可。
核心逻辑:订单字段/行的编辑权限由服务层状态制闸门裁决
(Excel ready 硬冻结 + 活动 Attempt 忙碌锁 + Schema 反向锁),
与实体类型无关——通知准备阶段(Notice 未建)编辑履约字段是受支持场景。
"""
if not isinstance(task, (ShippingNotice, ShippingOrderTask)):
raise ValidationError(
'Formal shipping notice is required for this operation',
code='SHIPPING.FORMAL_NOTICE_REQUIRED',
)
return task
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""分页列出当前用户可见的发货任务,可按处理状态过滤。"""
@@ -660,7 +675,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
fields = data.get('fields')
if not isinstance(fields, dict) or not fields:
@@ -707,7 +722,7 @@ def workspace_update_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get('line_index'))
@@ -796,7 +811,7 @@ def workspace_add_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
line = data.get('line')
if not isinstance(line, dict) or not line:
@@ -822,7 +837,7 @@ def workspace_remove_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get('line_index'))
+58 -112
View File
@@ -8,7 +8,6 @@ backend/app/core/config/settings.py
旧路径 app.config 为兼容 shim。
"""
import os
import warnings
from pathlib import Path
from dotenv import dotenv_values
@@ -16,18 +15,6 @@ from dotenv import dotenv_values
_BACKEND_DIR = Path(__file__).resolve().parents[3]
_ROOT_DIR = _BACKEND_DIR.parent
_WARNED_LEGACY_RPA_ENV: set[str] = set()
_RPA_LEGACY_TO_CANONICAL = {
'SHIPPING_RPA_CREDENTIAL_KEY': 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY',
'FREIGHT_INVENTORY_DROP_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR',
'FREIGHT_RPA_INVENTORY_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR',
'FREIGHT_UPLOAD_QUEUE_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR',
'FREIGHT_RPA_UPLOAD_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR',
'FREIGHT_RPA_BROWSER_PROFILE_DIR': 'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR',
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR': 'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR',
'FREIGHT_RPA_MOCK': 'SHIPPING_NOTICE_RPA_WORKER_MOCK',
}
def _normalize_env_name(raw: str | None) -> str:
@@ -90,47 +77,15 @@ def _backend_path(env_key: str, *parts: str) -> str:
return resolve_backend_relative_path(os.getenv(env_key), default)
def _rpa_env(canonical_name: str, default: str | None = None) -> str | None:
def _rpa_data_path(env_key: str, *parts: str) -> str:
"""
读取 Shipping Notice RPA 配置,并在迁移期兼容历史环境变量名。
解析 RPA 数据目录环境变量,未配置时回落到 `backend/data` 默认路径。
核心逻辑:优先读取 `SHIPPING_NOTICE_RPA_*`;仅在新变量缺失时读取映射的
历史变量,并按进程对每个旧名称最多发出一次弃用警告。
核心逻辑:直接读取规范环境变量名(FREIGHT_RPA_*);历史
SHIPPING_NOTICE_RPA_* 前缀已于 2026-09-18 废弃,不提供别名兼容。
Args:
canonical_name: 统一后的规范环境变量名。
default: 新旧变量均未设置时返回的默认值。
Returns:
str | None: 环境变量值或默认值。
"""
value = os.getenv(canonical_name)
if value is not None:
return value
legacy_name = next(
(legacy for legacy, canonical in _RPA_LEGACY_TO_CANONICAL.items() if canonical == canonical_name),
None,
)
if legacy_name:
value = os.getenv(legacy_name)
if value is not None:
if legacy_name not in _WARNED_LEGACY_RPA_ENV:
warnings.warn(
f'{legacy_name} is deprecated; use {canonical_name}',
DeprecationWarning,
stacklevel=2,
)
_WARNED_LEGACY_RPA_ENV.add(legacy_name)
return value
return default
def _rpa_data_path(canonical_name: str, *parts: str) -> str:
"""
解析 RPA 数据目录,并兼容历史环境变量名称。
Args:
canonical_name: 统一后的 RPA 目录环境变量名。
env_key: 规范 RPA 目录环境变量名。
*parts: 未配置时相对 `backend/data` 的默认路径片段。
Returns:
@@ -139,7 +94,7 @@ def _rpa_data_path(canonical_name: str, *parts: str) -> str:
from app.path_utils import resolve_backend_relative_path
default = _BACKEND_DIR.joinpath('data', *parts)
return resolve_backend_relative_path(_rpa_env(canonical_name), default)
return resolve_backend_relative_path(os.getenv(env_key), default)
class Config:
@@ -310,9 +265,7 @@ class Config:
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# RPA Profile 凭据字段的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = _rpa_env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY')
# 兼容仍从 Flask config 读取旧属性的扩展;新代码禁止继续使用该属性。
SHIPPING_RPA_CREDENTIAL_KEY = SHIPPING_NOTICE_RPA_CREDENTIAL_KEY
FREIGHT_RPA_CREDENTIAL_KEY = os.getenv('FREIGHT_RPA_CREDENTIAL_KEY')
# 文件检核 Chatflow Tool API
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
@@ -425,46 +378,46 @@ class Config:
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
)
SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED = (
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
in {'1', 'true', 'yes', 'on'}
if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
if os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip()
SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = (
os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
FREIGHT_RPA_SHARED_SCOPE_ID = os.getenv('FREIGHT_RPA_SHARED_SCOPE_ID', '').strip()
FREIGHT_RPA_SHARED_SENTINEL_NAME = (
os.getenv('FREIGHT_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
or '.hxops_rpa_shared_mount'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
FREIGHT_RPA_WORKER_ALERT_ENABLED = (
os.getenv('FREIGHT_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv(
'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', ''
FREIGHT_RPA_WORKER_ALERT_USERNAMES = os.getenv(
'FREIGHT_RPA_WORKER_ALERT_USERNAMES', ''
).strip()
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
os.getenv('FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
)
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
@@ -481,9 +434,9 @@ class Config:
)
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
)
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
@@ -496,39 +449,32 @@ class Config:
)
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', 'shipping_notice', 'freight_rpa', 'inventory_drop'
# RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop'
)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'inventory_triggers'
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers'
)
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_drop'
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop'
)
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_triggers'
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers'
)
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR', 'shipping_notice', 'freight_rpa', 'upload_queue'
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'inventory', 'upload_queue'
)
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'upload_triggers'
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'inventory', 'upload_triggers'
)
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR', 'shipping_notice', 'freight_rpa', 'browser_profile'
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
)
SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', 'shipping_notice', 'freight_rpa', 'inventory_archives'
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
)
SHIPPING_NOTICE_RPA_WORKER_MOCK = _rpa_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')
# 旧 Flask config 属性仅用于过渡期测试和外部扩展兼容。
FREIGHT_INVENTORY_DROP_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR
FREIGHT_UPLOAD_QUEUE_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR
FREIGHT_RPA_BROWSER_PROFILE_DIR = SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR
FREIGHT_RPA_MOCK = SHIPPING_NOTICE_RPA_WORKER_MOCK
FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false')
# WeCom (企业微信) 登录配置
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
@@ -789,8 +735,8 @@ class DevelopmentConfig(Config):
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = True
# 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# XFA 拆分确认 JTI:仅单进程 development 允许内存消费;test/prod 多 Worker 必须 Redis
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
@@ -810,8 +756,8 @@ class TestingConfig(Config):
FIXED_ASSETS_SYNC_ENABLED = False
FIXED_ASSETS_EXPORT_TO_DOCS = False
ENV_NAME = 'dev'
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# pytest 单进程:允许内存 JTI;生产语义由 ProductionConfig 关闭
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
@@ -68,7 +68,7 @@ def recover_stale_waiting_source_jobs() -> int:
from flask import current_app
try:
timeout = max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
timeout = max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
timeout = 900
cutoff = datetime.utcnow() - timedelta(seconds=timeout)
@@ -79,7 +79,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
def _receipt_timeout_seconds() -> int:
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
try:
return max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
return max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
return 900
@@ -39,14 +39,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
def get_inventory_archive_dir() -> str:
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
archive_dir = Path(
current_app.config.get("SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR")
current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
if current_app
else ""
)
if not str(archive_dir):
from app.core.config.settings import Config
archive_dir = Path(Config.SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR)
archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
@@ -251,7 +251,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != ".zip":
@@ -272,7 +272,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
@@ -19,7 +19,10 @@ from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
from app.services.shipping_notice.rpa_worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_inventory_rpa_worker_ready,
)
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -121,6 +124,8 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
try:
# 写 trigger 前强制就绪检查:worker 离线立即 failed,不进入 awaiting_rpa_callback。
assert_inventory_rpa_worker_ready()
trigger_path = write_inventory_export_batch_trigger(
run_no,
sources,
@@ -26,17 +26,17 @@ def _fernet() -> Fernet:
Raises:
ServiceUnavailableError: 未配置或配置了无效的主密钥。
"""
key = str(current_app.config.get('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') or '').strip()
key = str(current_app.config.get('FREIGHT_RPA_CREDENTIAL_KEY') or '').strip()
if not key:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is not configured',
'FREIGHT_RPA_CREDENTIAL_KEY is not configured',
code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING',
)
try:
return Fernet(key.encode('ascii'))
except (ValueError, UnicodeEncodeError) as exc:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is invalid',
'FREIGHT_RPA_CREDENTIAL_KEY is invalid',
code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
) from exc
@@ -420,7 +420,7 @@ def _auto_upload_enabled() -> bool:
def _rpa_upload_timeout_seconds() -> int:
"""货代上传 RPA 等待回调超时秒数。"""
try:
return max(int(current_app.config.get('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or 30), 1)
return max(int(current_app.config.get('FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS') or 30), 1)
except (TypeError, ValueError):
return 30
@@ -219,7 +219,7 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站
等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。
"""
timeout = max(1, int(current_app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS']))
timeout = max(1, int(current_app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS']))
runs = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
@@ -357,7 +357,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
db.session.commit()
return _payload(run)
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
# SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
# FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
raw_file_path = str(payload.get('file_path') or '').strip()
path: Path | None = None
from app.services.shipping_notice.rpa import inventory_drop_dir
@@ -56,11 +56,11 @@ def callback_quarantine_dir() -> Path | None:
def callback_cleanup_max_attempts() -> int:
"""cleanup job 最大重试次数(SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
"""cleanup job 最大重试次数(FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
try:
return max(
1,
int(current_app.config.get("SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
int(current_app.config.get("FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
)
except (TypeError, ValueError):
return _DEFAULT_MAX_CLEANUP_ATTEMPTS
@@ -117,7 +117,7 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
scheduled_at = next_inventory_rpa_recheck_at(task)
if scheduled_at is None:
recheck_seconds = max(
float(current_app.config.get('SHIPPING_NOTICE_RPA_WAIT_RECHECK_SECONDS', 10) or 10),
float(current_app.config.get('FREIGHT_RPA_WAIT_RECHECK_SECONDS', 10) or 10),
1,
)
scheduled_at = datetime.utcnow() + timedelta(seconds=recheck_seconds)
@@ -26,7 +26,7 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
def _read_receipt_callback_file(file_path: str) -> bytes:
"""只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。"""
configured_root = str(current_app.config.get('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip()
configured_root = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip()
if not configured_root:
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
root = Path(configured_root).resolve()
@@ -14,7 +14,7 @@ from flask import current_app
def receipt_trigger_dir() -> Path | None:
"""返回收料专用 trigger 目录;绝不回落到库存 trigger 目录。"""
value = str(current_app.config.get('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR') or '').strip()
value = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR') or '').strip()
return Path(value) if value else None
+6 -6
View File
@@ -37,7 +37,7 @@ def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | b
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
if mode in {"browser", "mock"}:
return _runtime_summary(mode)
raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") or "false").strip().lower()
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower()
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
@@ -49,8 +49,8 @@ def _path(key: str) -> Path | None:
def inventory_drop_dir() -> Path | None:
"""RPA 库存 Excel 落盘目录(SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR)。"""
return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR")
"""RPA 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR)。"""
return _path("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR")
def inventory_processed_dir() -> Path | None:
@@ -63,7 +63,7 @@ def inventory_processed_dir() -> Path | None:
def inventory_trigger_dir() -> Path | None:
"""RPA 库存导出触发 JSON 目录。"""
return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR")
return _path("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR")
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
@@ -82,12 +82,12 @@ def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
def upload_queue_dir() -> Path | None:
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。"""
return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR")
return _path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR")
def upload_trigger_dir() -> Path | None:
"""RPA 货代上传触发 JSON 目录。"""
return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR")
return _path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR")
def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
@@ -86,8 +86,8 @@ def upload_rpa_attempts(task: ShippingNotice | None) -> int:
def max_rpa_upload_attempts() -> int:
"""RPA 货代上传最大重试次数(环境变量 SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS)。"""
value = os.getenv("SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS")
"""RPA 货代上传最大重试次数(环境变量 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS)。"""
value = os.getenv("FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS")
if value is None or not str(value).strip():
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
try:
@@ -39,6 +39,7 @@ _MEMORY_LOCK = threading.Lock()
_REASON_USER_HINTS: dict[str, str] = {
"no_worker_heartbeat": "未收到任何 Worker 心跳",
"heartbeat_store_process_local": "未配置 REDIS_URL(或 Redis 不可达),心跳存储为本进程内存,跨进程不可见;请配置 REDIS_URL 或设 FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED=false 跳过心跳检查",
"heartbeat_storage_unavailable": "心跳存储不可用(Redis)",
"trigger_dir_not_configured": "后端未配置 trigger 目录",
"trigger_dir_not_accessible": "trigger 目录不存在或不可访问",
@@ -48,7 +49,7 @@ _REASON_USER_HINTS: dict[str, str] = {
"environment_mismatch": "Worker 环境与后端环境不一致",
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力",
"credential_key_missing": "未配置 SHIPPING_NOTICE_RPA_CREDENTIAL_KEY",
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
"callback_api_base_missing": "未配置 Worker 回调可达的 API 基址",
@@ -91,9 +92,9 @@ def _config_str(key: str, default: str = "") -> str:
def _heartbeat_ttl_seconds() -> int:
raw = 90
if current_app:
raw = int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or 90)
raw = int(current_app.config.get("FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or 90)
else:
raw = int(os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or "90")
raw = int(os.getenv("FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or "90")
return max(60, raw)
@@ -101,16 +102,16 @@ def _heartbeat_check_required() -> bool:
"""Mock RPA 或显式关闭时跳过 worker 心跳就绪检查。"""
if rpa_runtime_mode().get("mock"):
return False
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED", True)
return _config_bool("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED", True)
def _heartbeat_redis_required() -> bool:
"""test/prod 默认要求 Redis;dev 仅显式开启时要求。"""
explicit = os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
explicit = os.getenv("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
if explicit is not None and str(explicit).strip() != "":
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS", False)
return _config_bool("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS", False)
if current_app:
configured = current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
configured = current_app.config.get("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS")
if configured is not None:
return bool(configured)
env_name = resolve_backend_rpa_environment()
@@ -118,7 +119,7 @@ def _heartbeat_redis_required() -> bool:
def _heartbeat_allow_memory_fallback() -> bool:
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK", False)
return _config_bool("FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK", False)
def resolve_backend_rpa_environment() -> str:
@@ -131,7 +132,7 @@ def resolve_backend_rpa_environment() -> str:
def shared_scope_id() -> str:
"""共享 SMB 目录逻辑标识(如 hxops-rpa-test-data),用于跨平台路径对齐。"""
explicit = _config_str("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "")
explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "")
if explicit:
return explicit
trigger_dir = inventory_trigger_dir()
@@ -145,7 +146,7 @@ def shared_scope_id() -> str:
def shared_sentinel_name() -> str:
return _config_str("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME", ".hxops_rpa_shared_mount")
return _config_str("FREIGHT_RPA_SHARED_SENTINEL_NAME", ".hxops_rpa_shared_mount")
def _shared_mount_check_required() -> bool:
@@ -208,9 +209,21 @@ def _memory_list_workers() -> list[dict[str, Any]]:
def reset_rpa_worker_heartbeat_state_for_tests() -> None:
"""单测隔离:清空进程内内存心跳缓存。"""
"""单测隔离:清空进程内内存心跳缓存,并尽力清除 Redis 中的持久心跳记录。"""
with _MEMORY_LOCK:
_MEMORY_STORE.clear()
try:
client = _redis_client()
if client is None:
return
worker_ids = list(client.smembers(_REDIS_INDEX_KEY) or [])
stale_worker_keys = [f"{_REDIS_WORKER_KEY_PREFIX}{worker_id}" for worker_id in worker_ids]
if stale_worker_keys:
client.delete(*stale_worker_keys)
client.delete(_REDIS_INDEX_KEY)
except Exception:
# 隔离辅助尽力而为:Redis 不可用时内存清空已足够单测运行。
pass
def _redis_store_worker(worker: dict[str, Any]) -> bool:
@@ -517,6 +530,10 @@ def _check_rpa_worker_ready_for_capability(
if not workers and "heartbeat_storage_unavailable" not in reasons:
reasons.append("no_worker_heartbeat")
if _redis_client() is None and not eligible_workers:
# 无 Redis 时心跳存储为本进程内存:写方(API 进程收 Worker POST)与读方(排程/告警进程)
# 互不可见,本地排程必然命中 no_worker_heartbeat;追加原因码提示存储模式与本地测试姿势。
reasons.append("heartbeat_store_process_local")
mount_block_tokens = {
"trigger_dir_not_configured",
@@ -583,7 +600,7 @@ def _freight_upload_config_reasons() -> list[str]:
from app.services.shipping_notice.rpa import upload_queue_dir, upload_trigger_dir
reasons: list[str] = []
credential_key = _config_str("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", "")
credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "")
if not credential_key:
reasons.append("credential_key_missing")
@@ -46,28 +46,28 @@ def _config_bool(key: str, default: bool) -> bool:
def _alert_enabled() -> bool:
if not _heartbeat_check_required():
return False
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED", False)
return _config_bool("FREIGHT_RPA_WORKER_ALERT_ENABLED", False)
def _alert_cooldown_seconds() -> int:
return max(300, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS") or 1800))
return max(300, int(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS") or 1800))
def _send_lock_seconds() -> int:
"""企微发送中的短锁 TTL;发送失败过期后可重试,不进入长冷却。"""
return max(60, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS") or 120))
return max(60, int(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS") or 120))
def _alert_fallback_admin_enabled() -> bool:
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN", True)
return _config_bool("FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN", True)
def _alert_recipients() -> list[User]:
"""
解析告警接收人。
核心逻辑:优先 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。
核心逻辑:优先 FREIGHT_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。
"""
raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES") or "").strip()
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_USERNAMES") or "").strip()
names = [part.strip() for part in raw.split(",") if part.strip()] if raw else []
if names:
users = (
@@ -105,7 +105,7 @@ def _log_recipient_gap_once() -> None:
return
_RECIPIENT_GAP_LOGGED = True
logger.warning(
"[rpa-heartbeat-alert] no wecom recipients: set SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES "
"[rpa-heartbeat-alert] no wecom recipients: set FREIGHT_RPA_WORKER_ALERT_USERNAMES "
"or bind wecom_userid for at least one admin (FALLBACK_ADMIN=true)"
)
@@ -36,7 +36,7 @@ def shipping_recovery_tick() -> int:
# 根据最新 Attempt/Gate 状态刷新按钮与阻断原因。
inventory_timeout_seconds = max(int(getattr(
current_app.config,
'SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS',
'FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS',
900,
) or 900), 1)
inventory_scan_count = _scan_stale_inventory_attempts(
@@ -83,7 +83,7 @@ def auto_rpa_inventory_enabled() -> bool:
def rpa_inventory_timeout_seconds() -> int:
"""RPA 库存导出等待超时秒数。"""
return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 900, min_value=5)
return cfg_int("FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS", 900, min_value=5)
def auto_mapping_allow_llm() -> bool:
+26 -26
View File
@@ -19,7 +19,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSATL01
@@ -41,7 +41,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSAVP01
@@ -62,7 +62,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSAZA01
@@ -83,7 +83,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSCMH01
@@ -105,7 +105,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSCMN01
@@ -127,7 +127,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSEZE01
@@ -149,7 +149,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSFRA01
@@ -170,7 +170,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSGRU01
@@ -191,7 +191,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSIAD01
@@ -212,7 +212,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSJAN01
@@ -233,7 +233,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSLTN01
@@ -254,7 +254,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSMEL01
@@ -275,7 +275,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSNRT01
@@ -296,7 +296,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPHX01
@@ -317,7 +317,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPNE01
@@ -338,7 +338,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPRD01
@@ -359,7 +359,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSPSC01
@@ -380,7 +380,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSQRO01
@@ -401,7 +401,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSRIC01
@@ -422,7 +422,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSRNO01
@@ -443,7 +443,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSRUH01
@@ -464,7 +464,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSSBN01
@@ -485,7 +485,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSSCL01
@@ -506,7 +506,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSYYZ01
@@ -527,7 +527,7 @@ sources:
report_name: On Hand Inventory By Location 3lv
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single
values:
- BYAWSZAZ01
@@ -580,7 +580,7 @@ sources:
report_name: On Hand Inventory by Location
parameters:
- name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: multi_select
select_all: true
selectors:
+5 -5
View File
@@ -85,8 +85,8 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
return
app = request.getfixturevalue("app")
tmp_path = request.getfixturevalue("tmp_path")
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
)
if request.node.get_closest_marker("auto_rpa"):
@@ -108,9 +108,9 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
app.config["ENV_NAME"] = "dev"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
reset_rpa_worker_heartbeat_state_for_tests()
@@ -158,7 +158,7 @@ def _published_route_field_id() -> str:
def test_profile_credentials_are_not_returned(app):
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
assert payload['password_configured'] is True
@@ -169,7 +169,7 @@ def test_profile_credentials_are_not_returned(app):
def test_profile_rejects_page_operation_configuration(app):
"""货代登录连接不得保存报表路径、selector 或下载策略,防止连接越界成为业务配置源。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = _profile_data()
payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}}
@@ -180,7 +180,7 @@ def test_profile_rejects_page_operation_configuration(app):
def test_multiple_dbs_profiles_bind_independent_sources(app):
"""同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
second = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
@@ -192,7 +192,7 @@ def test_multiple_dbs_profiles_bind_independent_sources(app):
def test_source_rejects_profile_connector_mismatch(app):
"""库存源不能绑定不同 Driver 的 Profile。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
with pytest.raises(ValidationError) as exc_info:
@@ -202,7 +202,7 @@ def test_source_rejects_profile_connector_mismatch(app):
def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
"""禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='DRAFT_SOURCE')
@@ -227,7 +227,7 @@ def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
"""普通保存只能保留停用站点;独立启用动作必须返回尚未完成的测试步骤。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='ACTIVATION_SOURCE')
@@ -250,7 +250,7 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
def test_activation_status_exposes_structured_checks_without_duplicate_test_blocks(app):
"""未测试站点应显示后续验证步骤,但只由测试门禁阻断,避免管理员面对重复待办。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
payload = {
@@ -279,7 +279,7 @@ def test_activation_status_exposes_structured_checks_without_duplicate_test_bloc
def test_enabled_source_rejects_disabled_rpa_profile(app):
"""启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(
{**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None,
@@ -291,7 +291,7 @@ def test_enabled_source_rejects_disabled_rpa_profile(app):
def test_dbs_source_persists_report_path_parameters_and_aliases(app):
"""数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
@@ -303,11 +303,11 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app):
def test_source_rejects_driver_selector_in_business_parameters(app):
"""业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
payload = _source_data(profile['id'])
payload['query_parameters_json'][0]['selector_env'] = 'SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
payload['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
@@ -315,7 +315,7 @@ def test_source_rejects_driver_selector_in_business_parameters(app):
def test_crane_source_rejects_dbs_report_path(app):
"""动态仓 Crane 库存源不得误填 DBS 四级报表路径。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
payload = _source_data(profile['id'], code='CRANE', connector_type='crane')
@@ -328,7 +328,7 @@ def test_crane_source_rejects_dbs_report_path(app):
def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app):
"""停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE')
@@ -357,7 +357,7 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a
def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app):
"""批量绑定必须先全量预检;已启用站点阻断时其余站点不能部分写入。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED')
@@ -380,7 +380,7 @@ def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app):
def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app):
"""直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE')
@@ -407,7 +407,7 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app
def test_published_rule_cannot_be_mutated_in_place(app):
"""发布规则必须依靠新版本演进,避免改写历史任务依据。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
@@ -469,7 +469,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
"""未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
shipping_inventory_service.delete_profile(unused['id'])
@@ -500,7 +500,7 @@ def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
"""发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None)
@@ -535,7 +535,7 @@ def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
def test_active_default_external_mapping_is_unique_per_source(app):
"""同一库存源只能有一条启用的默认外部系统映射。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
@@ -550,7 +550,7 @@ def test_active_default_external_mapping_is_unique_per_source(app):
def test_external_mapping_normalizes_freight_warehouse_identity(app):
"""配置端小写货代仓应与库存行大写 Warehouse 使用同一精确映射身份。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
@@ -564,7 +564,7 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app):
def test_upload_config_change_does_not_bump_rpa_profile_version(app):
"""连接级上传配置(upload_config_json)变更不递增 config_version。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
base_version = profile['config_version']
@@ -104,7 +104,7 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
"""deps 默认触发器必须真写 trigger 文件,不得只查配置就返回 ok=True(B1 断线根因)。"""
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
outcome = _DefaultRpaTrigger().trigger(
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
)
+1 -1
View File
@@ -10,7 +10,7 @@ import pytest
def _load_navigation():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_navigation.py"
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "crane_navigation.py"
spec = importlib.util.spec_from_file_location("crane_navigation_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
+36 -5
View File
@@ -10,7 +10,7 @@ import pytest
def _load_export():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_report_export.py"
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "crane_report_export.py"
spec = importlib.util.spec_from_file_location("crane_report_export_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
@@ -47,7 +47,7 @@ def test_fill_parameters_skips_warehouse(monkeypatch):
select_or_fill=_fake_select,
)
assert calls == [("SHIPPING_NOTICE_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
assert calls == [("FREIGHT_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
def test_build_schedule_description_uses_short_uuid_hex(monkeypatch):
@@ -73,7 +73,7 @@ def test_build_schedule_description_hex_len_env():
text = module._build_schedule_description(
{"source_code": "CRANE_TZR2"},
None,
env=lambda name, default="": "16" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
env=lambda name, default="": "16" if name == "FREIGHT_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
)
assert len(text) == 16
@@ -148,7 +148,7 @@ def test_should_run_report_before_schedule_uses_driver_environment_only():
assert (
module._should_run_report_before_schedule(
{"navigation": {}},
env=lambda name, default="": "false" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default,
env=lambda name, default="": "false" if name == "FREIGHT_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default,
)
is False
)
@@ -444,7 +444,7 @@ def test_resolve_download_mode_uses_driver_environment_only():
"""下载模式只能由 Driver 环境变量决定。"""
module = _load_export()
assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report"
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "FREIGHT_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch):
@@ -596,3 +596,34 @@ def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_p
download_dir=str(tmp_path),
)
assert fallback_called["value"] is False
def test_row_matches_scheduled_report_normalizes_name_form(monkeypatch):
"""行名 InboundDetails.xlsx 与期望名 Inbound Details 应规范化后相等(收料轮询 not found 根因)。"""
module = _load_export()
texts = ["InboundDetails.xlsx", "2026/9/18 22:02:53", "accf9483fabe", "Download"]
class _Cell:
def __init__(self, text):
self._text = text
def inner_text(self, timeout=None):
return self._text
cells = MagicMock()
cells.count.return_value = len(texts)
cells.nth.side_effect = lambda i: _Cell(texts[i])
row = MagicMock()
row.locator.return_value = cells
row.is_visible.return_value = True
assert module._row_matches_scheduled_report(
row, description="accf9483fabe", expected_report_name="Inbound Details"
) is True
# [断言意图] 描述不一致时不得匹配(唯一性由 UUID 保证)
assert module._row_matches_scheduled_report(
row, description="other", expected_report_name="Inbound Details"
) is False
assert module._row_matches_scheduled_report(
row, description="accf9483fabe", expected_report_name="OnHandDetails.xlsx"
) is False
+7 -7
View File
@@ -8,7 +8,7 @@ from unittest.mock import MagicMock
def _load_crane_session():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_session.py"
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "crane_session.py"
spec = importlib.util.spec_from_file_location("crane_session_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
@@ -108,15 +108,15 @@ def test_maybe_auto_login_crane_fills_username_password_and_clicks_sign_in(monke
module.maybe_auto_login_crane(
page,
env=lambda name, default="": {
"SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME": "crane-user",
"SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD": "crane-pass",
"FREIGHT_RPA_WORKER_CRANE_USERNAME": "crane-user",
"FREIGHT_RPA_WORKER_CRANE_PASSWORD": "crane-pass",
}.get(name, default),
browser_timeout_ms=5_000,
)
assert calls == [
("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"),
("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"),
("FREIGHT_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"),
("FREIGHT_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"),
]
@@ -133,7 +133,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
locator = module._find_crane_sign_in_button(
page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
selector_env="FREIGHT_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
env=lambda name, default="": default,
browser_timeout_ms=3_000,
)
@@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
"""batch 内 session 有效时不应重复 goto + login。"""
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
assert spec and spec.loader
worker = importlib.util.module_from_spec(spec)
+5 -5
View File
@@ -1,4 +1,4 @@
"""scripts/rpa/dsv_report_parameters.py 单元测试。"""
"""scripts/freight_rpa/dsv_report_parameters.py 单元测试。"""
from __future__ import annotations
@@ -7,7 +7,7 @@ from pathlib import Path
def _load_module():
path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_parameters.py"
path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_parameters.py"
spec = importlib.util.spec_from_file_location("dsv_report_parameters_test", path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
@@ -43,7 +43,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
module.fill_dsv_filter_if_needed(
_FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
"FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
"Owner",
"CADU-0000000100",
env=lambda name, default="": default,
@@ -104,7 +104,7 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue():
module.fill_dsv_filter_if_needed(
_FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse",
"BYAWSATL01",
env=lambda name, default="": default,
@@ -290,7 +290,7 @@ def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value():
module.fill_dsv_filter_if_needed(
_FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse",
"RTM",
env=lambda name, default="": default,
@@ -99,7 +99,7 @@ def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
with app.app_context():
allowed_root = tmp_path / 'receipt-drop'
allowed_root.mkdir()
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
outside = tmp_path / 'outside.xlsx'
outside.write_bytes(b'not-a-real-xlsx')
@@ -76,7 +76,7 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
with app.app_context():
app.config['SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
@@ -100,7 +100,7 @@ def test_receipt_trigger_is_published_atomically(app, tmp_path):
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
with app.app_context():
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
written = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'receipt:atomic'}])
assert written is not None
@@ -7,18 +7,18 @@ from pathlib import Path
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
assert 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR' in text
assert 'shipping_receipt_rpa.v1' in text
assert '/api/shipping-notice/rpa/receipt-batch-ready' in text
assert 'freight_rpa_worker' not in text
assert 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
assert 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
def test_receipt_crane_driver_forces_inbound_details_match_name():
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。"""
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
receipt_driver = (root / 'receipt' / 'receipt_crane_export.py').read_text(encoding='utf-8')
crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8')
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver
@@ -27,7 +27,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name():
def test_receipt_crane_driver_forces_inbound_details_entry_route():
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。"""
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
module_path = root / 'receipt' / 'receipt_crane_export.py'
sys.path.insert(0, str(root))
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path)
@@ -45,7 +45,7 @@ def test_receipt_crane_driver_forces_inbound_details_entry_route():
def test_receipt_worker_uses_common_trigger_consumer():
"""收料 Worker 必须复用公共 claim/归档原语,不再自建目录搬移实现。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'claim_trigger' in text
assert 'archive_trigger' in text
assert "path.replace(claimed)" not in text # 领取逻辑收敛到公共模块
@@ -53,7 +53,7 @@ def test_receipt_worker_uses_common_trigger_consumer():
def test_receipt_worker_logs_full_lifecycle_and_banner():
"""收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'configure_file_logging' in text
assert 'maybe_rotate_open_log' in text
assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段
@@ -64,7 +64,36 @@ def test_receipt_worker_logs_full_lifecycle_and_banner():
def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
"""收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
assert 'SHIPPING_NOTICE_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
def test_receipt_register_script_mirrors_inventory_with_distinct_identity():
"""收料计划任务注册脚本与库存同构(AtLogOn+Interactive+headless),任务名独立可同机并存。"""
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
receipt = (root / 'receipt' / 'register_receipt_worker_tasks.ps1').read_text(encoding='utf-8')
inventory = (root / 'inventory' / 'register_inventory_worker_tasks.ps1').read_text(encoding='utf-8')
# [断言意图] 任务名赋值行必须指向 Receipt;docstring 允许提及库存任务名(并排设计说明),功能段不得引用
assert '$TestTask = "HXOPS Receipt RPA Worker TEST"' in receipt
assert '$ProdTask = "HXOPS Receipt RPA Worker PROD"' in receipt
assert 'HXOPS Inventory RPA Worker TEST' in inventory and 'HXOPS Receipt RPA Worker' not in inventory
# [断言意图] 动作必须指向收料启动脚本,且不得把库存启动脚本带进收料注册
assert 'start_receipt_worker.ps1' in receipt and 'start_inventory_worker.ps1' not in receipt
# [断言意图] 形状约束与库存同款:AtLogOn + Interactive + headless + 隐藏控制台
assert 'AtLogOn' in receipt and 'Interactive' in receipt and 'Headless' in receipt and 'WindowStyle Hidden' in receipt
def test_receipt_worker_supports_opt_in_session_reuse():
"""收料 Worker 支持可选跨批次会话复用:ps1 注入开关,worker 按 env 切换持久/一次性 Profile。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
# [断言意图] 开关经 env 读取(默认 false 保持一次性 Profile 行为不变)
assert "env('FREIGHT_RPA_WORKER_SESSION_REUSE', 'false')" in text
# [断言意图] 复用模式使用持久 receipt_session 目录,且该目录不做批次后删除(跨批次复用登录态)
assert "profile_root / 'receipt_session'" in text
assert 'not reuse_session' in text
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
# [断言意图] 启动脚本提供 -SessionReuse 开关并注入对应 env
assert '[switch]$SessionReuse' in ps1
assert 'FREIGHT_RPA_WORKER_SESSION_REUSE' in ps1
+8 -8
View File
@@ -10,7 +10,7 @@ from pathlib import Path
def _load_freight_rpa_heartbeat_module():
rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "rpa"
rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa"
if str(rpa_dir) not in sys.path:
sys.path.insert(0, str(rpa_dir))
module_path = rpa_dir / "common" / "rpa_heartbeat.py"
@@ -24,7 +24,7 @@ def _load_freight_rpa_heartbeat_module():
def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
module = _load_freight_rpa_heartbeat_module()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
payload = module.build_heartbeat_payload(
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
drop_dir=r"C:\HxopsRpaTest\data\inventory_drop",
@@ -35,15 +35,15 @@ def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
module = _load_freight_rpa_heartbeat_module()
monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False)
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR",
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
r"C:\HxopsRpaTest\data\inventory_triggers",
)
assert module._resolve_shared_scope_id() == ""
monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR",
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
r"C:\mount\hxops-rpa-test-data\inventory_triggers",
)
assert module._resolve_shared_scope_id() == "hxops-rpa-test-data"
@@ -54,7 +54,7 @@ def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
trigger_dir = tmp_path / "inventory_triggers"
trigger_dir.mkdir()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01")
sentinel = trigger_dir / ".hxops_rpa_shared_mount"
@@ -78,7 +78,7 @@ def test_maybe_send_heartbeat_does_not_block_trigger_loop_when_http_stalls(tmp_p
return False
monkeypatch.setattr(module, "post_heartbeat", stalled_post)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "15")
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS", "15")
started = time.monotonic()
sent_at = module.maybe_send_heartbeat(
trigger_dir=tmp_path,
+151 -112
View File
@@ -1,4 +1,4 @@
"""scripts/rpa/freight_rpa_worker.py tests.
"""scripts/freight_rpa/freight_rpa_worker.py tests.
覆盖货代 RPA worker 对真实库存导出 trigger JSON 的消费路径:
1. 读取 inventory_export_SN-20260629-2EDADC77.json。
@@ -15,6 +15,7 @@ import os
import re
import sys
import time
import warnings
from pathlib import Path
import pytest
@@ -27,7 +28,7 @@ def _repo_root() -> Path:
def _load_freight_rpa_worker():
module_path = _repo_root() / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
module_path = _repo_root() / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path)
assert spec is not None
assert spec.loader is not None
@@ -162,7 +163,7 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
"inventory_sources": [source],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
@@ -216,7 +217,7 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_
"inventory_sources": [source],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
@@ -300,7 +301,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
}],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
@@ -359,7 +360,7 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
}],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
@@ -432,11 +433,11 @@ def test_env_strips_wrapping_quotes(monkeypatch):
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", '"user@example.com"')
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "'secret-pass'")
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", '"user@example.com"')
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "'secret-pass'")
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "user@example.com"
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "secret-pass"
assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "user@example.com"
assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "secret-pass"
def test_worker_accepts_business_connector_without_site_id():
@@ -511,7 +512,7 @@ def test_dsv_sso_blank_transition_refreshes_once_before_portal_wait(monkeypatch)
clock['value'] += 3.0
return clock['value']
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000')
monkeypatch.setenv('FREIGHT_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000')
monkeypatch.setattr(session.time, 'monotonic', monotonic)
monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None)
monkeypatch.setattr(session, '_debug_dsv_stage', lambda *_args, **_kwargs: None)
@@ -533,7 +534,7 @@ def test_dsv_sso_return_timeout_is_explicit(monkeypatch):
worker = _load_freight_rpa_worker()
session = worker.dsv_session
import dsv_auth
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000')
monkeypatch.setenv('FREIGHT_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000')
class _Page:
url = 'https://auth.dbschenker.com/as/authorization.ping'
@@ -569,9 +570,9 @@ def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
worker = _load_freight_rpa_worker()
key = Fernet.generate_key()
cipher = Fernet(key)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", key.decode("ascii"))
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", raising=False)
monkeypatch.setenv("FREIGHT_RPA_CREDENTIAL_KEY", key.decode("ascii"))
monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_USERNAME", raising=False)
monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", raising=False)
monkeypatch.delenv("FREIGHT_RPA_DSV_USERNAME", raising=False)
monkeypatch.delenv("FREIGHT_RPA_DSV_PASSWORD", raising=False)
source = {
@@ -582,39 +583,35 @@ def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
},
}
with worker._profile_credentials(source):
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "test-user"
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "test-password"
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == ""
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == ""
assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "test-user"
assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "test-password"
assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == ""
assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == ""
def test_worker_prefers_canonical_rpa_env_over_legacy_name(monkeypatch):
"""新旧 RPA 变量同时存在时必须使用统一的新命名空间,避免旧部署值覆盖新配置。"""
def test_worker_ignores_legacy_rpa_name_without_compat(monkeypatch):
"""无兼容层:历史旧名(FREIGHT_RPA_MOCK)不作为 FREIGHT_RPA_WORKER_MOCK 的回退,也不发弃用警告。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.delenv("FREIGHT_RPA_WORKER_MOCK", raising=False)
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "false"
def test_worker_reads_legacy_rpa_env_during_migration(monkeypatch):
"""规范变量缺失时允许读取旧名称,保障 Windows Worker 分阶段迁移不中断。"""
worker = _load_freight_rpa_worker()
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", raising=False)
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
with pytest.warns(DeprecationWarning, match="FREIGHT_RPA_MOCK is deprecated"):
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "true"
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
# 断言 1:仅设置历史旧名时,规范名直读为空、带默认值读回默认值(旧名不被咨询)。
assert worker._env("FREIGHT_RPA_WORKER_MOCK") == ""
assert worker._env("FREIGHT_RPA_WORKER_MOCK", "false") == "false"
# 断言 2:读取过程不产生任何 DeprecationWarning(兼容层已删除)。
assert not any(issubclass(item.category, DeprecationWarning) for item in caught)
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
"""配置 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
"""配置 FREIGHT_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
# 等价迁移:文件日志实现已提取至公共 worker_logging 模块,本用例改测公共接口。
worker_logging = _load_worker_logging()
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("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(log_path))
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_FILE", str(log_path))
original_stdout = sys.stdout
original_stderr = sys.stderr
@@ -645,15 +642,15 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
"""日志超过 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
"""日志超过 FREIGHT_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
# 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。
worker_logging = _load_worker_logging()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
Path(f"{log_path}.1").write_text("old-1", encoding="utf-8")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2")
worker_logging.rotate_log_file_if_needed(log_path)
@@ -669,8 +666,8 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0")
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "0")
worker_logging.rotate_log_file_if_needed(log_path)
@@ -678,13 +675,13 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp
def _load_worker_logging():
"""加载 scripts/rpa/common/worker_logging.py 供单测直接断言。
"""加载 scripts/freight_rpa/common/worker_logging.py 供单测直接断言。
历史背景:文件日志实现(tee/轮转/时间戳)原内置于 inventory_rpa_worker.py,
已提取为公共模块;Worker 内部私有名(_configure_file_logging 等)已删除,
日志行为用例统一改测公共接口,行为断言保持等价。
"""
common_dir = _repo_root() / "scripts" / "rpa" / "common"
common_dir = _repo_root() / "scripts" / "freight_rpa" / "common"
if str(common_dir) not in sys.path:
sys.path.insert(0, str(common_dir))
module_path = common_dir / "worker_logging.py"
@@ -700,8 +697,8 @@ def _load_worker_logging():
def _load_worker_disk_cleanup():
"""加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
module_path = _repo_root() / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py"
"""加载 scripts/freight_rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
module_path = _repo_root() / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py"
spec = importlib.util.spec_from_file_location("worker_disk_cleanup_under_test", module_path)
assert spec is not None
assert spec.loader is not None
@@ -787,8 +784,8 @@ def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypat
(orphan_run / "Cookies").write_text("drop", encoding="utf-8")
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "7")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "7")
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
stats = cleanup.run_worker_disk_cleanup(
inventory_trigger_dir=inv_trigger,
@@ -835,8 +832,8 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
orphan_run.mkdir()
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "0")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "0")
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
cleanup.run_worker_disk_cleanup(
inventory_trigger_dir=inv_trigger,
@@ -881,8 +878,8 @@ def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
assert stats.deleted_dirs == 1
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。"""
def test_open_browser_uses_freight_rpa_common_profile_fallback(monkeypatch):
"""未配置 profile 根目录时,应回退到 freight_rpa/common 布局的 browser_profile。"""
worker = _load_freight_rpa_worker()
observed: dict[str, object] = {}
@@ -906,12 +903,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
def start(self):
return _FakePlaywright()
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false")
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "true")
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", raising=False)
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
temp_roots: list[Path] = []
@@ -930,7 +926,8 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
assert context is not None
assert page is not None
expected_root = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
# 断言意图:bare-run 默认值必须等于 freight_rpa 三层布局的 common/browser_profile
expected_root = _repo_root() / "backend" / "data" / "freight_rpa" / "common" / "browser_profile"
assert temp_roots == [expected_root]
assert runtime_profile_dir == expected_root / "run_unit"
assert runtime_profile_dir.parent == expected_root
@@ -946,7 +943,7 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa
"""profile 根目录配置为 data/shipping_notice 时,应按 backend 根目录解析。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
"FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
"data/shipping_notice/freight_rpa/browser_profile",
)
@@ -955,30 +952,32 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa
assert worker._browser_profile_root() == expected.resolve()
def test_browser_profile_root_remaps_legacy_freight_rpa_path(monkeypatch):
"""本机残留旧 profile 路径时,应强制迁到 shipping_notice 命名空间。"""
def test_browser_profile_root_keeps_freight_rpa_layout_without_remap(monkeypatch, capsys):
"""profile 配置为 freight_rpa 布局路径时,应按字面解析:不改写、不告警(无兼容层红线)。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
"backend/data/freight_rpa/browser_profile",
"FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
"data/freight_rpa/browser_profile",
)
expected = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
# 断言意图:迁移期 remap 已删除,旧布局形状的配置值必须原样落到 backend 根下
expected = _repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"
assert worker._browser_profile_root() == expected.resolve()
# 断言意图:不得再输出 legacy 改写告警
assert "legacy" not in capsys.readouterr().out
def test_browser_profile_root_remaps_absolute_legacy_freight_rpa_path(monkeypatch):
"""本机环境变量保存绝对旧路径时,也应迁到 shipping_notice 命名空间。"""
def test_browser_profile_root_keeps_absolute_freight_rpa_layout_without_remap(monkeypatch, capsys):
"""绝对 freight_rpa 路径同样按字面解析,证明 remap 分支已完全移除。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
str(_repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"),
)
profile_dir = _repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(profile_dir))
expected = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
assert worker._browser_profile_root() == expected.resolve()
# 断言意图:绝对路径不再被强制迁往 shipping_notice 命名空间
assert worker._browser_profile_root() == profile_dir.resolve()
# 断言意图:不得再输出 legacy 改写告警
assert "legacy" not in capsys.readouterr().out
def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path):
@@ -1002,7 +1001,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
out_file.write_bytes(b"fake inventory content")
return out_file
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
@@ -1060,8 +1059,8 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
processed_dir = trigger_dir / "processed"
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
@@ -1122,7 +1121,7 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
def raise_no_inventory(_trigger: dict, _drop: Path):
raise worker.NoInventoryDataError("DSV report has no inventory data")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
@@ -1187,7 +1186,7 @@ def test_real_upload_requires_connection_config_enabled(monkeypatch, tmp_path):
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
with pytest.raises(RuntimeError, match="not enabled for this connection"):
worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={"upload_config_json": {"enabled": False}})
@@ -1198,8 +1197,8 @@ def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
events: list[tuple[str, object]] = []
class _Locator:
@@ -1245,7 +1244,7 @@ def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
runtime_profile = tmp_path / "profile"
runtime_profile.mkdir()
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
monkeypatch.setattr(worker, "_open_browser", lambda _dir, **_kwargs: (_Playwright(), _Context(), _Page(), runtime_profile))
def fake_result(_page, filename):
return {"reference": "", "success_evidence": {"kind": "dsv_upload_success_dom", "selector": ".alert.alert-success", "filename": filename, "reference": None, "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<div/>", "dom_sha256": "abc"}}
@@ -1275,8 +1274,8 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
events: list[tuple[str, object]] = []
class _Locator:
@@ -1314,7 +1313,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
runtime_profile = tmp_path / "profile"
runtime_profile.mkdir()
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
monkeypatch.setattr(worker, "_open_browser", lambda _dir, **_kwargs: (_Playwright(), _Context(), _Page(), runtime_profile))
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda _page, _filename: {"reference": "", "success_evidence": {}})
assert worker._upload_shipment_with_browser(
@@ -1406,7 +1405,7 @@ def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch):
return clock["value"]
monkeypatch.setattr(worker.time, "monotonic", monotonic)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000")
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000")
with pytest.raises(RuntimeError, match="did not confirm a green success status"):
worker._wait_for_dsv_upload_history_receipt(_Page(), "shipment.xlsx")
@@ -1542,7 +1541,7 @@ def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path):
"task_no": "SN-UPLOAD-FAIL", "file_path": str(queue_file), "attempt_id": 8, "callback_id": "rpa:8",
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_upload_shipment_with_browser", lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("success marker missing")))
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
@@ -1565,7 +1564,7 @@ def test_upload_empty_queue_path_reports_failed_callback(monkeypatch, tmp_path):
"task_no": "SN-UPLOAD-EMPTY", "attempt_id": 9, "callback_id": "rpa:9",
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
@@ -1631,12 +1630,11 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
def start(self):
return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false")
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false")
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", "msedge")
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads")
@@ -1679,9 +1677,8 @@ def test_open_browser_reuses_session_profile_per_connector_and_rpa_profile(monke
def start(self):
return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true")
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, profile_dir = worker._open_browser(
@@ -1723,8 +1720,8 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo
def start(self):
return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true")
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, profile_dir = worker._open_browser(
@@ -2230,7 +2227,7 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch):
def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch):
"""登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。"""
module_path = _repo_root() / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_export.py"
module_path = _repo_root() / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_export.py"
spec = importlib.util.spec_from_file_location("dsv_report_export_retry_test", module_path)
assert spec is not None and spec.loader is not None
dsv_report_export = importlib.util.module_from_spec(spec)
@@ -2430,7 +2427,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
worker._fill_dsv_filter_if_needed(
_FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
"FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
"Owner",
"CADU-0000000100",
)
@@ -2466,7 +2463,7 @@ def test_fill_dsv_filter_if_needed_accepts_report_name_kwarg():
worker._fill_dsv_filter_if_needed(
_FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
"FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
"Owner",
"CADU-0000000100",
report_name="On Hand Inventory by Location",
@@ -2622,26 +2619,26 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
"""
手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。
默认跳过;仅当 SHIPPING_NOTICE_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码:
- SHIPPING_NOTICE_RPA_WORKER_MOCK=false
- SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false(建议首次调试)
- SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
- SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD
默认跳过;仅当 FREIGHT_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码:
- FREIGHT_RPA_WORKER_MOCK=false
- FREIGHT_RPA_WORKER_HEADLESS=false(建议首次调试)
- FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
- FREIGHT_RPA_WORKER_DSV_USERNAME / FREIGHT_RPA_WORKER_DSV_PASSWORD
"""
if str(os.getenv("SHIPPING_NOTICE_RPA_WORKER_E2E") or "").strip().lower() != "true":
pytest.skip("set SHIPPING_NOTICE_RPA_WORKER_E2E=true to run real freight RPA export")
if str(os.getenv("FREIGHT_RPA_WORKER_E2E") or "").strip().lower() != "true":
pytest.skip("set FREIGHT_RPA_WORKER_E2E=true to run real freight RPA export")
worker = _load_freight_rpa_worker()
trigger = _build_inventory_export_trigger("SN-20260629-2EDADC77")
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS"):
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR"):
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
if not os.getenv("FREIGHT_RPA_WORKER_HEADLESS"):
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false")
if not os.getenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR"):
monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
"FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
str(tmp_path / "browser_profile"),
)
@@ -2651,3 +2648,45 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
assert out_file.parent == drop_dir
assert out_file.suffix.lower() in {".xlsx", ".xls", ".csv"}
assert out_file.stat().st_size > 0
def test_ensure_dsv_session_continues_auto_login_after_goto_abort(monkeypatch):
"""未登录时 goto 被 SSO 重定向以 ERR_ABORTED 中止:应继续自动登录,而不是判死整个源。"""
module_path = _repo_root() / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_export.py"
spec = importlib.util.spec_from_file_location("dsv_report_export_abort_test", module_path)
assert spec is not None and spec.loader is not None
dsv_report_export = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dsv_report_export)
class _FakeGotoAbort(Exception):
pass
login_calls: list[str] = []
goto_calls: list[str] = []
monkeypatch.setattr(dsv_report_export, "_is_dsv_session_active", lambda page, entry_url: False)
monkeypatch.setattr(
dsv_report_export,
"_goto_dsv_entry_url",
lambda page, entry_url: (goto_calls.append(entry_url), (_ for _ in ()).throw(_FakeGotoAbort("Page.goto: net::ERR_ABORTED at https://s360.dbschenker.com/main/portal")))[0],
)
monkeypatch.setattr(
dsv_report_export,
"_maybe_auto_login_dsv",
lambda page: login_calls.append("login"),
)
monkeypatch.setattr(dsv_report_export, "_is_dsv_on_entry_site", lambda page, entry_url: True)
monkeypatch.setattr(
dsv_report_export,
"_wait_for_dsv_home_ready",
lambda page, timeout_ms=None: None,
)
monkeypatch.setattr(dsv_report_export, "_wait_for_dsv_reports_nav_stable", lambda page, timeout_ms=None: None)
entry_url = "https://s360.dbschenker.com/"
dsv_report_export._ensure_dsv_session(object(), entry_url)
# [断言意图] goto 被中止后必须继续自动登录(正是未登录才会被 SSO 重定向打断);
# 登录成功后直接等待首页就绪,不重复 goto entry(该二次跳转仅在 home-not-ready 分支出现)
assert goto_calls == [entry_url]
assert login_calls == ["login"]
@@ -34,7 +34,7 @@ _RPA_MODULE_PATHS = {
def _load_rpa_module(module_name: str):
rel = _RPA_MODULE_PATHS.get(module_name, f"{module_name}.py")
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / rel
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / rel
scripts_dir = str(module_path.parent)
if scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir)
@@ -59,12 +59,12 @@ def test_fill_report_parameter_multi_select(monkeypatch):
page,
{
"name": "Warehouse",
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"mode": "multi_select",
"values": ["WH1", "WH2"],
},
)
assert calls == [("SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
assert calls == [("FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
@@ -96,7 +96,7 @@ def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
)
assert calls == [
{
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"label": "Warehouse",
"values": ["RTM"],
"selectors": None,
@@ -136,7 +136,7 @@ def test_fill_report_parameter_multi_select_jda_report_passes_template_selectors
)
assert calls == [
{
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"label": "Warehouse",
"values": ["RTM"],
"selectors": None,
@@ -418,8 +418,8 @@ def test_dsv_existing_portal_session_skips_all_auth_probes(monkeypatch):
"""持久化 Profile 已恢复 Portal 时,不得先等待用户名或认证页面。"""
flow = _load_dsv_auth_login_flow()
page = MagicMock()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "user")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "password")
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", "user")
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "password")
selector_wait = MagicMock()
auth_ready = MagicMock()
monkeypatch.setattr(flow, "_has_existing_dsv_portal_session", lambda _page: True)
+1 -1
View File
@@ -9,7 +9,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
"""POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
from app import db
@@ -126,7 +126,7 @@ def _published_template(*, code: str) -> ShippingExcelTemplate:
def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path):
"""测试文件只能生成测试分析,重复发起复用运行,禁止创建生产库存快照。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -150,8 +150,8 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app,
drop_dir = tmp_path / 'inventory_drop'
drop_dir.mkdir()
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -170,7 +170,7 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app,
def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -211,7 +211,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend
def test_empty_configuration_export_without_published_profile_is_rejected(app):
"""没有受控解析定义时,空结果不能被用作站点可用性的替代证据。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -228,7 +228,7 @@ def test_empty_configuration_export_without_published_profile_is_rejected(app):
def test_configuration_test_automatically_verifies_compatible_bound_profile(app, tmp_path):
"""当前绑定方案的核心栏位仍在时,历史无关列缺失也必须直接成为验证证据。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -248,7 +248,7 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app,
def test_verified_current_profile_automatically_enables_ready_source(app, tmp_path):
"""当前解析验证通过且必要条件齐全时,站点无需人工确认即可自动启用。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -270,7 +270,7 @@ def test_verified_current_profile_automatically_enables_ready_source(app, tmp_pa
def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path):
"""解析测试通过不绕过发货模板门禁,条件不完整的站点必须保持停用。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -291,7 +291,7 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm
def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path):
"""固定仓查询成功但无库存时,也能在完整门禁下自动启用站点。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -314,7 +314,7 @@ def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path):
def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path):
"""同连接站点一次投递,混合成功、空库存及失败后仍独立汇总为部分失败。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
) as write_trigger:
@@ -356,7 +356,7 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app,
def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
"""批次重试只新建失败站点运行,成功和空库存结果不会被重复导出。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -378,7 +378,7 @@ def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app, tmp_path):
"""配置变更后的旧批次回调必须失效,未知运行号不能污染同批次状态。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -406,7 +406,7 @@ def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app,
def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
"""页面刷新只能恢复仍在执行的批次,已结束批次不会反复占用进度面板。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -428,7 +428,7 @@ def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path):
"""Worker 领取回调只更新本批次当前运行,终态运行不得被重新打开。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -461,7 +461,7 @@ def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path)
def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_path):
"""重开配置抽屉只能恢复当前版本测试;站点改动后可发起独立新测试而不复用旧运行。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -482,8 +482,8 @@ def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_
def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
"""RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -511,8 +511,8 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
"""同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -538,7 +538,7 @@ def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, t
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
"""确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -581,7 +581,7 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path):
"""连接凭据或登录配置变更后,旧测试不得继续作为当前库存站点的启用证据。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -611,7 +611,7 @@ def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path):
def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path):
"""正式运行中的站点不能发起测试;站点配置变化后旧测试不得绑定。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -654,7 +654,7 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
"""失败回调和非推荐方案均不得产生生产快照或修改站点解析方案。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
@@ -114,7 +114,7 @@ def _excel_template_id() -> int:
def test_published_parsing_profile_can_be_shared_by_sources(app):
"""同一 published Profile 应可绑定多个库存源,避免重复维护相同模板。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
parsing = _published_profile()
login = shipping_inventory_service.save_profile({
@@ -132,7 +132,7 @@ def test_published_parsing_profile_can_be_shared_by_sources(app):
def test_source_rejects_draft_parsing_profile(app):
"""库存源只能绑定 published Profile,避免运行期读取可变草稿。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
@@ -175,7 +175,7 @@ def test_csv_parsing_profile_rejects_worksheet_configuration(app):
def test_new_published_version_does_not_retire_bound_version(app):
"""发布新版本不得使现有库存源绑定的旧 published 版本失效。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
first = _published_profile()
field_id = order_schema_service.get_state()['fields'][0]['id']
@@ -195,7 +195,7 @@ def test_new_published_version_does_not_retire_bound_version(app):
def test_referenced_published_profile_cannot_be_retired(app):
"""已绑定库存源的解析 Profile 必须先迁移 Source,不能直接退役。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
parsing = _published_profile()
login = shipping_inventory_service.save_profile({
@@ -12,7 +12,7 @@ from pathlib import Path
def _load_worker():
module_path = (
Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
)
scripts_dir = str(module_path.parent)
if scripts_dir not in sys.path:
+34
View File
@@ -0,0 +1,34 @@
"""
tests/test_ot_inline_edit.py
用途:验证通知准备阶段(Notice 未建、仅 OT)的就地编辑全链路。
依赖:pytest、task_workflow.update_notice_line、effective_order_view、有效视图夹具。
逻辑:复现"FORMAL_NOTICE_REQUIRED"报错场景——OT task_no 直接走 update-notice-line 通道,
编辑后有效值立即可见(库存匹配/Excel/通知行的统一读取口径)。
"""
from __future__ import annotations
from app.services.shipping_notice.effective_order_view import effective_order_field_values
from app.services.shipping_notice.task_workflow import update_notice_line
from tests.test_effective_order_view import _seed_frozen_order
def test_update_notice_line_accepts_order_task_before_notice(app):
"""通知准备阶段(无 Notice)编辑 OT 行字段必须成功且进入有效视图。"""
with app.app_context():
fixture = _seed_frozen_order()
response = update_notice_line({
'task_id': fixture.order.task_no,
'line_index': 0,
'patch': {'part_number': 'D4-A08AR12000002'},
'event_source': 'workspace_api',
'reviewed_by_id': fixture.user.id,
'expected_order_data_version': int(fixture.order.order_data_version or 1),
})
# 断言:服务层对 OT 放行(修复前 API 层 _require_formal_notice 报 FORMAL_NOTICE_REQUIRED)。
assert response['status'] == 'ok'
_header, lines = effective_order_field_values(fixture.order)
# 断言:编辑后的料号进入有效视图(重新匹配库存的读取口径),旧值不再出现。
assert lines[0]['f-part'] == 'D4-A08AR12000002'
assert lines[1]['f-part'] == 'D4-B07BR07000001'
+4 -4
View File
@@ -13,7 +13,7 @@ from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common"))
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common"))
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
@@ -64,7 +64,7 @@ def test_archive_rejects_bad_outcome_and_unclaimed_path(tmp_path):
def test_inventory_worker_scans_with_claim(tmp_path):
"""库存 Worker 扫描必须先领取(processing/),不得原地消费根目录文件。"""
root = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory"
root = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory"
text = (root / "inventory_rpa_worker.py").read_text(encoding="utf-8")
assert "claim_trigger" in text
# 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent
@@ -73,7 +73,7 @@ def test_inventory_worker_scans_with_claim(tmp_path):
def test_receipt_worker_runs_periodic_disk_cleanup():
"""收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。"""
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt
cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
assert '"receipt_"' in cleanup or "'receipt_'" in cleanup
+59 -39
View File
@@ -67,12 +67,12 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d
trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id=scope_id)
app.config["ENV_NAME"] = "test"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
return trigger_dir
@@ -132,11 +132,11 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["ENV_NAME"] = "test"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
with app.app_context():
record_rpa_worker_heartbeat(
@@ -154,9 +154,9 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
"""生产策略要求 Redis 时,写入失败应抛存储不可用。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
lambda _worker: False,
@@ -169,23 +169,35 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
assert exc_info.value.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path):
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
"""fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
# 隔离:强制无 Redis 分支(_redis_client 为模块级单例,config 置空不可靠,须 monkeypatch);
# 并清空心跳存储,确保走 no_worker_heartbeat + 进程内存储原因码。
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
reset_rpa_worker_heartbeat_state_for_tests()
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config["ENV_NAME"] = "test"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
assert_inventory_rpa_worker_ready()
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
assert "no_worker_heartbeat" in (exc_info.value.details or {}).get("reasons", [])
reasons = (exc_info.value.details or {}).get("reasons", [])
assert "no_worker_heartbeat" in reasons
# [断言意图] 无 Redis 时心跳存储为本进程内存,必须给出原因码与本地测试指引
assert "heartbeat_store_process_local" in reasons
assert (exc_info.value.details or {}).get("detail_message")
@@ -194,7 +206,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path,
import time as time_module
trigger_dir = _enable_prod_like_checks(app, tmp_path)
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90
base_now = time_module.time()
with app.app_context():
@@ -218,7 +230,7 @@ def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
res = client.post(
@@ -258,11 +270,19 @@ def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
assert res.status_code == 401
def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path):
def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypatch):
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
from app.services.shipping_notice.rpa_worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
# 隔离:强制无 Redis 分支(防真实心跳/单例缓存混入测试窗口)并清空存储,锁定离线 fail-fast 分支。
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
reset_rpa_worker_heartbeat_state_for_tests()
trigger_dir = _enable_prod_like_checks(app, tmp_path)
@@ -304,8 +324,8 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_path, monkeypatch):
"""Redis 读取异常应报 heartbeat_storage_unavailable,而非 no_worker_heartbeat。"""
trigger_dir = _enable_prod_like_checks(app, tmp_path)
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
class BrokenRedis:
def smembers(self, _key):
@@ -327,8 +347,8 @@ def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_pat
def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch):
"""test/prod Redis 策略:写入+读取成功时应 ready。"""
trigger_dir = _enable_prod_like_checks(app, tmp_path)
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
bucket: dict[str, Any] = {"index": set()}
class FakeRedis:
@@ -370,8 +390,8 @@ def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path)
trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
trigger_dir.mkdir(parents=True)
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config.pop("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", None)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
assert shared_scope_id() == "hxops-rpa-test-data"
@@ -385,15 +405,15 @@ def _enable_freight_upload_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-t
upload_queue.mkdir()
_write_shared_sentinel(upload_trigger, scope_id=scope_id)
app.config["ENV_NAME"] = "test"
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["FREIGHT_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
return upload_trigger
@@ -437,7 +457,7 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
_enable_freight_upload_checks(app, tmp_path)
# 去掉凭据主密钥:即使 Redis 残留心跳,静态配置缺失也必须阻断。
app.config.pop("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", None)
app.config.pop("FREIGHT_RPA_CREDENTIAL_KEY", None)
reset_rpa_worker_heartbeat_state_for_tests()
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
@@ -32,16 +32,16 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["ENV_NAME"] = "test"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = ""
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
app.config["FREIGHT_RPA_WORKER_ALERT_ENABLED"] = True
app.config["FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600
app.config["FREIGHT_RPA_WORKER_ALERT_USERNAMES"] = ""
app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
return trigger_dir
@@ -188,7 +188,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch
import logging
_enable_alert_checks(app, tmp_path)
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
@@ -214,7 +214,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch
def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatch):
"""显式配置的用户名优先于 admin 回退。"""
_enable_alert_checks(app, tmp_path)
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = "oncall_user"
app.config["FREIGHT_RPA_WORKER_ALERT_USERNAMES"] = "oncall_user"
with app.app_context():
from app import db
@@ -325,7 +325,7 @@ def test_concurrent_first_claim_integrity_error_does_not_claim(app, monkeypatch)
def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
"""过期 sending 锁且 sending_target=offline 时,Worker 恢复后应发送恢复通知。"""
_enable_alert_checks(app, tmp_path)
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS"] = 60
app.config["FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS"] = 60
stale_sending = {
"status": _STATUS_SENDING,
+6 -6
View File
@@ -2,7 +2,7 @@
用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、
按大小轮转滚动备份、shutdown 恢复标准流。
依赖:标准库 + scripts/rpa/common/worker_logging。
依赖:标准库 + scripts/freight_rpa/common/worker_logging。
逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。
"""
@@ -13,7 +13,7 @@ from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common"))
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common"))
from worker_logging import ( # noqa: E402
WorkerLogTee,
@@ -50,8 +50,8 @@ def test_tee_writes_timestamped_lines_to_both_streams(tmp_path, capsys):
def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch):
"""超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。"""
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "10")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "10")
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2")
path = tmp_path / "worker.log"
for round_no in range(3):
path.write_text(f"round-{round_no}-padding", encoding="utf-8")
@@ -65,7 +65,7 @@ def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch):
def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monkeypatch, capsys):
"""configure 启用落盘、print 双写;shutdown 恢复标准流且不再写文件。"""
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log"))
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log"))
enabled = configure_file_logging()
assert enabled == tmp_path / "logs" / "worker.log"
assert enabled.parent.is_dir() # 日志目录自动创建
@@ -80,5 +80,5 @@ def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monk
def test_configure_without_env_is_noop(monkeypatch):
"""未配置 LOG_FILE 时 configure 返回 None 且不改标准流。"""
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", raising=False)
monkeypatch.delenv("FREIGHT_RPA_WORKER_LOG_FILE", raising=False)
assert configure_file_logging() is None
@@ -135,7 +135,7 @@ def _confirm_direct_rpa_task_customer(task: ShippingOrderTask) -> None:
def test_encrypt_credential_round_trip_requires_runtime_key(app):
"""凭据必须依赖环境主密钥加密,且可在受控运行时回读。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
ciphertext = encrypt_credential('not-a-real-password')
assert ciphertext != 'not-a-real-password'
@@ -144,7 +144,7 @@ def test_encrypt_credential_round_trip_requires_runtime_key(app):
def test_encrypt_credential_rejects_missing_runtime_key(app):
"""关键加密主密钥缺失时拒绝写入凭据,避免产生不可恢复密文。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = ''
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = ''
with app.app_context(), pytest.raises(ServiceUnavailableError):
encrypt_credential('not-a-real-password')
@@ -130,7 +130,7 @@ def test_serialize_run_reads_inventory_raw_zip_available_from_summary(app):
def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path):
"""finalize 预生成应落盘 ZIP 并返回 summary 字段。"""
archive_dir = tmp_path / "inventory_archives"
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
xlsx = tmp_path / "inventory.xlsx"
xlsx.write_bytes(b"fake-xlsx-content")
@@ -176,7 +176,7 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p
def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
"""无可读快照时不生成 ZIP。"""
archive_dir = tmp_path / "inventory_archives"
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
with app.app_context():
run = _make_inventory_run_with_created(
@@ -193,7 +193,7 @@ def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_fi
def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp_path):
"""created 有记录但磁盘文件缺失时不应生成 ZIP。"""
archive_dir = tmp_path / "inventory_archives"
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
with app.app_context():
run = _make_inventory_run_with_created(
@@ -219,7 +219,7 @@ def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp
def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path):
"""下载解析应返回归档路径与建议文件名。"""
archive_dir = tmp_path / "inventory_archives"
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
xlsx = tmp_path / "inventory.xlsx"
xlsx.write_bytes(b"fake-xlsx-content")
@@ -262,7 +262,7 @@ def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app):
def test_resolve_inventory_raw_zip_download_rejects_path_outside_archive_dir(app, tmp_path):
"""summary 指向归档目录外的真实文件时必须 404。"""
archive_dir = tmp_path / "inventory_archives"
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
outside_zip = tmp_path / "outside.zip"
outside_zip.write_bytes(b"fake-zip")
@@ -286,7 +286,7 @@ def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path
"""summary 指向非 .zip 后缀文件时必须 404。"""
archive_dir = tmp_path / "inventory_archives"
archive_dir.mkdir(parents=True)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
fake_file = archive_dir / "RUN-ARCH-RESOLVE-BAD.txt"
fake_file.write_bytes(b"not-a-zip")
@@ -414,7 +414,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
app.config["WECOM_NOTIFY_ENABLED"] = True
app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com"
app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/"
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
user = User(
username="wecom_jump_user",
@@ -482,7 +482,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
):
"""admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。"""
archive_dir = tmp_path / "inventory_archives"
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
xlsx = tmp_path / "inventory.xlsx"
xlsx.write_bytes(b"fake-xlsx-content")
@@ -641,7 +641,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_mixed.xlsx"
@@ -683,7 +683,7 @@ def test_rpa_snapshot_persists_confirmed_profile_mapping(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory-mapping-confirmed.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -769,7 +769,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "batch_task_success.xlsx"
@@ -854,7 +854,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
with app.app_context():
task = ShippingOrderTask(
@@ -981,7 +981,7 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
sample = drop_dir / "crane-multi-warehouse.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("CRANE-WH").getvalue())
@@ -1054,7 +1054,7 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
sample = drop_dir / "crane-unresolved-link.xlsx"
sample.write_bytes(
inventory_xlsx_with_warehouse(
@@ -1301,7 +1301,7 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "orphan_task.xlsx"
with open(sample, "wb") as handle:
@@ -1398,7 +1398,7 @@ def test_inventory_trigger_writes_without_online_worker(app, tmp_path, monkeypat
with app.app_context():
trigger_dir = tmp_path / 'inventory_triggers'
app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR'] = str(trigger_dir)
app.config['FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR'] = str(trigger_dir)
monkeypatch.setattr(
'app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready',
lambda: (_ for _ in ()).throw(AssertionError('trigger write must not require worker heartbeat')),
@@ -1515,7 +1515,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "reuse_ingest_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -1587,7 +1587,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
run_no = "RUN-REUSE-MISMATCH"
@@ -1642,7 +1642,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
drop_dir = tmp_path / "drop"
drop_dir.mkdir(parents=True, exist_ok=True)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
sample_a = drop_dir / "task_a.xlsx"
sample_b = drop_dir / "task_b.xlsx"
sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -1714,7 +1714,7 @@ def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path,
drop_dir = tmp_path / "drop"
drop_dir.mkdir(parents=True, exist_ok=True)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
sample = drop_dir / "failed_before_confirm.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
callback_calls: list[dict] = []
@@ -1775,7 +1775,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
sample = drop_dir / "shared.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
run_no = "RUN-SHARED-LINK"
@@ -1851,7 +1851,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "post_commit.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -1894,7 +1894,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "promote_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -1988,7 +1988,7 @@ def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "move_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -2027,7 +2027,7 @@ def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, m
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "quarantine_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -2156,7 +2156,7 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat
processed_dir = tmp_path / "processed"
drop_dir.mkdir()
processed_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir)
quarantine = drop_dir / ".hxops_quarantine"
@@ -103,7 +103,7 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
"""排程 executor 应写入 inventory_export_batch trigger。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
@@ -135,7 +135,7 @@ def test_run_task_now_defers_inventory_rpa_until_callback(app, tmp_path):
"""run_task_now 写 trigger 后应保持 running 且 awaiting_rpa=true。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
@@ -157,7 +157,7 @@ def test_deferred_run_sets_started_at_when_missing(app, tmp_path):
"""复用无 started_at 的 run 时,defer 应补写 started_at,避免立即超时回收。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
@@ -244,7 +244,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
"""全部 source 成功但 Excel 导出失败时应降为 partial_failed 并写入 error_message。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_excel_fail.xlsx"
@@ -309,7 +309,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
"""finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_fail_finalize.xlsx"
@@ -373,7 +373,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
drop_dir.mkdir()
processed_dir = drop_dir / "processed"
processed_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_sample.xlsx"
@@ -516,7 +516,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
"""回调结果少于触发源数时,排程应 partial_failed。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_partial.xlsx"
@@ -851,7 +851,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "missing_warehouse.xlsx"
_write_sample_inventory(sample, "AWSDU")
@@ -881,7 +881,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "retry_snapshot.xlsx"
_write_sample_inventory(sample, "AWSDU")
@@ -944,7 +944,7 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "retry_move.xlsx"
_write_sample_inventory(sample, "AWSDU")
@@ -14,7 +14,7 @@ from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_
def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch):
"""batch 开启时单票按需应写 inventory_export_batch trigger。"""
trigger_dir = tmp_path / "triggers"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config.pop("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", None)
monkeypatch.setenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
@@ -55,7 +55,7 @@ def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path):
from app.core.errors import ValidationError
trigger_dir = tmp_path / "triggers"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
@@ -71,7 +71,7 @@ def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_p
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
trigger_dir = tmp_path / "triggers"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
path = write_inventory_export_batch_trigger("RUN-DBS", [{
"source_code": "UNKNOWN_FOR_TEST", "connector_type": "dbs", "rpa_profile_code": "DBS_TEST",
@@ -92,7 +92,7 @@ def test_batch_trigger_writes_explicit_v2_callback_identity(app, tmp_path):
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
trigger_dir = tmp_path / "triggers"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
source = {
"source_code": "DBS",
+2 -2
View File
@@ -459,8 +459,8 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
trigger.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,