Files
syops/scripts/rpa/dsv_export_batch_smoke.py
T

227 lines
8.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
scripts/rpa/dsv_export_batch_smoke.py
用途:本地验证 DSV 360 同一浏览器 session 内连续导出 3 份库存 Excel。
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、shipping_inventory_sources.yaml、freight_rpa_worker。
逻辑:复用 worker 批量导出循环(一次登录 + reset 入口),不依赖 HXOPS callback。
场景:
warehouse — 同一 source_code / 同一 3lv 报表,仅 Warehouse 参数变化
source_code — 三个不同 source_code(YAML 中独立配置项)
用法:
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py warehouse
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py source_code
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py all
"""
from __future__ import annotations
import importlib.util
import json
import os
import shutil
import sys
import tempfile
import time
import traceback
from copy import deepcopy
from datetime import datetime
from pathlib import Path
from typing import Any
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _load_worker():
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _load_export_smoke_helpers():
module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_smoke.py"
spec = importlib.util.spec_from_file_location("dsv_export_smoke_batch", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _with_warehouse(source: dict[str, Any], warehouse: str, *, keep_source_code: bool) -> dict[str, Any]:
"""
克隆 source 并替换 Warehouse 参数与 query。
keep_source_code=True 时用于「同 source、仅 Warehouse 变化」场景。
"""
cloned = deepcopy(source)
wh = str(warehouse).strip()
if not keep_source_code:
cloned["source_code"] = f"DSV360_AWSBI_{wh}"
cloned["warehouse_id"] = wh
cloned["warehouse_code"] = wh
query = dict(cloned.get("query") or {})
query["warehouse_code"] = wh
cloned["query"] = query
parameters = []
for item in cloned.get("parameters") or []:
if not isinstance(item, dict):
continue
param = dict(item)
if str(param.get("name") or "").lower() == "warehouse":
param["values"] = [wh]
parameters.append(param)
cloned["parameters"] = parameters
return cloned
def _build_warehouse_scenario_sources() -> list[dict[str, Any]]:
"""场景 1:同一 source_code,3lv 报表不变,仅 Warehouse 下拉值变化。"""
helper = _load_export_smoke_helpers()
base = helper._build_source_from_config("DSV360_AWSBI_BYAWSCMH01")
warehouses = ["BYAWSATL01", "BYAWSCMH01", "BYAWSAVP01"]
return [_with_warehouse(base, wh, keep_source_code=True) for wh in warehouses]
def _build_source_code_scenario_sources() -> list[dict[str, Any]]:
"""场景 2:三个独立 source_code。"""
helper = _load_export_smoke_helpers()
codes = [
"DSV360_AWSBI_BYAWSATL01",
"DSV360_AWSBI_BYAWSCMH01",
"DSV360_AWSBI_BYAWSAVP01",
]
return [helper._build_source_from_config(code) for code in codes]
def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]], drop_dir: Path) -> list[dict[str, Any]]:
"""
在同一 DSV session 内连续导出多份库存。
核心逻辑:与 _handle_inventory_batch_trigger 浏览器分支一致,但不 POST callback。
"""
run_no = f"BATCH-SMOKE-{scenario.upper()}-{datetime.now().strftime('%Y%m%d%H%M%S')}"
trigger = {"run_no": run_no, "task_no": run_no}
entry_url = str((sources[0] or {}).get("entry_url") or "https://s360.dbschenker.com/").strip()
results: list[dict[str, Any]] = []
started = time.monotonic()
playwright = context = runtime_profile_dir = None
try:
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
export_fn = worker._export_dsv_inventory_source
previous_source: dict[str, Any] | None = None
for index, source in enumerate(sources):
code = str(source.get("source_code") or "")
wh = str(source.get("warehouse_id") or source.get("warehouse_code") or "")
print(
f"[batch-smoke] scenario={scenario} step={index + 1}/{len(sources)} "
f"source_code={code} warehouse={wh}"
)
try:
skip_navigation = worker._prepare_dsv_batch_export_step(
page,
entry_url,
previous_source,
source,
index=index,
)
download = export_fn(page, trigger, source, skip_navigation=skip_navigation)
out_file = worker._save_batch_download(download, drop_dir, run_no, source)
size_kb = out_file.stat().st_size / 1024
results.append(
{
"source_code": code,
"warehouse_id": wh,
"success": True,
"file_path": str(out_file),
"size_kb": round(size_kb, 1),
}
)
print(f"[batch-smoke] OK {code}/{wh} -> {out_file.name} ({size_kb:.1f} KB)")
except Exception as exc:
results.append(
{
"source_code": code,
"warehouse_id": wh,
"success": False,
"error_message": str(exc),
}
)
print(f"[batch-smoke] FAIL {code}/{wh}: {exc}", file=sys.stderr)
traceback.print_exc()
previous_source = source
finally:
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
if runtime_profile_dir is not None:
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
elapsed_s = int(time.monotonic() - started)
ok = sum(1 for item in results if item.get("success"))
print(
f"[batch-smoke] scenario={scenario} done success={ok}/{len(results)} "
f"elapsed={elapsed_s}s drop_dir={drop_dir}"
)
return results
def _run_scenario(worker: Any, scenario: str) -> int:
if scenario == "warehouse":
sources = _build_warehouse_scenario_sources()
elif scenario == "source_code":
sources = _build_source_code_scenario_sources()
else:
raise ValueError(f"unknown scenario: {scenario}")
drop_dir = Path(tempfile.mkdtemp(prefix=f"dsv_batch_{scenario}_"))
print(f"[batch-smoke] scenario={scenario} exports={len(sources)} drop_dir={drop_dir}")
for index, source in enumerate(sources, start=1):
print(
f"[batch-smoke] plan[{index}] source_code={source.get('source_code')} "
f"warehouse={source.get('warehouse_id')} "
f"query={json.dumps(source.get('query') or {}, ensure_ascii=False)}"
)
results = _run_batch_exports(worker, scenario, sources, drop_dir)
if not results or not all(item.get("success") for item in results):
return 2
return 0
def main() -> int:
scenario_arg = (sys.argv[1] if len(sys.argv) > 1 else "all").strip().lower()
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true")
os.environ.setdefault(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile",
)
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
worker = _load_worker()
if not worker._env("FREIGHT_RPA_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"):
print("[batch-smoke] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD")
return 1
scenarios = ["warehouse", "source_code"] if scenario_arg == "all" else [scenario_arg]
exit_code = 0
for scenario in scenarios:
if scenario not in {"warehouse", "source_code"}:
print(f"[batch-smoke] 未知场景: {scenario}(可用 warehouse / source_code / all)")
return 1
print(f"\n[batch-smoke] ===== 开始场景: {scenario} =====")
code = _run_scenario(worker, scenario)
exit_code = max(exit_code, code)
return exit_code
if __name__ == "__main__":
sys.exit(main())