feat(schedule): 增加库存源选项描述字段与站点ID支持
This commit is contained in:
1 parent
f4e74f7b07
commit
8b1efbedb9
37 files changed
+8488
-4126
No files matched your search
@@ -0,0 +1,159 @@
|
||||
"""crane_navigation 报表页导航测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _load_navigation():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "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)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, *, visible: bool = True) -> None:
|
||||
self.visible = visible
|
||||
self.clicked = False
|
||||
self.hovered = False
|
||||
|
||||
@property
|
||||
def first(self) -> "_FakeLocator":
|
||||
return self
|
||||
|
||||
def is_visible(self, timeout: int = 0) -> bool:
|
||||
return self.visible
|
||||
|
||||
def click(self, timeout: int = 0, force: bool = False) -> None:
|
||||
self.clicked = True
|
||||
|
||||
def hover(self, timeout: int = 0) -> None:
|
||||
self.hovered = True
|
||||
|
||||
|
||||
class _FakePage:
|
||||
def __init__(self, *, url: str = "https://wms-portal.craneww.com/#/") -> None:
|
||||
self.url = url
|
||||
self.frames: list[_FakePage] = []
|
||||
self.goto_calls: list[str] = []
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if "on-hand-details-query" in selector or "On Hand Details" in selector:
|
||||
return _FakeLocator(visible=True)
|
||||
if "Queries" in selector or "navbar" in selector:
|
||||
return _FakeLocator(visible=True)
|
||||
return _FakeLocator(visible=False)
|
||||
|
||||
def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator:
|
||||
if role == "link" and name in {"On Hand Details", "Queries"}:
|
||||
return _FakeLocator(visible=True)
|
||||
return _FakeLocator(visible=False)
|
||||
|
||||
def goto(self, url: str, wait_until: str = "", timeout: int = 0) -> None:
|
||||
self.goto_calls.append(url)
|
||||
self.url = url
|
||||
|
||||
|
||||
def test_navigate_prefers_dashboard_tile(monkeypatch):
|
||||
"""应优先尝试首页 On Hand Details 卡片。"""
|
||||
module = _load_navigation()
|
||||
page = _FakePage()
|
||||
calls: list[str] = []
|
||||
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_click_dashboard_on_hand_details",
|
||||
lambda *args, **kwargs: calls.append("dashboard") or True,
|
||||
)
|
||||
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: calls.append("navbar") or True)
|
||||
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
|
||||
|
||||
mode = module.navigate_to_crane_report(
|
||||
page,
|
||||
"https://wms-portal.craneww.com/#/on-hand-details-query",
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
)
|
||||
|
||||
assert mode == "dashboard_tile"
|
||||
assert calls == ["dashboard"]
|
||||
assert page.goto_calls == []
|
||||
|
||||
|
||||
def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch):
|
||||
"""首页卡片未进入报表时应回退顶部 Queries 菜单。"""
|
||||
module = _load_navigation()
|
||||
page = _FakePage()
|
||||
wait_calls = {"n": 0}
|
||||
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
|
||||
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
|
||||
|
||||
def _wait(page_arg, entry_url, *, browser_timeout_ms):
|
||||
wait_calls["n"] += 1
|
||||
return wait_calls["n"] >= 2
|
||||
|
||||
monkeypatch.setattr(module, "_wait_for_report_navigation", _wait)
|
||||
|
||||
mode = module.navigate_to_crane_report(
|
||||
page,
|
||||
"https://wms-portal.craneww.com/#/on-hand-details-query",
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
)
|
||||
|
||||
assert mode == "navbar_menu"
|
||||
assert wait_calls["n"] == 2
|
||||
|
||||
|
||||
def test_navigate_uses_direct_goto_as_last_resort(monkeypatch):
|
||||
"""卡片与菜单均失败时应 goto entry_url。"""
|
||||
module = _load_navigation()
|
||||
page = _FakePage()
|
||||
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||||
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
|
||||
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: False)
|
||||
|
||||
with pytest.raises(RuntimeError, match="navigation failed"):
|
||||
module.navigate_to_crane_report(page, entry, env=lambda n, d="": d, browser_timeout_ms=5_000)
|
||||
|
||||
assert page.goto_calls[0] == entry
|
||||
assert any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
|
||||
|
||||
|
||||
def test_is_crane_on_report_route_reads_entry_hash():
|
||||
"""应从 entry_url hash 判断当前是否已在目标报表路由。"""
|
||||
module = _load_navigation()
|
||||
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
|
||||
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||||
assert module.is_crane_on_report_route(page, entry) is True
|
||||
|
||||
|
||||
def test_homepage_is_not_report_form_ready():
|
||||
"""登录后首页 /#/ 不应被误判为报表表单已就绪。"""
|
||||
module = _load_navigation()
|
||||
page = _FakePage(url="https://wms-portal.craneww.com/#/")
|
||||
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||||
assert module.is_crane_on_homepage(page) is True
|
||||
assert module.is_crane_report_form_ready(page, entry) is False
|
||||
|
||||
|
||||
def test_report_route_without_controls_is_not_ready(monkeypatch):
|
||||
"""仅有 hash 路由但无 Run Report 控件时仍不算 ready。"""
|
||||
module = _load_navigation()
|
||||
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
|
||||
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||||
monkeypatch.setattr(module, "_has_report_form_controls", lambda page_arg: False)
|
||||
assert module.is_crane_report_form_ready(page, entry) is False
|
||||
@@ -0,0 +1,446 @@
|
||||
"""crane_report_export 异步报表导出流程测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _load_export():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "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)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_fill_parameters_skips_warehouse(monkeypatch):
|
||||
"""Warehouse 参数应被跳过,不再填写。"""
|
||||
module = _load_export()
|
||||
calls: list[tuple[str, str, str]] = []
|
||||
|
||||
def _fake_select(page, selector_env, label, value):
|
||||
calls.append((selector_env, label, value))
|
||||
|
||||
module._fill_crane_report_parameters(
|
||||
MagicMock(),
|
||||
{
|
||||
"parameters": [
|
||||
{
|
||||
"name": "Warehouse",
|
||||
"selector_env": "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR",
|
||||
"mode": "single",
|
||||
"values": ["TZR2"],
|
||||
},
|
||||
{
|
||||
"name": "Owner",
|
||||
"selector_env": "FREIGHT_RPA_CRANE_OWNER_SELECTOR",
|
||||
"mode": "single",
|
||||
"values": ["OWNER1"],
|
||||
},
|
||||
]
|
||||
},
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
select_or_fill=_fake_select,
|
||||
)
|
||||
|
||||
assert calls == [("FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
|
||||
|
||||
|
||||
def test_build_schedule_description_uses_short_uuid_hex(monkeypatch):
|
||||
"""Description 默认取 UUID4 前 12 位 hex,兼顾唯一性与列表可读性。"""
|
||||
module = _load_export()
|
||||
monkeypatch.setattr(
|
||||
module.uuid,
|
||||
"uuid4",
|
||||
lambda: module.uuid.UUID("11111111-2222-4333-8444-555555555555"),
|
||||
)
|
||||
text = module._build_schedule_description(
|
||||
{"source_code": "CRANE_TZR2"},
|
||||
{"task_no": "SN-1001"},
|
||||
env=lambda name, default="": default,
|
||||
)
|
||||
assert text == "111111112222"
|
||||
assert len(text) == 12
|
||||
|
||||
|
||||
def test_build_schedule_description_hex_len_env():
|
||||
"""可通过环境变量调整 Description 长度(8~32)。"""
|
||||
module = _load_export()
|
||||
text = module._build_schedule_description(
|
||||
{"source_code": "CRANE_TZR2"},
|
||||
None,
|
||||
env=lambda name, default="": "16" if name == "FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
|
||||
)
|
||||
assert len(text) == 16
|
||||
|
||||
|
||||
def test_export_scheduled_report_flow(monkeypatch):
|
||||
"""scheduled_report 模式应按 Run → Schedule → Scheduled Reports 顺序执行。"""
|
||||
module = _load_export()
|
||||
page = MagicMock()
|
||||
page.url = "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||||
calls: list[str] = []
|
||||
captured: dict[str, str] = {}
|
||||
|
||||
monkeypatch.setattr(module, "_fill_crane_report_parameters", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(module, "_build_schedule_description", lambda *args, **kwargs: "HXOPS-CRANE_TZR2-TEST")
|
||||
monkeypatch.setattr(module, "_click_run_report", lambda *args, **kwargs: calls.append("run"))
|
||||
monkeypatch.setattr(module, "_wait_for_run_report_results", lambda *args, **kwargs: calls.append("wait_run"))
|
||||
|
||||
def _schedule(*args, **kwargs):
|
||||
calls.append("schedule")
|
||||
|
||||
def _confirm(page_arg, description, **kwargs):
|
||||
calls.append("confirm")
|
||||
captured["description"] = description
|
||||
|
||||
monkeypatch.setattr(module, "_click_schedule_report", _schedule)
|
||||
monkeypatch.setattr(module, "_confirm_schedule_report_modal", _confirm)
|
||||
monkeypatch.setattr(module, "_wait_for_report_submission_complete", lambda *args, **kwargs: calls.append("wait_submitted"))
|
||||
monkeypatch.setattr(module, "_open_scheduled_reports", lambda *args, **kwargs: calls.append("open_scheduled"))
|
||||
|
||||
def _download(*args, **kwargs):
|
||||
calls.append("download")
|
||||
captured["download_description"] = kwargs.get("description", "")
|
||||
return "download-object"
|
||||
|
||||
monkeypatch.setattr(module, "_wait_and_click_scheduled_download", _download)
|
||||
|
||||
result = module.export_crane_inventory_report(
|
||||
page,
|
||||
{"navigation": {"download_mode": "scheduled_report"}, "parameters": [], "source_code": "CRANE_TZR2"},
|
||||
trigger={"task_no": "SN-1001"},
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
select_or_fill=lambda *args, **kwargs: None,
|
||||
click_text=lambda *args, **kwargs: None,
|
||||
)
|
||||
|
||||
assert result == "download-object"
|
||||
assert calls == ["run", "wait_run", "schedule", "confirm", "wait_submitted", "open_scheduled", "download"]
|
||||
assert captured["description"] == "HXOPS-CRANE_TZR2-TEST"
|
||||
assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST"
|
||||
|
||||
|
||||
def test_should_run_report_before_schedule_defaults_true():
|
||||
"""默认必须先 Run Report;仅显式 run_before_schedule=false 可关闭。"""
|
||||
module = _load_export()
|
||||
assert (
|
||||
module._should_run_report_before_schedule(
|
||||
{"navigation": {}},
|
||||
env=lambda name, default="": default,
|
||||
)
|
||||
is True
|
||||
)
|
||||
assert (
|
||||
module._should_run_report_before_schedule(
|
||||
{"navigation": {"run_before_schedule": False}},
|
||||
env=lambda name, default="": default,
|
||||
)
|
||||
is False
|
||||
)
|
||||
assert (
|
||||
module._should_run_report_before_schedule(
|
||||
{"navigation": {}},
|
||||
env=lambda name, default="": "false" if name == "FREIGHT_RPA_CRANE_RUN_BEFORE_SCHEDULE" else default,
|
||||
)
|
||||
is False
|
||||
)
|
||||
|
||||
|
||||
def test_is_on_scheduled_reports_page_detects_hash_route():
|
||||
"""仅 on-hand-details-query 不算 Scheduled Reports 页。"""
|
||||
module = _load_export()
|
||||
|
||||
class _Page:
|
||||
def __init__(self, url: str) -> None:
|
||||
self.url = url
|
||||
|
||||
assert module._is_on_scheduled_reports_page(_Page("https://wms-portal.craneww.com/#/scheduled-reports")) is True
|
||||
assert module._is_on_scheduled_reports_page(_Page("https://wms-portal.craneww.com/#/on-hand-details-query")) is False
|
||||
|
||||
|
||||
def test_find_scheduled_download_waits_until_status_is_download():
|
||||
"""Description 行末列为 Submitted 时不应返回下载链接。"""
|
||||
module = _load_export()
|
||||
|
||||
class _Cells:
|
||||
def __init__(self, texts: list[str]) -> None:
|
||||
self._texts = texts
|
||||
|
||||
def count(self) -> int:
|
||||
return len(self._texts)
|
||||
|
||||
def nth(self, index: int) -> _Cell:
|
||||
return _Cell(self._texts[index])
|
||||
|
||||
class _Cell:
|
||||
def __init__(self, text: str, *, visible: bool = False) -> None:
|
||||
self._text = text
|
||||
self._visible = visible
|
||||
|
||||
def inner_text(self, timeout: int = 0) -> str:
|
||||
return self._text
|
||||
|
||||
def is_visible(self, timeout: int = 0) -> bool:
|
||||
return self._visible
|
||||
|
||||
@property
|
||||
def first(self):
|
||||
return self
|
||||
|
||||
class _Row:
|
||||
def __init__(self, name: str, description: str, status: str, *, submitted: str = "2026/7/9 04:45:45") -> None:
|
||||
self._description = description
|
||||
self._status = status
|
||||
self._cells = _Cells([name, submitted, description, status])
|
||||
|
||||
def is_visible(self, timeout: int = 0) -> bool:
|
||||
return True
|
||||
|
||||
def locator(self, selector: str) -> Any:
|
||||
if selector == "td":
|
||||
return self._cells
|
||||
return _Cell("Download", visible=selector.startswith("a"))
|
||||
|
||||
def get_by_role(self, role: str, name: str, exact: bool = False) -> _Cell:
|
||||
return _Cell("Download", visible=True)
|
||||
|
||||
class _Rows:
|
||||
def __init__(self, rows: list[_Row]) -> None:
|
||||
self._rows = rows
|
||||
|
||||
def count(self) -> int:
|
||||
return len(self._rows)
|
||||
|
||||
def nth(self, index: int) -> _Row:
|
||||
return self._rows[index]
|
||||
|
||||
class _Page:
|
||||
def __init__(self, rows: list[_Row]) -> None:
|
||||
self.frames: list = []
|
||||
self._rows = rows
|
||||
self.url = "https://wms-portal.craneww.com/#/scheduled-reports"
|
||||
|
||||
def locator(self, selector: str) -> _Rows:
|
||||
return _Rows(self._rows)
|
||||
|
||||
submitted = module._find_scheduled_download_by_description(
|
||||
_Page([_Row("OnHandDetails.xlsx", "uuid-1", "Submitted")]),
|
||||
"uuid-1",
|
||||
env=lambda name, default="": default,
|
||||
)
|
||||
assert submitted is None
|
||||
|
||||
download = module._find_scheduled_download_by_description(
|
||||
_Page([_Row("OnHandDetails.xlsx", "uuid-2", "Download")]),
|
||||
"uuid-2",
|
||||
env=lambda name, default="": default,
|
||||
)
|
||||
assert download is not None
|
||||
|
||||
|
||||
def test_find_scheduled_download_skips_wrong_name_and_picks_first_match():
|
||||
"""应跳过 Name 不符的行,自上而下取首条 OnHandDetails.xlsx + Description 匹配项。"""
|
||||
module = _load_export()
|
||||
|
||||
class _Cells:
|
||||
def __init__(self, texts: list[str]) -> None:
|
||||
self._texts = texts
|
||||
|
||||
def count(self) -> int:
|
||||
return len(self._texts)
|
||||
|
||||
def nth(self, index: int) -> _Cell:
|
||||
return _Cell(self._texts[index])
|
||||
|
||||
class _Cell:
|
||||
def __init__(self, text: str, *, visible: bool = False) -> None:
|
||||
self._text = text
|
||||
self._visible = visible
|
||||
|
||||
def inner_text(self, timeout: int = 0) -> str:
|
||||
return self._text
|
||||
|
||||
def is_visible(self, timeout: int = 0) -> bool:
|
||||
return self._visible
|
||||
|
||||
@property
|
||||
def first(self):
|
||||
return self
|
||||
|
||||
class _Row:
|
||||
def __init__(self, name: str, submitted: str, description: str, status: str) -> None:
|
||||
self._cells = _Cells([name, submitted, description, status])
|
||||
|
||||
def is_visible(self, timeout: int = 0) -> bool:
|
||||
return True
|
||||
|
||||
def locator(self, selector: str) -> Any:
|
||||
if selector == "td":
|
||||
return self._cells
|
||||
return _Cell("Download", visible=selector.startswith("a"))
|
||||
|
||||
def get_by_role(self, role: str, name: str, exact: bool = False) -> _Cell:
|
||||
return _Cell("Download", visible=True)
|
||||
|
||||
class _Rows:
|
||||
def __init__(self, rows: list[_Row]) -> None:
|
||||
self._rows = rows
|
||||
|
||||
def count(self) -> int:
|
||||
return len(self._rows)
|
||||
|
||||
def nth(self, index: int) -> _Row:
|
||||
return self._rows[index]
|
||||
|
||||
class _Page:
|
||||
def __init__(self, rows: list[_Row]) -> None:
|
||||
self.frames: list = []
|
||||
self._rows = rows
|
||||
self.url = "https://wms-portal.craneww.com/#/scheduled-reports"
|
||||
|
||||
def locator(self, selector: str) -> _Rows:
|
||||
return _Rows(self._rows)
|
||||
|
||||
rows = [
|
||||
_Row("OutboundDetails.xlsx", "2026/7/9 04:50:00", "target-uuid", "Download"),
|
||||
_Row("OnHandDetails.xlsx", "2026/7/9 04:45:45", "other-uuid", "Download"),
|
||||
_Row("OnHandDetails.xlsx", "2026/7/9 04:40:00", "target-uuid", "Download"),
|
||||
]
|
||||
locator = module._find_scheduled_download_by_description(
|
||||
_Page(rows),
|
||||
"target-uuid",
|
||||
env=lambda name, default="": default,
|
||||
)
|
||||
assert locator is not None
|
||||
|
||||
|
||||
def test_probe_scheduled_download_status_returns_submitted_before_download():
|
||||
"""每轮 poll 应能读到 Submitted;仅 Download 时返回 locator。"""
|
||||
module = _load_export()
|
||||
|
||||
class _Cells:
|
||||
def __init__(self, texts: list[str]) -> None:
|
||||
self._texts = texts
|
||||
|
||||
def count(self) -> int:
|
||||
return len(self._texts)
|
||||
|
||||
def nth(self, index: int) -> _Cell:
|
||||
return _Cell(self._texts[index])
|
||||
|
||||
class _Cell:
|
||||
def __init__(self, text: str, *, visible: bool = False) -> None:
|
||||
self._text = text
|
||||
self._visible = visible
|
||||
|
||||
def inner_text(self, timeout: int = 0) -> str:
|
||||
return self._text
|
||||
|
||||
def is_visible(self, timeout: int = 0) -> bool:
|
||||
return self._visible
|
||||
|
||||
@property
|
||||
def first(self):
|
||||
return self
|
||||
|
||||
class _Row:
|
||||
def __init__(self, name: str, description: str, status: str) -> None:
|
||||
self._cells = _Cells([name, "2026/7/9 04:45:45", description, status])
|
||||
|
||||
def is_visible(self, timeout: int = 0) -> bool:
|
||||
return True
|
||||
|
||||
def locator(self, selector: str) -> Any:
|
||||
if selector == "td":
|
||||
return self._cells
|
||||
return _Cell("Download", visible=selector.startswith("a"))
|
||||
|
||||
def get_by_role(self, role: str, name: str, exact: bool = False) -> _Cell:
|
||||
return _Cell("Download", visible=True)
|
||||
|
||||
class _Rows:
|
||||
def __init__(self, rows: list[_Row]) -> None:
|
||||
self._rows = rows
|
||||
|
||||
def count(self) -> int:
|
||||
return len(self._rows)
|
||||
|
||||
def nth(self, index: int) -> _Row:
|
||||
return self._rows[index]
|
||||
|
||||
class _Page:
|
||||
def __init__(self, rows: list[_Row]) -> None:
|
||||
self.frames: list = []
|
||||
self._rows = rows
|
||||
self.url = "https://wms-portal.craneww.com/#/scheduled-reports"
|
||||
|
||||
def locator(self, selector: str) -> _Rows:
|
||||
return _Rows(self._rows)
|
||||
|
||||
page = _Page([_Row("OnHandDetails.xlsx", "uuid-1", "Submitted")])
|
||||
status, locator = module._probe_scheduled_download_status(
|
||||
page,
|
||||
"uuid-1",
|
||||
env=lambda name, default="": default,
|
||||
)
|
||||
assert status == "Submitted"
|
||||
assert locator is None
|
||||
|
||||
page_ready = _Page([_Row("OnHandDetails.xlsx", "uuid-2", "Download")])
|
||||
status2, locator2 = module._probe_scheduled_download_status(
|
||||
page_ready,
|
||||
"uuid-2",
|
||||
env=lambda name, default="": default,
|
||||
)
|
||||
assert status2 == "Download"
|
||||
assert locator2 is not None
|
||||
|
||||
|
||||
def test_is_crane_login_blocking_ignores_login_flash_when_table_visible():
|
||||
"""reload 过渡态:登录框闪现但表格仍在时,不应判定为需要重登。"""
|
||||
module = _load_export()
|
||||
|
||||
class _Rows:
|
||||
def count(self) -> int:
|
||||
return 1
|
||||
|
||||
class _Page:
|
||||
frames: list = []
|
||||
url = "https://wms-portal.craneww.com/#/scheduled-reports"
|
||||
|
||||
def locator(self, selector: str) -> _Rows:
|
||||
return _Rows()
|
||||
|
||||
page = _Page()
|
||||
session = module._load_crane_session_module()
|
||||
original = session.is_crane_login_page
|
||||
session.is_crane_login_page = lambda _page: True
|
||||
try:
|
||||
assert module._is_crane_login_blocking(page) is False
|
||||
assert module._is_on_scheduled_reports_page(page) is True
|
||||
finally:
|
||||
session.is_crane_login_page = original
|
||||
|
||||
|
||||
def test_resolve_scheduled_report_file_name_prefers_navigation_config():
|
||||
"""scheduled_report_file_name 应优先于环境变量默认值。"""
|
||||
module = _load_export()
|
||||
name = module._resolve_scheduled_report_file_name(
|
||||
{"navigation": {"scheduled_report_file_name": "Custom.xlsx"}},
|
||||
env=lambda name, default="": default,
|
||||
)
|
||||
assert name == "Custom.xlsx"
|
||||
|
||||
|
||||
def test_resolve_download_mode_defaults_to_scheduled_report():
|
||||
"""未配置 download_mode 时默认走 scheduled_report。"""
|
||||
module = _load_export()
|
||||
assert module._resolve_download_mode({"navigation": {}}) == "scheduled_report"
|
||||
@@ -0,0 +1,166 @@
|
||||
"""crane_session 登录页识别与自动填写测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
|
||||
def _load_crane_session():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "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)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, *, visible: bool = True, enabled: bool = True) -> None:
|
||||
self.visible = visible
|
||||
self.enabled = enabled
|
||||
self.filled: list[str] = []
|
||||
self.clicked = False
|
||||
|
||||
@property
|
||||
def first(self) -> "_FakeLocator":
|
||||
return self
|
||||
|
||||
def is_visible(self, timeout: int = 0) -> bool:
|
||||
return self.visible
|
||||
|
||||
def is_enabled(self, timeout: int = 0) -> bool:
|
||||
return self.enabled
|
||||
|
||||
def fill(self, value: str, timeout: int = 0) -> None:
|
||||
self.filled.append(value)
|
||||
|
||||
def click(self, timeout: int = 0, force: bool = False) -> None:
|
||||
self.clicked = True
|
||||
|
||||
def evaluate(self, script: str) -> bool:
|
||||
return self.enabled
|
||||
|
||||
|
||||
class _FakePage:
|
||||
def __init__(self) -> None:
|
||||
self.frames: list[_FakePage] = []
|
||||
self.url = "https://wms-portal.craneww.com/"
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
lowered = selector.lower()
|
||||
if "user name" in lowered or "password" in lowered:
|
||||
return _FakeLocator(visible=True)
|
||||
if "is-primary" in lowered or "sign in" in lowered:
|
||||
return _FakeLocator(visible=True, enabled=True)
|
||||
return _FakeLocator(visible=False)
|
||||
|
||||
def get_by_label(self, label: str, exact: bool = False) -> _FakeLocator:
|
||||
return _FakeLocator(visible=label in {"User Name", "Password"})
|
||||
|
||||
def get_by_placeholder(self, placeholder: str, exact: bool = False) -> _FakeLocator:
|
||||
return _FakeLocator(visible=placeholder.startswith("Enter "))
|
||||
|
||||
def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator:
|
||||
return _FakeLocator(visible=role == "button" and name == "Sign in", enabled=True)
|
||||
|
||||
def wait_for_load_state(self, state: str, timeout: int = 0) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def test_is_crane_login_page_detects_username_placeholder():
|
||||
"""登录页应通过 Enter user name... / Enter password... placeholder 识别。"""
|
||||
module = _load_crane_session()
|
||||
page = _FakePage()
|
||||
assert module.is_crane_login_page(page) is True
|
||||
|
||||
|
||||
def test_maybe_auto_login_crane_fills_username_password_and_clicks_sign_in(monkeypatch):
|
||||
"""自动登录应依次填写用户名、密码并点击 Sign in。"""
|
||||
module = _load_crane_session()
|
||||
page = _FakePage()
|
||||
calls: list[tuple[str, str]] = []
|
||||
|
||||
def _fake_fill(
|
||||
page_arg,
|
||||
*,
|
||||
selector_env,
|
||||
value,
|
||||
env,
|
||||
browser_timeout_ms,
|
||||
fallback_selectors,
|
||||
label=None,
|
||||
placeholder=None,
|
||||
):
|
||||
calls.append((selector_env, value))
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(module, "_fill_crane_field", _fake_fill)
|
||||
login_page_states = iter([True, False])
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"is_crane_login_page",
|
||||
lambda page_arg: next(login_page_states, False),
|
||||
)
|
||||
monkeypatch.setattr(module, "_click_crane_login_submit", lambda *args, **kwargs: True)
|
||||
|
||||
module.maybe_auto_login_crane(
|
||||
page,
|
||||
env=lambda name, default="": {
|
||||
"FREIGHT_RPA_CRANE_USERNAME": "crane-user",
|
||||
"FREIGHT_RPA_CRANE_PASSWORD": "crane-pass",
|
||||
}.get(name, default),
|
||||
browser_timeout_ms=5_000,
|
||||
)
|
||||
|
||||
assert calls == [
|
||||
("FREIGHT_RPA_CRANE_USERNAME_SELECTOR", "crane-user"),
|
||||
("FREIGHT_RPA_CRANE_PASSWORD_SELECTOR", "crane-pass"),
|
||||
]
|
||||
|
||||
|
||||
def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
|
||||
"""Sign in 初始 disabled,填写凭据后应能定位到可点击按钮。"""
|
||||
module = _load_crane_session()
|
||||
page = _FakePage()
|
||||
states = iter([False, False, True])
|
||||
|
||||
def _fake_enabled(locator):
|
||||
return next(states, True)
|
||||
|
||||
monkeypatch.setattr(module, "_is_crane_button_enabled", _fake_enabled)
|
||||
|
||||
locator = module._find_crane_sign_in_button(
|
||||
page,
|
||||
selector_env="FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR",
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=3_000,
|
||||
)
|
||||
|
||||
assert locator is not None
|
||||
assert locator.enabled is True
|
||||
|
||||
|
||||
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
|
||||
"""batch 内 session 有效时不应重复 goto + login。"""
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_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)
|
||||
spec.loader.exec_module(worker)
|
||||
|
||||
page = MagicMock()
|
||||
login = MagicMock()
|
||||
ready = MagicMock()
|
||||
goto = MagicMock()
|
||||
monkeypatch.setattr(worker, "_is_crane_session_active", MagicMock(return_value=True))
|
||||
monkeypatch.setattr(worker, "_goto_crane_entry_url", goto)
|
||||
monkeypatch.setattr(worker, "_maybe_auto_login_crane", login)
|
||||
monkeypatch.setattr(worker, "_wait_for_crane_app_ready", ready)
|
||||
|
||||
worker._ensure_crane_session(page, "https://wms-portal.craneww.com/#/on-hand-details-query")
|
||||
|
||||
goto.assert_not_called()
|
||||
login.assert_not_called()
|
||||
ready.assert_called_once()
|
||||
@@ -112,3 +112,58 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue():
|
||||
)
|
||||
|
||||
assert selected.get("value") == "BYAWSATL01" or selected.get("label") == "BYAWSATL01"
|
||||
|
||||
|
||||
def test_fill_dsv_multi_select_parameter_supports_select_all_checkbox_dropdown():
|
||||
"""AWSAMS Warehouse 这类 checkbox 下拉应支持 select_all 和显式 selector。"""
|
||||
module = _load_module()
|
||||
payloads: list[dict[str, object]] = []
|
||||
|
||||
class _FakeLocator:
|
||||
first = None
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.first = self
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def input_value(self, timeout: int | None = None) -> str:
|
||||
return ""
|
||||
|
||||
def click(self, timeout: int | None = None, force: bool = False) -> None:
|
||||
return None
|
||||
|
||||
class _FakeReportRootLocator:
|
||||
def count(self) -> int:
|
||||
return 1
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str):
|
||||
if selector == "#ReportViewerMain":
|
||||
return _FakeReportRootLocator()
|
||||
return _FakeLocator()
|
||||
|
||||
def evaluate(self, script: str, payload: dict[str, object]) -> bool:
|
||||
payloads.append(payload)
|
||||
return True
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
|
||||
ok = module.fill_dsv_multi_select_parameter(
|
||||
_FakePage(),
|
||||
"Warehouse",
|
||||
["RTM"],
|
||||
selectors={
|
||||
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
|
||||
},
|
||||
select_all=True,
|
||||
browser_timeout_ms=lambda: 3_000,
|
||||
)
|
||||
|
||||
assert ok is True
|
||||
assert payloads[-1]["dropdownSelector"] == "#ReportViewerMain_ctl08_ctl17_divDropDown"
|
||||
assert payloads[-1]["selectAll"] is True
|
||||
@@ -1164,8 +1164,8 @@ def test_has_dsv_password_upgrade_prompt_does_not_match_generic_not_now_text():
|
||||
assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is False
|
||||
|
||||
|
||||
def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan():
|
||||
"""已经进入 s360 portal 时,应直接判定没有升级提示,避免在首页做长时间空扫描。"""
|
||||
def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch):
|
||||
"""portal 首页导航已可用时,应直接判定没有升级提示,避免在稳定首页做无效扫描。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
locator_calls = {"value": 0}
|
||||
|
||||
@@ -1175,12 +1175,41 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan():
|
||||
|
||||
def locator(self, selector: str):
|
||||
locator_calls["value"] += 1
|
||||
raise AssertionError("portal page should short-circuit before scanning locators")
|
||||
raise AssertionError("stable portal home should short-circuit before scanning locators")
|
||||
|
||||
monkeypatch.setattr(worker.dsv_session, "has_dsv_report_nav_usable", lambda page: True)
|
||||
|
||||
assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is False
|
||||
assert locator_calls["value"] == 0
|
||||
|
||||
|
||||
def test_has_dsv_password_upgrade_prompt_detects_maybe_later_on_portal(monkeypatch):
|
||||
"""portal 上若升级弹窗挡住首页,仍应识别“也许以后”按钮。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, selector: str) -> None:
|
||||
self.selector = selector
|
||||
self.first = self
|
||||
|
||||
def is_visible(self, timeout: int | None = None) -> bool:
|
||||
return self.selector == 'button.dbs-sims-button-secondary:has-text("也许以后")'
|
||||
|
||||
def inner_text(self, timeout: int | None = None) -> str:
|
||||
return ""
|
||||
|
||||
class _FakePage:
|
||||
url = "https://s360.dbschenker.com/main/portal"
|
||||
frames: list[object] = []
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator(selector)
|
||||
|
||||
monkeypatch.setattr(worker.dsv_session, "has_dsv_report_nav_usable", lambda page: False)
|
||||
|
||||
assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is True
|
||||
|
||||
|
||||
def test_wait_for_dsv_home_ready_skips_duplicate_upgrade_prompt_check(monkeypatch):
|
||||
"""首页已可探测或 app wait 返回后,若无升级提示强特征,不应再次进入升级提示处理。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -3,13 +3,25 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
|
||||
def _load_worker():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_param_test", module_path)
|
||||
return _load_rpa_module("freight_rpa_worker")
|
||||
|
||||
|
||||
def _load_dsv_report_export():
|
||||
return _load_rpa_module("dsv_report_export")
|
||||
|
||||
|
||||
def _load_rpa_module(module_name: str):
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py"
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
sys.path.insert(0, scripts_dir)
|
||||
spec = importlib.util.spec_from_file_location(f"{module_name}_param_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
@@ -18,11 +30,11 @@ def _load_worker():
|
||||
|
||||
def test_fill_report_parameter_multi_select(monkeypatch):
|
||||
"""multi_select 应对每个值尝试多选填充,而非只取第一个。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
calls: list[tuple[str, str, list[str]]] = []
|
||||
|
||||
def _fake_multi(page_arg, selector_env, label, values):
|
||||
def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False):
|
||||
calls.append((selector_env, label, list(values)))
|
||||
|
||||
monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi)
|
||||
@@ -38,6 +50,51 @@ def test_fill_report_parameter_multi_select(monkeypatch):
|
||||
assert calls == [("FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
|
||||
|
||||
|
||||
def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
|
||||
"""select_all 应传入 DSV checkbox 下拉处理,供 AWSAMS Warehouse 全选。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
calls: list[dict[str, object]] = []
|
||||
|
||||
def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False):
|
||||
calls.append(
|
||||
{
|
||||
"selector_env": selector_env,
|
||||
"label": label,
|
||||
"values": list(values),
|
||||
"selectors": selectors,
|
||||
"select_all": select_all,
|
||||
}
|
||||
)
|
||||
|
||||
selectors = {
|
||||
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
|
||||
}
|
||||
monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi)
|
||||
worker._fill_report_parameter(
|
||||
page,
|
||||
{
|
||||
"name": "Warehouse",
|
||||
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
|
||||
"mode": "multi_select",
|
||||
"select_all": True,
|
||||
"selectors": selectors,
|
||||
"values": ["RTM"],
|
||||
},
|
||||
)
|
||||
assert calls == [
|
||||
{
|
||||
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
|
||||
"label": "Warehouse",
|
||||
"values": ["RTM"],
|
||||
"selectors": selectors,
|
||||
"select_all": True,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
|
||||
"""单票 DSV 导出应走与批量相同的 session + export 函数。"""
|
||||
worker = _load_worker()
|
||||
@@ -47,20 +104,40 @@ def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"parameters": [{"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "selector_env": "X"}],
|
||||
}
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", MagicMock())
|
||||
export_mock = MagicMock(return_value="download")
|
||||
monkeypatch.setattr(worker, "_export_dsv_inventory_source", export_mock)
|
||||
monkeypatch.setattr(worker.dsv_driver, "download_dsv360_inventory", export_mock)
|
||||
|
||||
result = worker._download_dsv360_inventory(page, {"task_no": "SN-1"}, source)
|
||||
|
||||
worker._ensure_dsv_session.assert_called_once_with(page, "https://s360.dbschenker.com/")
|
||||
export_mock.assert_called_once_with(page, {"task_no": "SN-1"}, source)
|
||||
assert result == "download"
|
||||
|
||||
|
||||
def test_dsv_report_has_inventory_data_rows_false_when_table_has_only_three_rows(monkeypatch):
|
||||
"""DSV 报表明细表只有 3 行时应视为无库存数据,不进入导出。"""
|
||||
worker = _load_dsv_report_export()
|
||||
frame = MagicMock()
|
||||
frame.evaluate.return_value = False
|
||||
monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page: (0, frame, {}))
|
||||
|
||||
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is False
|
||||
frame.evaluate.assert_called_once()
|
||||
|
||||
|
||||
def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monkeypatch):
|
||||
"""DSV 报表明细表第 4 行后存在非空行时应允许继续导出。"""
|
||||
worker = _load_dsv_report_export()
|
||||
frame = MagicMock()
|
||||
frame.evaluate.return_value = True
|
||||
monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page: (0, frame, {}))
|
||||
|
||||
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is True
|
||||
frame.evaluate.assert_called_once()
|
||||
|
||||
|
||||
def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch):
|
||||
"""批量 navigation 变化时应 goto entry 并检测 session。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
login = MagicMock()
|
||||
home = MagicMock()
|
||||
@@ -79,7 +156,7 @@ def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch):
|
||||
|
||||
def test_dsv_sources_share_navigation_when_program_report_match():
|
||||
"""同 program/report 导航的 AWSBI 子仓应判定为可复用参数页。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_dsv_report_export()
|
||||
nav = {
|
||||
"program_group": "Bison",
|
||||
"program_label": "AWSBI",
|
||||
@@ -93,7 +170,7 @@ def test_dsv_sources_share_navigation_when_program_report_match():
|
||||
|
||||
def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches(monkeypatch):
|
||||
"""同 navigation 的第二步应 reload 参数页而非 reset 首页。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
ensure = MagicMock()
|
||||
reset = MagicMock()
|
||||
@@ -120,7 +197,7 @@ def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches(
|
||||
|
||||
def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatch):
|
||||
"""program/report 变化时仍应回 portal 首页。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
reset = MagicMock()
|
||||
reuse = MagicMock()
|
||||
@@ -150,7 +227,7 @@ def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatc
|
||||
|
||||
def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
|
||||
"""同 entry_url 且 session 有效时 reset 不应再触发 auto_login。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
login = MagicMock()
|
||||
home = MagicMock()
|
||||
@@ -171,7 +248,7 @@ def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
|
||||
|
||||
def test_ensure_dsv_session_skips_login_when_session_active(monkeypatch):
|
||||
"""batch 首条前若 session 已有效,ensure 不应 goto + login。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
login = MagicMock()
|
||||
home = MagicMock()
|
||||
@@ -191,7 +268,7 @@ def test_ensure_dsv_session_skips_login_when_session_active(monkeypatch):
|
||||
|
||||
def test_prepare_dsv_batch_reuses_form_for_different_source_code_same_entry(monkeypatch):
|
||||
"""source_code 不同但 navigation/entry_url 一致时,第二步应复用参数页且不 reset 登录。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
ensure = MagicMock()
|
||||
reset = MagicMock()
|
||||
@@ -228,7 +305,7 @@ def test_prepare_dsv_batch_reuses_form_for_different_source_code_same_entry(monk
|
||||
|
||||
def test_is_dsv_oauth_handshake_url_detects_pingfederate_page():
|
||||
"""authorization.oauth2 应识别为 OAuth 握手中间页。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_rpa_module("dsv_auth")
|
||||
url = (
|
||||
"https://auth.dbschenker.com/as/authorization.oauth2?"
|
||||
"response_type=code&client_id=contract-logistics-360"
|
||||
@@ -240,7 +317,7 @@ def test_is_dsv_oauth_handshake_url_detects_pingfederate_page():
|
||||
|
||||
def test_goto_dsv_entry_url_tolerates_domcontentloaded_timeout_on_auth_redirect(monkeypatch):
|
||||
"""goto 超时但已跳转到 auth 域时不应抛错。"""
|
||||
worker = _load_worker()
|
||||
worker = _load_rpa_module("dsv_session")
|
||||
page = MagicMock()
|
||||
page.url = "https://auth.dbschenker.com/as/authorization.oauth2?response_type=code"
|
||||
|
||||
|
||||
@@ -46,6 +46,76 @@ def test_fresh_snapshot_is_reused(app, tmp_path):
|
||||
assert is_snapshot_fresh(found)
|
||||
|
||||
|
||||
def test_snapshot_uses_site_id_as_matching_warehouse(app, tmp_path):
|
||||
"""DSV 子仓导出入库后,应用 site_id 作为库存匹配与发货 Excel 的 warehouse id。"""
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
xlsx = tmp_path / "stock.xlsx"
|
||||
wb = Workbook()
|
||||
wb.active.append(["sku", "qty"])
|
||||
wb.active.append(["A001", 10])
|
||||
wb.save(xlsx)
|
||||
wb.close()
|
||||
|
||||
source = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01")
|
||||
assert source is not None
|
||||
assert source["site_id"] == "AWSBI"
|
||||
assert source["warehouse_id"] == "BYAWSATL01"
|
||||
|
||||
with app.app_context():
|
||||
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
|
||||
task = ShippingTask(task_no="SN-SNAPSHOT-SITE", source_type="manual", process_status="waiting_inventory")
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
link = link_snapshot_to_task(task, inv, reason="reuse_latest")
|
||||
db.session.commit()
|
||||
|
||||
assert inv.warehouse_id == "AWSBI"
|
||||
assert (inv.source_query_json or {}).get("export_warehouse_id") == "BYAWSATL01"
|
||||
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI") is not None
|
||||
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "BYAWSATL01") is None
|
||||
assert link is not None
|
||||
assert link.matched_warehouse_id == "AWSBI"
|
||||
|
||||
|
||||
def test_snapshot_without_site_id_uses_inventory_excel_warehouse_id(app, tmp_path):
|
||||
"""无配置 site_id 时,快照 warehouse_id 应取库存 Excel 内的 Warehouse ID。"""
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
xlsx = tmp_path / "crane_stock.xlsx"
|
||||
wb = Workbook()
|
||||
wb.active.append(["Warehouse ID", "sku", "qty"])
|
||||
wb.active.append(["TZR2", "A001", 10])
|
||||
wb.save(xlsx)
|
||||
wb.close()
|
||||
|
||||
source = {
|
||||
"source_code": "CRANE",
|
||||
"source_type": "crane_footprint",
|
||||
"site_id": "",
|
||||
"warehouse_id": "",
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
|
||||
task = ShippingTask(task_no="SN-SNAPSHOT-EXCEL-WH", source_type="manual", process_status="waiting_inventory")
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
link = link_snapshot_to_task(task, inv, reason="rpa_callback")
|
||||
db.session.commit()
|
||||
|
||||
assert inv.warehouse_id == "TZR2"
|
||||
assert (inv.source_query_json or {}).get("site_id") is None
|
||||
assert (inv.source_query_json or {}).get("excel_warehouse_id") == "TZR2"
|
||||
assert (inv.source_query_json or {}).get("warehouse_id_source") == "inventory_excel"
|
||||
assert link is not None
|
||||
assert link.matched_warehouse_id == "TZR2"
|
||||
|
||||
|
||||
def test_expired_snapshot_not_reused(app, tmp_path):
|
||||
"""过期快照不应被 find_latest_ready_snapshot 返回。"""
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
|
||||
|
||||
@@ -19,8 +19,9 @@ def test_inventory_sources_yaml_loads(app):
|
||||
reload_inventory_sources_config()
|
||||
source = get_inventory_source("DSV360_AWSDU")
|
||||
assert source is not None
|
||||
assert source["warehouse_id"] == "AWSDU"
|
||||
assert source["source_type"] == "dsv360"
|
||||
assert source["site_id"] == "AWSDU"
|
||||
assert source["warehouse_id"] == ""
|
||||
assert source["query"]["program_label"]
|
||||
|
||||
|
||||
@@ -29,6 +30,7 @@ def test_build_rpa_inventory_source_keeps_legacy_query(app):
|
||||
with app.app_context():
|
||||
payload = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01")
|
||||
assert payload is not None
|
||||
assert payload["site_id"] == "AWSBI"
|
||||
assert payload["warehouse_id"] == "BYAWSATL01"
|
||||
assert payload["query"]["warehouse_code"] == "BYAWSATL01"
|
||||
assert payload["query"]["program_label"] == "AWSBI"
|
||||
@@ -37,6 +39,23 @@ def test_build_rpa_inventory_source_keeps_legacy_query(app):
|
||||
assert payload["parameters"][0]["name"] == "Warehouse"
|
||||
|
||||
|
||||
def test_awsams_warehouse_uses_multi_select_all(app):
|
||||
"""AWSAMS Warehouse 是 SSRS checkbox 下拉,配置应显式走 multi_select + select_all。"""
|
||||
with app.app_context():
|
||||
reload_inventory_sources_config()
|
||||
payload = build_rpa_inventory_source("DSV360_AWSAMS")
|
||||
assert payload is not None
|
||||
warehouse_param = next(item for item in payload["parameters"] if item["name"] == "Warehouse")
|
||||
assert warehouse_param["mode"] == "multi_select"
|
||||
assert warehouse_param["select_all"] is True
|
||||
assert warehouse_param["values"] == ["RTM"]
|
||||
assert warehouse_param["selectors"] == {
|
||||
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
|
||||
}
|
||||
|
||||
|
||||
def test_duplicate_source_code_raises(app, tmp_path):
|
||||
"""source_code 重复时加载应报错。"""
|
||||
bad = tmp_path / "bad_sources.json"
|
||||
@@ -45,8 +64,8 @@ def test_duplicate_source_code_raises(app, tmp_path):
|
||||
{
|
||||
"version": 1,
|
||||
"sources": [
|
||||
{"source_code": "X1", "enabled": true, "site": "dsv360", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []},
|
||||
{"source_code": "X1", "enabled": true, "site": "dsv360", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []}
|
||||
{"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []},
|
||||
{"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []}
|
||||
]
|
||||
}
|
||||
""",
|
||||
@@ -58,6 +77,42 @@ def test_duplicate_source_code_raises(app, tmp_path):
|
||||
reload_inventory_sources_config()
|
||||
|
||||
|
||||
def test_dsv_source_requires_site_id(app, tmp_path):
|
||||
"""DSV 源必须显式配置 site_id,避免把站点和仓库混用。"""
|
||||
bad = tmp_path / "bad_sources.yaml"
|
||||
bad.write_text(
|
||||
"""
|
||||
version: 1
|
||||
sources:
|
||||
- source_code: DSV360_BAD
|
||||
enabled: true
|
||||
source_type: dsv360
|
||||
warehouse_id: AWSBI
|
||||
entry_url: http://x
|
||||
navigation: {}
|
||||
parameters: []
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad)
|
||||
with app.app_context():
|
||||
with pytest.raises(InventorySourceConfigError, match="site_id is required"):
|
||||
reload_inventory_sources_config()
|
||||
|
||||
|
||||
def test_build_rpa_inventory_source_crane_has_no_site_or_warehouse_requirement(app):
|
||||
"""Crane 源不要求配置 site_id/warehouse_id,导出走 Schedule Report 异步下载。"""
|
||||
with app.app_context():
|
||||
reload_inventory_sources_config()
|
||||
payload = build_rpa_inventory_source("CRANE")
|
||||
assert payload is not None
|
||||
assert payload["source_type"] == "crane_footprint"
|
||||
assert payload["site_id"] == ""
|
||||
assert payload["warehouse_id"] == ""
|
||||
assert payload["parameters"] == []
|
||||
assert payload["navigation"]["download_mode"] == "scheduled_report"
|
||||
|
||||
|
||||
def test_match_aliases_available_via_list(app):
|
||||
"""list_inventory_sources 应包含 match_aliases 供规则匹配。"""
|
||||
with app.app_context():
|
||||
@@ -65,6 +120,6 @@ def test_match_aliases_available_via_list(app):
|
||||
codes = {item["source_code"] for item in list_inventory_sources()}
|
||||
assert "DSV360_AWSDU" in codes
|
||||
assert "DSV360_AWSBI_BYAWSATL01" in codes
|
||||
assert "CRANE_TZR2" in codes
|
||||
assert "CRANE" in codes
|
||||
awsbi_count = sum(1 for item in list_inventory_sources() if str(item.get("source_code", "")).startswith("DSV360_AWSBI_"))
|
||||
assert awsbi_count == 25
|
||||
Reference in new issue
Block a user