Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-09-07 15:09:54 +08:00
commit 7329ccd179
17 files changed
+1195 -184

No files matched your search

+155 -5
View File
@@ -623,6 +623,155 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp
assert not log_path.exists()
def _load_worker_disk_cleanup():
"""加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
module_path = _repo_root() / "scripts" / "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
module = importlib.util.module_from_spec(spec)
# dataclass 在装饰阶段会查 sys.modules;动态加载须先登记。
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypatch, tmp_path):
"""
超过保留期的归档应删除;进行中的 trigger、会话 Profile、cleanup_queue 必须保留。
断言意图:验证磁盘清理只碰“归档/临时物”,不误删业务进行中文件。
"""
cleanup = _load_worker_disk_cleanup()
now = time.time()
old = now - (10 * 86400)
recent = now - 3600
inv_trigger = tmp_path / "inventory_triggers"
upload_trigger = tmp_path / "upload_triggers"
drop = tmp_path / "inventory_drop"
queue = tmp_path / "upload_queue"
profiles = tmp_path / "browser_profile"
logs = tmp_path / "logs"
for path in (
inv_trigger / "processed",
inv_trigger / "failed",
upload_trigger / "processed",
drop / "processed",
drop / ".hxops_quarantine",
drop / ".cleanup_queue",
drop / ".cleanup_failed",
queue,
profiles,
logs,
):
path.mkdir(parents=True)
active_trigger = inv_trigger / "inventory_export_SN-ACTIVE.json"
active_trigger.write_text("{}", encoding="utf-8")
os.utime(active_trigger, (old, old))
stale_processed = inv_trigger / "processed" / "inventory_export_SN-OLD.json"
stale_processed.write_text("{}", encoding="utf-8")
os.utime(stale_processed, (old, old))
fresh_processed = inv_trigger / "processed" / "inventory_export_SN-NEW.json"
fresh_processed.write_text("{}", encoding="utf-8")
os.utime(fresh_processed, (recent, recent))
stale_drop = drop / "processed" / "inventory_OLD.xlsx"
stale_drop.write_bytes(b"xlsx")
os.utime(stale_drop, (old, old))
stale_root_drop = drop / "inventory_STALE.xlsx"
stale_root_drop.write_bytes(b"xlsx")
os.utime(stale_root_drop, (old, old))
cleanup_job = drop / ".cleanup_queue" / "move_abc.json"
cleanup_job.write_text("{}", encoding="utf-8")
os.utime(cleanup_job, (old, old))
stale_queue = queue / "upload_OLD.xlsx"
stale_queue.write_bytes(b"xlsx")
os.utime(stale_queue, (old, old))
log_path = logs / "worker.log"
log_path.write_text("current", encoding="utf-8")
stale_backup = Path(f"{log_path}.1")
stale_backup.write_text("old-backup", encoding="utf-8")
os.utime(stale_backup, (old, old))
session_profile = profiles / "dsv360__DEFAULT_session"
session_profile.mkdir()
(session_profile / "Cookies").write_text("keep", encoding="utf-8")
os.utime(session_profile, (old, old))
orphan_run = profiles / "run_orphan"
orphan_run.mkdir()
(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")
stats = cleanup.run_worker_disk_cleanup(
inventory_trigger_dir=inv_trigger,
upload_trigger_dir=upload_trigger,
drop_dir=drop,
upload_queue_dir=queue,
browser_profile_dir=profiles,
log_file=log_path,
now_unix=now,
)
assert not stale_processed.exists()
assert fresh_processed.exists()
assert active_trigger.exists()
assert not stale_drop.exists()
assert not stale_root_drop.exists()
assert cleanup_job.exists()
assert not stale_queue.exists()
assert log_path.exists()
assert not stale_backup.exists()
assert session_profile.exists()
assert not orphan_run.exists()
assert stats.deleted_files >= 4
assert stats.deleted_dirs >= 1
def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path):
"""DISK_RETENTION_DAYS<=0 时不删归档;孤儿 Profile 仍可按独立配置清理。"""
cleanup = _load_worker_disk_cleanup()
now = time.time()
old = now - (10 * 86400)
inv_trigger = tmp_path / "inventory_triggers"
processed = inv_trigger / "processed"
profiles = tmp_path / "browser_profile"
processed.mkdir(parents=True)
profiles.mkdir(parents=True)
stale_processed = processed / "old.json"
stale_processed.write_text("{}", encoding="utf-8")
os.utime(stale_processed, (old, old))
orphan_run = profiles / "run_orphan"
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")
cleanup.run_worker_disk_cleanup(
inventory_trigger_dir=inv_trigger,
browser_profile_dir=profiles,
now_unix=now,
)
assert stale_processed.exists()
assert not orphan_run.exists()
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。"""
worker = _load_freight_rpa_worker()
@@ -1483,8 +1632,8 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo
assert worker._should_cleanup_browser_profile(profile_dir) is False
def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_path):
"""超过 TTL 的持久 Profile 应被清空重建,迫使重新登录。"""
def test_prepare_reusable_session_profile_keeps_existing_dir(tmp_path):
"""持久 Profile 不按本地时间清空;已有内容应保留供站点会话继续复用。"""
worker = _load_freight_rpa_worker()
profile_dir = tmp_path / "dsv360__OLD_session"
profile_dir.mkdir(parents=True)
@@ -1495,7 +1644,6 @@ def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_pat
json.dumps({"created_at_unix": created, "connector_type": "dsv360", "profile_code": "OLD"}),
encoding="utf-8",
)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24")
prepared = worker._prepare_reusable_session_profile(
profile_dir,
@@ -1504,9 +1652,11 @@ def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_pat
)
assert prepared == profile_dir
assert not stale_marker.exists()
assert stale_marker.exists()
meta = json.loads((profile_dir / ".hxops_rpa_session_meta.json").read_text(encoding="utf-8"))
assert float(meta["created_at_unix"]) > created
assert float(meta["created_at_unix"]) == created
assert "ttl_hours" not in meta
def test_is_dsv_username_page_ignores_login_method_page_text():
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
@@ -612,6 +612,65 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
def test_stage_context_hides_inventory_actions_while_rpa_running(app) -> None:
"""库存 RPA queued/running 时,工作台 preparation 行不得下发重试 RPA 动作。
与 Case 投影同源:inventory_rpa_is_running 在行循环外算一次;运行中 actions 为空。
"""
from app.models import ShippingTaskInventoryRpaAttempt
with app.app_context():
user = User(username='ui-rpa-running', email='ui-rpa-running@example.com')
db.session.add(user)
db.session.flush()
task = ShippingOrderTask(task_no='OT-UI-RPA-RUNNING', user_id=user.id, stage='inventory_matching')
db.session.add(task)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=1, schema_version_id=1,
order_data_version=1, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
task.order_snapshot_id = snapshot.id
snapshot_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0, line_no=1,
reservation_id='RSV-RPA', part_number='PN-RPA', qty='10', field_values_json={},
)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
snapshot_line_id=snapshot_line.id,
line_no=1,
line_index=0,
match_result='matched',
inventory_status='ready',
required_qty='10',
available_qty='7',
matched_qty='7',
shortage_qty='3',
reservation_id='RSV-RPA',
part_number='PN-RPA',
inventory_source_code='DBS_DUB',
is_current=True,
))
db.session.add(ShippingTaskInventoryRpaAttempt(
task_no=task.task_no,
source_code='DBS_DUB',
attempt_no=1,
source_run_no='PSR-UI-RPA-1',
status='running',
))
db.session.commit()
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
line = preparation['lines'][0]
# 关键断言:RPA 运行中必须清空库存动作,前端 Bot 不得渲染/触发。
assert line['user_line_status'] == 'acquiring_inventory'
assert line['inventory_allowed_actions'] == []
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monkeypatch) -> None:
"""行级 source_conflict 与候选源只读 Match;Excel 未生成时下发 source_options。"""
monkeypatch.setattr(
@@ -59,7 +59,7 @@ def test_inventory_running_is_not_inferred_from_stage_automation_job():
"""阶段推进 Job 运行中但未创建库存 Attempt 时,明细不得显示获取库存中。"""
task = SimpleNamespace(task_no='OT-TEST-1')
with patch(
'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query',
'app.services.shipping_notice.line_inventory_match_projection.ShippingTaskInventoryRpaAttempt.query',
) as query:
query.filter.return_value.first.return_value = None
assert _inventory_rpa_is_running(task) is False
@@ -69,7 +69,7 @@ def test_inventory_running_requires_queued_or_running_attempt():
"""只有库存 RPA Attempt queued/running 才能投影 acquiring_inventory。"""
task = SimpleNamespace(task_no='OT-TEST-2')
with patch(
'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query',
'app.services.shipping_notice.line_inventory_match_projection.ShippingTaskInventoryRpaAttempt.query',
) as query:
query.filter.return_value.first.return_value = SimpleNamespace(status='queued')
assert _inventory_rpa_is_running(task) is True