feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议
This commit is contained in:
1 parent
46eb63f5bb
commit
e9bdd81f1a
320 files changed
+28361
-10487
No files matched your search
@@ -16,6 +16,7 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from cryptography.fernet import Fernet
|
||||
from openpyxl import load_workbook
|
||||
|
||||
|
||||
@@ -33,16 +34,6 @@ def _load_freight_rpa_worker():
|
||||
return module
|
||||
|
||||
|
||||
def _load_dsv_export_batch_smoke():
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_batch_smoke.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_export_batch_smoke_worker_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
|
||||
"""构造库存导出 trigger 样本,避免测试依赖会被 worker 消费掉的仓库文件。"""
|
||||
return {
|
||||
@@ -72,20 +63,96 @@ def test_env_strips_wrapping_quotes(monkeypatch):
|
||||
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", '"user@example.com"')
|
||||
monkeypatch.setenv("FREIGHT_RPA_DSV_PASSWORD", "'secret-pass'")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", '"user@example.com"')
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "'secret-pass'")
|
||||
|
||||
assert worker._env("FREIGHT_RPA_DSV_USERNAME") == "user@example.com"
|
||||
assert worker._env("FREIGHT_RPA_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"
|
||||
|
||||
|
||||
def test_worker_accepts_business_connector_without_site_id():
|
||||
"""数据库 Source 的 dbs/crane 业务类型不应要求已删除的 site_id 字段。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
worker._validate_inventory_source_for_rpa({
|
||||
"source_code": "DBS_DUB", "connector_type": "dbs", "warehouse_id": "DUB",
|
||||
})
|
||||
worker._validate_inventory_source_for_rpa({
|
||||
"source_code": "CRANE", "connector_type": "crane",
|
||||
})
|
||||
|
||||
|
||||
def test_worker_groups_same_connector_by_rpa_profile():
|
||||
"""同 connector 的不同 Profile 必须分组,防止错误复用登录态。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
grouped = worker._group_batch_sources_by_profile([
|
||||
{"source_code": "DBS_DUB", "connector_type": "dbs", "rpa_profile_code": "DBS_EU_A"},
|
||||
{"source_code": "DBS_RTM", "connector_type": "dbs", "rpa_profile_code": "DBS_EU_B"},
|
||||
])
|
||||
assert set(grouped) == {("dsv360", "DBS_EU_A"), ("dsv360", "DBS_EU_B")}
|
||||
|
||||
|
||||
def test_worker_keeps_same_profile_sources_in_one_session_group():
|
||||
"""同一登录连接的多个 Source 可复用登录会话,不与其他 Profile 混用。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
grouped = worker._group_batch_sources_by_profile([
|
||||
{'source_code': 'DBS_DUB', 'connector_type': 'dbs', 'rpa_profile_code': 'DBS_EU_A'},
|
||||
{'source_code': 'DBS_RTM', 'connector_type': 'dbs', 'rpa_profile_code': 'DBS_EU_A'},
|
||||
{'source_code': 'DBS_CMH', 'connector_type': 'dbs', 'rpa_profile_code': 'DBS_US_B'},
|
||||
])
|
||||
assert [item['source_code'] for item in grouped[('dsv360', 'DBS_EU_A')]] == ['DBS_DUB', 'DBS_RTM']
|
||||
assert [item['source_code'] for item in grouped[('dsv360', 'DBS_US_B')]] == ['DBS_CMH']
|
||||
|
||||
|
||||
def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
|
||||
"""worker 解密 Profile 密文后必须在退出执行范围时恢复原有环境。"""
|
||||
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.delenv("FREIGHT_RPA_DSV_USERNAME", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_DSV_PASSWORD", raising=False)
|
||||
source = {
|
||||
"connector_type": "dbs",
|
||||
"credential_envelope": {
|
||||
"username_ciphertext": cipher.encrypt(b"test-user").decode("ascii"),
|
||||
"password_ciphertext": cipher.encrypt(b"test-password").decode("ascii"),
|
||||
},
|
||||
}
|
||||
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") == ""
|
||||
|
||||
|
||||
def test_worker_prefers_canonical_rpa_env_over_legacy_name(monkeypatch):
|
||||
"""新旧 RPA 变量同时存在时必须使用统一的新命名空间,避免旧部署值覆盖新配置。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "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"
|
||||
|
||||
|
||||
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
|
||||
"""配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
|
||||
"""配置 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
log_path = tmp_path / "logs" / "worker.log"
|
||||
timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ")
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_LOG_FILE", str(log_path))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(log_path))
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
|
||||
@@ -116,14 +183,14 @@ 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):
|
||||
"""日志超过 FREIGHT_RPA_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
|
||||
"""日志超过 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
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("FREIGHT_RPA_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "2")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
|
||||
|
||||
worker._rotate_log_file_if_needed(log_path)
|
||||
|
||||
@@ -138,8 +205,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("FREIGHT_RPA_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "0")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0")
|
||||
|
||||
worker._rotate_log_file_if_needed(log_path)
|
||||
|
||||
@@ -171,10 +238,10 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.delenv("FREIGHT_RPA_BROWSER_PROFILE_DIR", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "true")
|
||||
monkeypatch.delenv("FREIGHT_RPA_BROWSER_CHANNEL", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=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.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
temp_roots: list[Path] = []
|
||||
@@ -209,7 +276,7 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa
|
||||
"""profile 根目录配置为 data/shipping_notice 时,应按 backend 根目录解析。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"data/shipping_notice/freight_rpa/browser_profile",
|
||||
)
|
||||
|
||||
@@ -222,7 +289,7 @@ def test_browser_profile_root_remaps_legacy_freight_rpa_path(monkeypatch):
|
||||
"""本机残留旧 profile 路径时,应强制迁到 shipping_notice 命名空间。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"backend/data/freight_rpa/browser_profile",
|
||||
)
|
||||
|
||||
@@ -235,7 +302,7 @@ def test_browser_profile_root_remaps_absolute_legacy_freight_rpa_path(monkeypatc
|
||||
"""本机环境变量保存绝对旧路径时,也应迁到 shipping_notice 命名空间。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
str(_repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"),
|
||||
)
|
||||
|
||||
@@ -265,7 +332,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("FREIGHT_RPA_MOCK", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_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)))
|
||||
|
||||
@@ -312,8 +379,8 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
processed_dir = trigger_dir / "processed"
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
|
||||
monkeypatch.delenv("FREIGHT_RPA_SAMPLE_INVENTORY", raising=False)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_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)
|
||||
@@ -363,7 +430,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("FREIGHT_RPA_MOCK", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_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)))
|
||||
|
||||
@@ -447,37 +514,14 @@ def test_summarize_inventory_batch_item_empty_dict_counts_as_failed():
|
||||
assert summary["success"] is False
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_all_skipped_smoke_exit_success():
|
||||
"""全 skipped 时 summary status=success,smoke 应退出 0(链路正常、无 Excel)。"""
|
||||
def test_summarize_inventory_batch_results_all_skipped_is_success():
|
||||
"""全 skipped 代表链路正常但无库存,不得误报为批量导出失败。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
|
||||
summary = worker._summarize_inventory_batch_results(results)
|
||||
assert summary["status"] == "success"
|
||||
assert summary["has_success"] is False
|
||||
assert summary["status"] not in {"failed", "partial_failed"}
|
||||
smoke = _load_dsv_export_batch_smoke()
|
||||
assert smoke._resolve_smoke_scenario_exit_code(
|
||||
results=results,
|
||||
summary=summary,
|
||||
require_export=False,
|
||||
) == 0
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_all_skipped_require_export_smoke_exit_fail():
|
||||
"""FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 时,全 skipped 应退出 2(无 Excel 导出)。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
smoke = _load_dsv_export_batch_smoke()
|
||||
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
|
||||
summary = worker._summarize_inventory_batch_results(results)
|
||||
assert summary["status"] == "success"
|
||||
assert summary["has_success"] is False
|
||||
assert smoke._resolve_smoke_scenario_exit_code(
|
||||
results=results,
|
||||
summary=summary,
|
||||
require_export=True,
|
||||
) == 2
|
||||
|
||||
|
||||
def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path):
|
||||
"""真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -503,10 +547,10 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
|
||||
monkeypatch.delenv("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
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.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads")
|
||||
@@ -1004,7 +1048,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
|
||||
|
||||
worker._fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"FREIGHT_RPA_DSV_OWNER_SELECTOR",
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"Owner",
|
||||
"CADU-0000000100",
|
||||
)
|
||||
@@ -1159,26 +1203,26 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
|
||||
"""
|
||||
手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。
|
||||
|
||||
默认跳过;仅当 FREIGHT_RPA_E2E=true 时执行。执行前需准备账号密码:
|
||||
- FREIGHT_RPA_MOCK=false
|
||||
- FREIGHT_RPA_HEADLESS=false(建议首次调试)
|
||||
- FREIGHT_RPA_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
|
||||
- FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD
|
||||
默认跳过;仅当 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
|
||||
"""
|
||||
if str(os.getenv("FREIGHT_RPA_E2E") or "").strip().lower() != "true":
|
||||
pytest.skip("set FREIGHT_RPA_E2E=true to run real freight RPA export")
|
||||
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")
|
||||
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger = _build_inventory_export_trigger("SN-20260629-2EDADC77")
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_MOCK", "false")
|
||||
if not os.getenv("FREIGHT_RPA_HEADLESS"):
|
||||
monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "false")
|
||||
if not os.getenv("FREIGHT_RPA_BROWSER_PROFILE_DIR"):
|
||||
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_BROWSER_PROFILE_DIR",
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
str(tmp_path / "browser_profile"),
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user