Files
hugoandCursor 4c2a7e2a23 feat(in-transit-transfer): 落地证据流重解析并纳入货代与排程配套改动
外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 00:48:37 +08:00

797 lines
34 KiB
Python
Raw Permalink 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.
"""
tests/conftest.py
用途:Flask testing app、库存配置种子与测试隔离夹具。
依赖:pytest、app.create_app、shipping inventory 模型。
逻辑:各测试用例共享;Windows 下将 basetemp 固定到 backend/.pytest_tmp,
配合 pytest.ini 的 retention=0,避免 %TEMP%/pytest-current 清理 PermissionError;
pure_unit 标记跳过 Flask/DB 创建,供契约类纯单测加速。
"""
import shutil
from pathlib import Path
import pytest
def pytest_configure(config):
"""
注册自定义标记,避免 PytestUnknownMarkWarning。
pure_unit:契约类纯单测,跳过 Flask/DB 创建(见 _shipping_notice_stable_auto_config)。
"""
config.addinivalue_line(
'markers',
'pure_unit: skip Flask app/DB creation unless the test requests the app fixture',
)
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(request, monkeypatch):
"""
发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。
标记 pure_unit 且未显式请求 app 的用例跳过 Flask/DB 创建,显著降低契约类单测耗时。
"""
if request.node.get_closest_marker("pure_unit") and "app" not in request.fixturenames:
return
app = request.getfixturevalue("app")
tmp_path = request.getfixturevalue("tmp_path")
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["FREIGHT_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_ONHAND_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
monkeypatch.setattr(
"app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,
)
monkeypatch.setattr(
"app.services.freight_rpa.common.worker_heartbeat.assert_freight_upload_rpa_ready",
lambda: None,
)
return
app.config["SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
# 货代自动上传默认 fail-closed;单测与产品默认一致关闭。
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
app.config["ENV_NAME"] = "dev"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
from app.services.freight_rpa.common.worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
reset_rpa_worker_heartbeat_state_for_tests()
from app.services.freight_rpa.common.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。
标记 onhand_source_gate 的用例跳过,避免干扰库存源门禁专项测试。
"""
if request.node.get_closest_marker("onhand_source_gate"):
return
from app.services.shipping_notice import extract as extract_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)
def seed_task_inventory_source(
task: "ShippingNotice",
*,
source_code: str = "DSV360_AWSDU",
) -> None:
"""测试辅助:冻结库存候选集,供库存门禁从正式事实源读取。"""
_ensure_test_task_dynamic_order(task)
from app import db
from app.models import ShippingOrderTask
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
_ensure_test_task_dynamic_order(task)
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
if owner is None:
raise ValueError('test task must be linked to ShippingOrderTask')
from app.services.shipping_notice.onhand_candidate_freeze_service import freeze_candidates_for_task
from app.services.shipping_notice.onhand_source_rules import InventorySourceAdjudication
from app.services.shipping_notice.onhand_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}")
if getattr(task, '_test_customer_confirmed', False) and not owner.order_snapshot_id:
freeze_test_task_order_snapshot(task)
if not owner.order_snapshot_id:
raise ValueError('test task must have a frozen order snapshot before inventory source selection')
freeze_candidates_for_task(
owner,
adjudication=InventorySourceAdjudication(
status='resolved',
method='test_fixture',
source_code=str(source.get('source_code') or source_code).strip().upper(),
candidates=[source],
config_version=inventory_sources_runtime_version(),
),
)
def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
"""将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。"""
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
from app import db
from app.models import ShippingOrderTask
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
_ensure_test_task_dynamic_order(task)
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
if owner is None:
raise ValueError('test task must be linked to ShippingOrderTask')
if owner.order_snapshot_id:
return
rows = list(getattr(task, '_test_order_rows', []) or [])
if not rows:
lines = getattr(task, 'lines_json', None)
lines = lines if isinstance(lines, list) else []
rows = [
{
'part_number': row.get('part_number'),
'reservation_id': row.get('reservation_id'),
'qty': row.get('qty'),
}
for row in lines if isinstance(row, dict)
]
owner._test_order_rows = rows
_ensure_test_task_dynamic_order(owner)
owner.order_data_version = int(owner.order_data_version or 1)
from app.models import ShippingOrderExtraction
db.session.flush()
extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id)
customer = getattr(owner, 'customer', None)
if extraction is not None and customer is not None:
confirm_test_customer_resolution(owner, customer=customer, extraction=extraction)
freeze_order_snapshot(
owner,
actor_id=None,
expected_order_data_version=int(owner.order_data_version),
freeze_mode='auto',
auto_freeze_policy={
'test_fixture': True,
'enabled': True,
'mode': 'qualified',
'qualification_status': 'qualified',
'customer_scope_status': 'allowed',
'blocking_reason_codes': [],
},
)
db.session.flush()
def confirm_test_customer_resolution(task: "ShippingOrderTask", *, customer, extraction=None) -> None:
"""为测试 OT 写入唯一客户真相源,不构造已退役的角色匹配记录。"""
from app import db
from app.models import ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderIntake
candidate = db.session.get(ShippingOrderCandidate, task.candidate_id) if task.candidate_id else None
if candidate is None:
intake = ShippingOrderIntake(
intake_no=f'INT-TEST-RESOLUTION-{task.id}', asset_id=int(task.id),
user_id=int(task.user_id), parser_version='test',
)
db.session.add(intake)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no=f'CAND-TEST-RESOLUTION-{task.id}', intake_id=intake.id,
primary_document_id=1, candidate_key=f'test-resolution-{task.id}',
candidate_status='accepted',
)
db.session.add(candidate)
db.session.flush()
task.candidate_id = candidate.id
if extraction is not None:
candidate.order_extraction_id = int(extraction.id)
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=candidate.id).one_or_none()
if resolution is None:
resolution = ShippingCustomerShadowResolution(
candidate_id=candidate.id,
intake_id=candidate.intake_id,
resolution_version='test.v1', status='confirmed',
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}],
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
identity_rule_set_checksum='t' * 64,
)
db.session.add(resolution)
resolution.status = 'confirmed'
resolution.confirmed_customer_id = customer.id
resolution.confirmation_method = 'test_fixture'
db.session.flush()
def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
"""将 RPA 测试显式构造的旧行样例转换为当前测试所需的动态 FieldValue。"""
from decimal import Decimal
from app import db
from app.models import (
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchemaVersion,
ShippingOrderTask, User,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
if task.id is None:
db.session.add(task)
db.session.flush()
user_id = getattr(task, 'user_id', None) or db.session.query(User.id).order_by(User.id).first()
user_id = user_id[0] if isinstance(user_id, tuple) else user_id
owner = ShippingOrderTask(
task_no=f'OT-TEST-{task.task_no}',
user_id=int(user_id or 1),
status='ready',
current_step='customer_review',
)
db.session.add(owner)
db.session.flush()
task.order_task_id = owner.id
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id)
if owner is None:
raise ValueError('test task must be linked to ShippingOrderTask')
if owner.current_order_extraction_id is not None:
return
rows = list(getattr(task, '_test_order_rows', []) or [])
if not rows:
return
if owner.id is None:
db.session.add(owner)
db.session.flush()
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
if version is None:
order_schema_service.initialize_schema({'display_name': 'RPA 测试动态订单'}, actor_id=None)
existing_fields = {
item['field_code']: item
for item in order_schema_service.get_state()['fields']
}
fields = {
code: order_schema_service.save_field(
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
field_id=existing_fields.get(code, {}).get('id'),
)
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
}
draft = order_schema_service.create_draft({}, actor_id=None)
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
saved = order_schema_service.save_draft(draft['id'], {
'fields': [{
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
} for code, field in fields.items()],
'expected_lock_version': draft['lock_version'],
}, actor_id=None)
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
field_ids = {str(item['field_code']): str(item['field_id']) for item in (version.definition_json or {}).get('fields') or []}
required = {'part_number', 'reservation_id', 'qty'}
if not required.issubset(field_ids):
raise ValueError('RPA test schema lacks required order business purposes')
extraction = ShippingOrderExtraction(task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted')
db.session.add(extraction)
db.session.flush()
for position, row in enumerate(rows):
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
db.session.add(line)
db.session.flush()
for code in required:
value = row.get(code)
if code == 'qty' and value not in (None, ''):
value = Decimal(str(value))
json_value = str(value) if code == 'qty' and value is not None else value
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
supporting_observation_ids_json=[], resolved_value_json=json_value,
)
db.session.add(decision)
db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
value_json=json_value,
))
owner.current_order_extraction_id = extraction.id
db.session.flush()
def seed_rpa_inventory_trigger(
task: "ShippingNotice",
*,
run_no: str = "RUN-TEST-001",
trigger_path: str | None = None,
) -> None:
"""测试辅助:写入 onhand_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,
"onhand_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 = "00001",
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: "ShippingNotice") -> dict[str, str]:
"""构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。"""
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
source_code = next(iter(task_frozen_onhand_source_codes(task)), '')
source = get_database_inventory_source(source_code) or {}
return {
"source_code": str(source_code or ""),
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
}
def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
"""构造定时 batch 成功回调 item 的 Source/Warehouse 身份(与数据库配置一致)。"""
from app.services.shipping_notice.onhand_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 v2_inventory_batch_payload(payload: dict) -> dict:
"""测试构造器:补齐冻结 freight_rpa.onhand.v1 回调 envelope。"""
body = dict(payload or {})
run_no = str(body.get('batch_run_no') or body.get('run_no') or '').strip()
body.setdefault('schema_version', 'freight_rpa.onhand.v1')
body.setdefault('callback_id', f'test-callback:{run_no or "unknown"}')
body.setdefault('batch_run_no', run_no)
return body
def rpa_callback_payload(
task: "ShippingNotice",
file_path: str | Path,
*,
run_no: str = "RUN-TEST-001",
status: str = "success",
) -> dict:
"""构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。"""
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
source_code = next(iter(task_frozen_onhand_source_codes(task)), '')
source = get_database_inventory_source(source_code) or {}
return {
"schema_version": "freight_rpa.onhand.v1",
"callback_id": f"test-callback:{run_no}",
"task_id": task.task_no,
"status": status,
"file_path": str(file_path),
"run_no": run_no,
"source_run_no": run_no,
"source_code": source_code,
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
"attempt_no": 1,
"lease_token": "test-lease-token",
"candidate_set_id": 1,
"execution_id": 1,
"gate_id": 1,
}
def pytest_configure(config):
"""
注册自定义 markers,并把临时目录固定到仓库内可写路径。
核心逻辑:未显式传 --basetemp 时使用 backend/.pytest_tmp/run,避免系统 TEMP
中 pytest-current 符号链接在 atexit 清理时触发 WinError 5,导致 exit code≠0。
"""
config.addinivalue_line(
"markers",
"auto_rpa: 发货通知测试启用 auto_progress + RPA 自动链",
)
config.addinivalue_line(
"markers",
"onhand_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
)
config.addinivalue_line(
"markers",
"postgres: requires PostgreSQL dialect (skip on SQLite/memory fixtures)",
)
# [STEP] Windows 质量门禁:basetemp 落仓内 + retention=0(见 pytest.ini)。
if not getattr(config.option, 'basetemp', None):
basetemp = Path(__file__).resolve().parents[1] / '.pytest_tmp' / 'run'
basetemp.mkdir(parents=True, exist_ok=True)
config.option.basetemp = str(basetemp)
def pytest_unconfigure(config):
"""
测试结束后删除仓库内显式指定的旧式 pytest 临时目录。
核心逻辑:仅清理 backend 直属且名称以 .pytest- 开头的 basetemp;默认
backend/.pytest_tmp/run 保留复用,仓库外路径与其他目录不处理。
"""
basetemp_value = getattr(config.option, 'basetemp', None)
if not basetemp_value:
return
backend_dir = Path(__file__).resolve().parents[1]
basetemp = Path(basetemp_value).resolve()
if basetemp.parent == backend_dir and basetemp.name.startswith('.pytest-'):
shutil.rmtree(basetemp, ignore_errors=True)
@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。
s18 起:报表路径/查询条件/解析方案挂在 FreightRpaOnhandReportConfig 上,
站点行只剩连接、模板绑定与启停。
"""
from app import db
from app.models import (
ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaOnhandReportConfig,
FreightRpaParsingProfile, FreightRpaSource, FreightRpaProfile,
)
from app.services.shipping_notice.onhand_structure_fingerprint import (
FINGERPRINT_VERSION,
compatibility_fingerprint,
exact_fingerprint,
structure_definition,
)
# 各测试显式创建所需用户字段;生产目录本身保持零预置。
if not FreightRpaOnhandField.query.filter_by(field_code='part_number').first():
db.session.add_all([
FreightRpaOnhandField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10),
FreightRpaOnhandField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20),
FreightRpaOnhandField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30),
FreightRpaOnhandField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40),
FreightRpaOnhandField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100),
FreightRpaOnhandField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110),
FreightRpaOnhandField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120),
FreightRpaOnhandField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130),
FreightRpaOnhandField(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 FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.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 = FreightRpaParsingProfile(
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 = FreightRpaProfile(
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 = FreightRpaSource(
source_code='DSV360_AWSDU', display_name='DBS Dublin AWSDU', connector_type='dbs',
rpa_profile=profile, excel_template=excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU',
enabled=True,
)
# s18 起报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig,站点行不再承载。
report_config = FreightRpaOnhandReportConfig(
source=source,
parsing_profile=parsing_profile,
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},
],
)
db.session.add_all([profile, parsing_profile, excel_template, source, report_config])
db.session.commit()
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def dbs_ready_file() -> dict:
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。
rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date),
与真实仓库 movement_file_repository 产出一致(B5 接线后 run_matching 按
parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。
【T−2 成熟封顶 2026-10-21】rows 异动日期取 2026-08-04(= 业务日 08-06 的
T−2 恰好成熟边界);更晚日期(T−1/当天)已被圈档封顶排除,不得再作夹具日期。
"""
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "inbound",
"file_no": "REC-20260806-001",
"file_version": "v3",
"checksum": "d" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 10, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-04", "quantity": "500", "unit": "个", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 11, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-04", "quantity": "700", "unit": "个", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 20, "doc_no": "HOX-002", "lot_no": "LOT-20", "material_code": "MAT-002",
"material_name": "控制器组件", "specification": "标准型 / 48V",
"movement_date": "2026-08-04", "quantity": "1200", "unit": "PCS", "source_code": "DBS-AWSBI"},
],
}
@pytest.fixture
def crane_ready_file() -> dict:
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
异动日期=T−2 成熟边界(见 dbs_ready_file 注释)。
"""
return {
"source_code": "CRANE-SZ",
"business_date": "2026-08-06",
"file_purpose": "inbound",
"file_no": "REC-20260806-002",
"file_version": "v4",
"checksum": "c" * 64,
"status": "ready",
"rows": [
{"sheet": "Inbound", "row_no": 5, "doc_no": "WTP-008", "lot_no": "LOT-8", "material_code": "MAT-200",
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
"movement_date": "2026-08-04", "quantity": "600", "unit": "PCS", "source_code": "CRANE-SZ"},
],
}
@pytest.fixture
def same_day_inbound_file() -> dict:
"""含业务日期当天异动数据的文件(T−2 成熟封顶 2026-10-21:当天未成熟不匹配)。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
"""
return {
"source_code": "DBS-AWSSG",
"business_date": "2026-08-06",
"file_purpose": "inbound",
"file_no": "REC-20260806-003",
"file_version": "v2",
"checksum": "s" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 3, "doc_no": "HOM-3", "lot_no": "INV-041", "material_code": "MAT-041",
"material_name": "连接器组件", "specification": "C 型",
"movement_date": "2026-08-06", "quantity": "400", "unit": "个", "source_code": "DBS-AWSSG"},
],
}
@pytest.fixture
def transfer_db(app):
"""请求 app 后返回 db 实例;表由 create_all/drop_all 随 app 生命周期隔离。"""
from app import db
return db
@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'
}