426 lines
17 KiB
Python
426 lines
17 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["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
|
||
app.config["SHIPPING_NOTICE_RPA_SHARED_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_source_repository import (
|
||
get_database_inventory_source,
|
||
inventory_sources_runtime_version,
|
||
)
|
||
|
||
source = get_database_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_warehouse_id = identity.warehouse_id
|
||
task.inventory_source_status = "resolved"
|
||
task.inventory_source_method = "rule_exact"
|
||
task.inventory_source_config_version = inventory_sources_runtime_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",
|
||
reservation_id: str = "R-1",
|
||
qty: int = 1,
|
||
) -> "BytesIO":
|
||
"""生成符合发布解析方案的库存 Excel,供身份、结构和库存解析测试使用。"""
|
||
from io import BytesIO
|
||
|
||
from openpyxl import Workbook
|
||
|
||
buf = BytesIO()
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.append(["Warehouse ID", "SKU", "Reservation ID", "Qty"])
|
||
ws.append([warehouse_id, sku, reservation_id, 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 须携带的 Source/Warehouse 身份字段。"""
|
||
return {
|
||
"source_code": str(task.inventory_source_code or ""),
|
||
"warehouse_id": str(task.inventory_warehouse_id or ""),
|
||
}
|
||
|
||
|
||
def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
|
||
"""构造定时 batch 成功回调 item 的 Source/Warehouse 身份(与数据库配置一致)。"""
|
||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||
|
||
source = get_database_inventory_source(source_code)
|
||
if not source:
|
||
raise ValueError(f"unknown inventory source for tests: {source_code}")
|
||
item = {
|
||
"source_code": source_code,
|
||
"warehouse_id": str(source.get("fixed_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,
|
||
"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()
|
||
_seed_test_inventory_configuration()
|
||
yield app
|
||
db.session.remove()
|
||
db.drop_all()
|
||
|
||
|
||
def _seed_test_inventory_configuration() -> None:
|
||
"""为发货测试创建数据库库存源与发布路由规则,测试运行期不读取 YAML。"""
|
||
from app import db
|
||
from app.models import (
|
||
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryRoutingRule,
|
||
ShippingInventoryRoutingRuleCondition, ShippingInventorySource, ShippingRpaProfile,
|
||
)
|
||
from app.services.shipping_notice.inventory_structure_fingerprint import (
|
||
FINGERPRINT_VERSION,
|
||
compatibility_fingerprint,
|
||
exact_fingerprint,
|
||
structure_definition,
|
||
)
|
||
|
||
# 各测试显式创建所需用户字段;生产目录本身保持零预置。
|
||
if not ShippingInventoryField.query.filter_by(field_code='part_number').first():
|
||
db.session.add_all([
|
||
ShippingInventoryField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10),
|
||
ShippingInventoryField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20),
|
||
ShippingInventoryField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30),
|
||
ShippingInventoryField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40),
|
||
ShippingInventoryField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100),
|
||
ShippingInventoryField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110),
|
||
ShippingInventoryField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120),
|
||
ShippingInventoryField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130),
|
||
ShippingInventoryField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140),
|
||
])
|
||
|
||
db.session.flush()
|
||
inventory_fields = {
|
||
item.field_code: item
|
||
for item in ShippingInventoryField.query.filter(
|
||
ShippingInventoryField.field_code.in_([
|
||
'part_number', 'reservation_id', 'available_qty', 'warehouse_id',
|
||
])
|
||
).all()
|
||
}
|
||
field_mapping = {
|
||
str(inventory_fields['part_number'].id): 'SKU',
|
||
str(inventory_fields['reservation_id'].id): 'Reservation ID',
|
||
str(inventory_fields['available_qty'].id): 'Qty',
|
||
str(inventory_fields['warehouse_id'].id): 'Warehouse ID',
|
||
}
|
||
# 测试专用稳定字段 ID 避免全局创建订单模板,后者会破坏订单模板初始化专项测试。
|
||
match_keys = [
|
||
{
|
||
'order_field_id': 'test-order-part-number',
|
||
'inventory_field_id': str(inventory_fields['part_number'].id),
|
||
},
|
||
{
|
||
'order_field_id': 'test-order-reservation-id',
|
||
'inventory_field_id': str(inventory_fields['reservation_id'].id),
|
||
},
|
||
]
|
||
definition = {
|
||
'sheet_name': 'Sheet',
|
||
'header_row_index': 1,
|
||
'field_mapping': field_mapping,
|
||
'match_keys': match_keys,
|
||
}
|
||
structure = structure_definition(
|
||
file_format='xlsx', sheet_name='Sheet', header_row_index=1,
|
||
headers=['Warehouse ID', 'SKU', 'Reservation ID', 'Qty'],
|
||
)
|
||
import hashlib
|
||
import json
|
||
|
||
checksum = hashlib.sha256(
|
||
json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||
).hexdigest()
|
||
parsing_profile = ShippingInventoryParsingProfile(
|
||
profile_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published',
|
||
file_format='xlsx', definition_json=definition, checksum=checksum,
|
||
structure_definition_json=structure,
|
||
exact_structure_fingerprint=exact_fingerprint(structure),
|
||
compatibility_fingerprint=compatibility_fingerprint(
|
||
definition=structure, field_mapping=field_mapping, match_keys=match_keys,
|
||
),
|
||
fingerprint_version=FINGERPRINT_VERSION,
|
||
)
|
||
excel_template = ShippingExcelTemplate(
|
||
template_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published',
|
||
storage_provider='minio', storage_bucket='test', storage_key='test/runtime/template.xlsx',
|
||
original_filename='template.xlsx',
|
||
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
|
||
)
|
||
|
||
profile = ShippingRpaProfile(
|
||
profile_code='DBS_DUB_TEST', display_name='DBS Dublin', connector_type='dbs',
|
||
login_url='https://test.invalid/dbs', login_config_json={'auth_mode': 'password'},
|
||
)
|
||
source = ShippingInventorySource(
|
||
source_code='DSV360_AWSDU', display_name='DBS Dublin AWSDU', connector_type='dbs',
|
||
rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template,
|
||
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU',
|
||
report_path_json={
|
||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
|
||
},
|
||
query_parameters_json=[
|
||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': True, 'select_all': False},
|
||
],
|
||
match_aliases_json=['AWSDU', 'DUB'],
|
||
enabled=True,
|
||
)
|
||
rule = ShippingInventoryRoutingRule(
|
||
rule_code='TEST_DUB', rule_name='Test DUB route', scope='task', priority=100,
|
||
match_mode='all', status='published', action_type='add_source_candidates',
|
||
action_payload_json={'source_codes': ['DSV360_AWSDU']}, version=1,
|
||
)
|
||
rule.conditions.append(ShippingInventoryRoutingRuleCondition(
|
||
condition_group=1, source_kind='system_fact', system_fact_key='task.destination_port', operator='equals',
|
||
expected_value_json='DUB', sequence=1,
|
||
))
|
||
db.session.add_all([profile, parsing_profile, excel_template, source, rule])
|
||
db.session.commit()
|
||
|
||
|
||
@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'
|
||
}
|