feat(rpa): 恢复FREIGHT_RPA命名空间统一运行目录并完成收料部署对齐与readiness加固

- AGENTS.md §8.1 红线改写:env 命名空间恢复 FREIGHT_RPA_*,SHIPPING_NOTICE_RPA_* 一刀切废弃、不设兼容层
- 全仓机械前缀替换(70 文件)并删除兼容层;4 个既有基线测试失败一并清零(过期桩/存储隔离/排程 fail-fast 接线)
- 运行期数据目录统一 freight_rpa/{inventory,receipt,common}:settings 默认、4 个 env、2 个 ps1 三侧一致
- 代码目录 scripts/rpa 更名 scripts/freight_rpa 与数据根对齐;全仓路径引用同步,README 部署走查与升级小节
- 收料部署对齐库存:计划任务注册脚本(独立任务名)、可选 -SessionReuse 会话复用、DSV 老别名链移除
- readiness 加固:排程离线立即 failed(不挂 awaiting);无 Redis 时追加进程内存储原因码与本地测试指引
- DSV 会话准备遇 SSO 重定向中止时改走自动登录,首源不再因未登录判死
This commit is contained in:
hugo committed 2026-09-19 09:49:25 +08:00
1 parent 95488db656
commit c3eef5cf20
90 files changed
+2022 -1463

No files matched your search

+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"]