310 lines
11 KiB
Python
310 lines
11 KiB
Python
import pytest
|
||
from pathlib import Path
|
||
|
||
|
||
def parse_api_error(body: dict) -> dict:
|
||
"""
|
||
从标准 API 错误 envelope 中提取 error 子对象,供测试断言 error.code / details。
|
||
"""
|
||
assert isinstance(body, dict)
|
||
assert body.get('success') is False
|
||
error = body.get('error')
|
||
assert isinstance(error, dict)
|
||
return error
|
||
|
||
|
||
def parse_api_data(body: dict):
|
||
"""
|
||
从标准 API 成功 envelope 中提取 data;legacy 裸 JSON 则原样返回。
|
||
"""
|
||
assert isinstance(body, dict)
|
||
if body.get('success') is True:
|
||
return body.get('data')
|
||
return body
|
||
|
||
|
||
def flatten_api_error(body: dict) -> dict:
|
||
"""
|
||
将 envelope 错误扁平化为 { error_code, error, ...details },便于 WeCom 等历史测试断言。
|
||
"""
|
||
error = parse_api_error(body)
|
||
flat = dict(error.get('details') or {})
|
||
flat['error_code'] = error.get('code')
|
||
flat['error'] = error.get('message')
|
||
return flat
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def _isolate_persisted_settings(monkeypatch, tmp_path):
|
||
"""Prevent tests from inheriting the developer's local ``backend/.env``.
|
||
|
||
``apply_env_settings`` is called eagerly in ``create_app`` and on every
|
||
request via the ``before_request`` hook. If the dev's real ``backend/.env``
|
||
contains ``WECOM_AUTO_CREATE_USER=true`` (or any other WECOM_* override),
|
||
those values would silently overwrite the explicit ``app.config.update(...)``
|
||
calls inside test fixtures. Routing reads to a tmp path makes every test
|
||
start from a clean slate.
|
||
"""
|
||
from app.core.config import env_persistence
|
||
|
||
monkeypatch.setattr(env_persistence, 'LEGACY_BACKEND_ENV_PATH', tmp_path / 'isolated.env')
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def _shipping_notice_stable_auto_config(app, request, monkeypatch):
|
||
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
|
||
tmp_path = request.getfixturevalue("tmp_path")
|
||
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
|
||
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(
|
||
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
|
||
)
|
||
if request.node.get_closest_marker("auto_rpa"):
|
||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||
monkeypatch.setattr(
|
||
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||
lambda: None,
|
||
)
|
||
return
|
||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
|
||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
|
||
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True
|
||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||
app.config["ENV_NAME"] = "dev"
|
||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
|
||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||
from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
|
||
|
||
reset_rpa_worker_heartbeat_state_for_tests()
|
||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests
|
||
|
||
reset_rpa_worker_alert_state_for_tests()
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def _shipping_test_default_destination(monkeypatch, request):
|
||
"""
|
||
为未提供目的地线索的发货通知单测注入 Dublin,以唯一命中 DSV360_AWSDU。
|
||
标记 inventory_source_gate 的用例跳过,避免干扰库存源门禁专项测试。
|
||
"""
|
||
if request.node.get_closest_marker("inventory_source_gate"):
|
||
return
|
||
|
||
from app.services.shipping_notice import extract as extract_mod
|
||
import app.services.shipping_notice.task_workflow as task_workflow_mod
|
||
|
||
original = extract_mod.extract_notice_fields
|
||
|
||
def _extract_with_default_destination(*args, structured=None, **kwargs):
|
||
patched = structured
|
||
if isinstance(structured, dict):
|
||
patched = dict(structured)
|
||
has_dest = any(
|
||
str(patched.get(key) or "").strip()
|
||
for key in ("ship_to", "destination_city", "destination_port", "destination_country", "warehouse_hint")
|
||
) or isinstance(patched.get("destination"), dict)
|
||
if not has_dest:
|
||
for line in patched.get("lines") or []:
|
||
if isinstance(line, dict) and any(
|
||
str(line.get(key) or "").strip()
|
||
for key in ("ship_to", "destination_city", "destination_port", "warehouse_hint")
|
||
):
|
||
has_dest = True
|
||
break
|
||
if not has_dest:
|
||
patched.setdefault("ship_to", "Dublin")
|
||
patched.setdefault("destination", {"city": "Dublin", "country": "IE"})
|
||
return original(*args, structured=patched, **kwargs)
|
||
|
||
monkeypatch.setattr(extract_mod, "extract_notice_fields", _extract_with_default_destination)
|
||
monkeypatch.setattr(task_workflow_mod, "extract_notice_fields", _extract_with_default_destination)
|
||
|
||
|
||
def seed_task_inventory_source(
|
||
task: "ShippingTask",
|
||
*,
|
||
source_code: str = "DSV360_AWSDU",
|
||
) -> None:
|
||
"""测试辅助:为直接构造的 ShippingTask 写入稳定库存源独立字段。"""
|
||
from app.services.shipping_notice.inventory_source_rules import (
|
||
compute_routing_fingerprint,
|
||
extract_routing_context,
|
||
)
|
||
from app.services.shipping_notice.inventory_sources import (
|
||
get_inventory_source,
|
||
get_inventory_sources_config_version,
|
||
)
|
||
|
||
source = get_inventory_source(source_code)
|
||
if not source:
|
||
raise ValueError(f"unknown inventory source for tests: {source_code}")
|
||
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
|
||
|
||
context = extract_routing_context(task)
|
||
resolution = resolve_inventory_source_identity(source, context)
|
||
if not resolution.ok or not resolution.identity:
|
||
raise ValueError(
|
||
f"cannot seed stable inventory source {source_code}: {resolution.reason or 'identity_incomplete'}"
|
||
)
|
||
identity = resolution.identity
|
||
task.inventory_source_code = identity.source_code
|
||
task.inventory_connector_type = identity.connector_type
|
||
task.inventory_site_id = identity.site_id
|
||
task.inventory_warehouse_id = identity.warehouse_id
|
||
task.inventory_source_status = "resolved"
|
||
task.inventory_source_method = "rule_exact"
|
||
task.inventory_source_config_version = get_inventory_sources_config_version()
|
||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||
|
||
|
||
def seed_rpa_inventory_trigger(
|
||
task: "ShippingTask",
|
||
*,
|
||
run_no: str = "RUN-TEST-001",
|
||
trigger_path: str | None = None,
|
||
) -> None:
|
||
"""测试辅助:写入 inventory_rpa_triggered 事件,供单任务回调 run_no 校验。"""
|
||
from app import db
|
||
from app.services.shipping_notice.tool_common import log_task_event
|
||
|
||
if task.id is None:
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
trigger = trigger_path or f"inventory_export_batch_{run_no}.json"
|
||
log_task_event(
|
||
task,
|
||
"inventory_rpa_triggered",
|
||
{"trigger": trigger, "run_no": run_no, "attempt": 1, "manual_retry_round": False},
|
||
)
|
||
|
||
|
||
def inventory_xlsx_with_warehouse(
|
||
warehouse_id: str,
|
||
*,
|
||
sku: str = "A001",
|
||
qty: int = 1,
|
||
) -> "BytesIO":
|
||
"""生成带 Warehouse ID 列的库存 Excel,供身份校验测试使用。"""
|
||
from io import BytesIO
|
||
|
||
from openpyxl import Workbook
|
||
|
||
buf = BytesIO()
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.append(["Warehouse ID", "SKU", "Qty"])
|
||
ws.append([warehouse_id, sku, qty])
|
||
wb.save(buf)
|
||
wb.close()
|
||
buf.seek(0)
|
||
return buf
|
||
|
||
|
||
def inventory_csv_with_warehouse(
|
||
warehouse_id: str,
|
||
*,
|
||
sku: str = "A001",
|
||
qty: int = 1,
|
||
delimiter: str = ",",
|
||
) -> "BytesIO":
|
||
"""生成带 Warehouse ID 列的库存 CSV,供身份校验测试使用。"""
|
||
from io import BytesIO
|
||
|
||
buf = BytesIO()
|
||
content = f"Warehouse ID{delimiter}SKU{delimiter}Qty\n{warehouse_id}{delimiter}{sku}{delimiter}{qty}\n"
|
||
buf.write(content.encode("utf-8"))
|
||
buf.seek(0)
|
||
return buf
|
||
|
||
|
||
def batch_rpa_item_identity(task: "ShippingTask") -> dict[str, str]:
|
||
"""构造 batch 成功回调 item 须携带的 Worker 身份字段。"""
|
||
return {
|
||
"source_code": str(task.inventory_source_code or ""),
|
||
"site_id": str(task.inventory_site_id or ""),
|
||
"warehouse_id": str(task.inventory_warehouse_id or ""),
|
||
}
|
||
|
||
|
||
def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
|
||
"""构造定时 batch 成功回调 item 的四字段身份(与 YAML 配置一致)。"""
|
||
from app.services.shipping_notice.inventory_sources import get_inventory_source
|
||
|
||
source = get_inventory_source(source_code)
|
||
if not source:
|
||
raise ValueError(f"unknown inventory source for tests: {source_code}")
|
||
item = {
|
||
"source_code": source_code,
|
||
"site_id": str(source.get("site_id") or ""),
|
||
"warehouse_id": str(source.get("warehouse_id") or ""),
|
||
}
|
||
item.update(overrides)
|
||
return item
|
||
|
||
|
||
def rpa_callback_payload(
|
||
task: "ShippingTask",
|
||
file_path: str | Path,
|
||
*,
|
||
run_no: str = "RUN-TEST-001",
|
||
status: str = "success",
|
||
) -> dict:
|
||
"""构造通过单任务 RPA 回调身份/run_no 校验的最小 payload。"""
|
||
return {
|
||
"task_id": task.task_no,
|
||
"status": status,
|
||
"file_path": str(file_path),
|
||
"run_no": run_no,
|
||
"source_code": task.inventory_source_code,
|
||
"site_id": task.inventory_site_id,
|
||
"warehouse_id": task.inventory_warehouse_id,
|
||
}
|
||
|
||
|
||
def pytest_configure(config):
|
||
config.addinivalue_line(
|
||
"markers",
|
||
"auto_rpa: 发货通知测试启用 auto_progress + RPA 自动链",
|
||
)
|
||
config.addinivalue_line(
|
||
"markers",
|
||
"inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
|
||
)
|
||
|
||
|
||
@pytest.fixture
|
||
def app():
|
||
from app import create_app, db
|
||
|
||
app = create_app('testing')
|
||
with app.app_context():
|
||
db.create_all()
|
||
yield app
|
||
db.session.remove()
|
||
db.drop_all()
|
||
|
||
|
||
@pytest.fixture
|
||
def client(app):
|
||
return app.test_client()
|
||
|
||
|
||
@pytest.fixture
|
||
def admin_headers():
|
||
return {
|
||
'X-Username': 'admin',
|
||
'X-Role': 'admin',
|
||
'Content-Type': 'application/json'
|
||
}
|
||
|
||
|
||
@pytest.fixture
|
||
def user_headers():
|
||
return {
|
||
'X-Username': 'user',
|
||
'X-Role': 'user',
|
||
'Content-Type': 'application/json'
|
||
}
|