741 lines
30 KiB
Python
741 lines
30 KiB
Python
"""
|
||
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',
|
||
)
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def _capture_legacy_order_rows_for_tests(monkeypatch):
|
||
"""将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。"""
|
||
from app.models import ShippingNotice
|
||
|
||
original_init = ShippingNotice.__init__
|
||
legacy_headers = ('customer_name', 'customer_code', 'ship_to', 'po_number', 'required_date')
|
||
|
||
def _init(self, **kwargs):
|
||
rows = kwargs.pop('lines_json', None)
|
||
kwargs.pop('order_lines_migration_status', None)
|
||
header_values = {key: kwargs.pop(key) for key in legacy_headers if key in kwargs}
|
||
original_init(self, **kwargs)
|
||
if rows is not None:
|
||
self._test_order_rows = [dict(item) for item in rows if isinstance(item, dict)]
|
||
for key, value in header_values.items():
|
||
setattr(self, f'_test_{key}', value)
|
||
|
||
monkeypatch.setattr(ShippingNotice, '__init__', _init)
|
||
for key in (*legacy_headers, 'lines_json'):
|
||
storage = f'_test_{key}' if key != 'lines_json' else '_test_order_rows'
|
||
monkeypatch.setattr(
|
||
ShippingNotice,
|
||
key,
|
||
property(
|
||
lambda task, name=storage: getattr(task, name, None),
|
||
lambda task, value, name=storage: setattr(task, name, value),
|
||
),
|
||
raising=False,
|
||
)
|
||
|
||
|
||
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["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,
|
||
)
|
||
monkeypatch.setattr(
|
||
"app.services.shipping_notice.rpa_worker_heartbeat.assert_freight_upload_rpa_ready",
|
||
lambda: None,
|
||
)
|
||
return
|
||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_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["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
|
||
|
||
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:
|
||
"""测试辅助:为直接构造的 ShippingNotice 写入稳定库存源独立字段。"""
|
||
_ensure_test_task_dynamic_order(task)
|
||
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))
|
||
if getattr(task, '_test_customer_confirmed', False) and not task.order_snapshot_id:
|
||
freeze_test_task_order_snapshot(task)
|
||
|
||
|
||
def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
|
||
"""将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。"""
|
||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||
|
||
if task.order_snapshot_id:
|
||
return
|
||
rows = list(getattr(task, '_test_order_rows', []) or [])
|
||
if not rows:
|
||
lines = task.lines_json if isinstance(task.lines_json, 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)
|
||
]
|
||
task._test_order_rows = rows
|
||
_ensure_test_task_dynamic_order(task)
|
||
task.order_data_version = int(task.order_data_version or 1)
|
||
from app import db
|
||
from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction
|
||
db.session.flush()
|
||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||
customer = getattr(task, 'customer', None)
|
||
if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by(
|
||
extraction_id=extraction.id, role='bill_to',
|
||
).one_or_none() is None:
|
||
db.session.add(ShippingOrderCustomerMatch(
|
||
extraction_id=extraction.id, role='bill_to',
|
||
raw_name=customer.standard_name,
|
||
normalized_name=str(customer.standard_name or '').upper(), status='confirmed',
|
||
customer_id=customer.id,
|
||
customer_name_snapshot=customer.standard_name,
|
||
customer_short_code_snapshot=customer.short_code,
|
||
identity_fingerprint='r' * 64,
|
||
identity_rule_version='test.v1', resolution_method='manual',
|
||
confirmation_reason='测试确认', confirmed_by_id=None,
|
||
))
|
||
db.session.flush()
|
||
freeze_order_snapshot(
|
||
task,
|
||
actor_id=None,
|
||
expected_order_data_version=int(task.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 _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,
|
||
)
|
||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||
|
||
if task.current_order_extraction_id is not None:
|
||
return
|
||
rows = list(getattr(task, '_test_order_rows', []) or [])
|
||
if not rows:
|
||
return
|
||
if task.id is None:
|
||
db.session.add(task)
|
||
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=task.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)
|
||
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,
|
||
))
|
||
task.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:
|
||
"""测试辅助:写入 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 = "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 身份字段。"""
|
||
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 v2_inventory_batch_payload(payload: dict) -> dict:
|
||
"""测试构造器:补齐冻结 shipping_inventory_rpa.v2 回调 envelope。"""
|
||
body = dict(payload or {})
|
||
run_no = str(body.get('batch_run_no') or body.get('run_no') or '').strip()
|
||
body.setdefault('schema_version', 'shipping_inventory_rpa.v2')
|
||
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。"""
|
||
return {
|
||
"schema_version": "shipping_inventory_rpa.v2",
|
||
"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": task.inventory_source_code,
|
||
"warehouse_id": task.inventory_warehouse_id,
|
||
"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",
|
||
"inventory_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。"""
|
||
from app import db
|
||
from app.models import (
|
||
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, 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},
|
||
],
|
||
enabled=True,
|
||
)
|
||
db.session.add_all([profile, parsing_profile, excel_template, source])
|
||
db.session.commit()
|
||
|
||
|
||
@pytest.fixture
|
||
def client(app):
|
||
return app.test_client()
|
||
|
||
|
||
@pytest.fixture
|
||
def dbs_ready_file() -> dict:
|
||
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。"""
|
||
return {
|
||
"source_code": "DBS-AWSBI",
|
||
"business_date": "2026-08-06",
|
||
"file_purpose": "receipt",
|
||
"file_no": "REC-20260806-001",
|
||
"file_version": "v3",
|
||
"checksum": "d" * 64,
|
||
"status": "ready",
|
||
"rows": [
|
||
{"sheet": "Receipt", "row_no": 10, "invoice_no": "INV-001", "material_no": "MAT-001",
|
||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||
"receipt_date": "2026-08-05", "receipt_quantity": "500", "source_code": "DBS-AWSBI"},
|
||
{"sheet": "Receipt", "row_no": 11, "invoice_no": "INV-001", "material_no": "MAT-001",
|
||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||
"receipt_date": "2026-08-05", "receipt_quantity": "700", "source_code": "DBS-AWSBI"},
|
||
{"sheet": "Receipt", "row_no": 20, "invoice_no": "INV-002", "material_no": "MAT-002",
|
||
"material_name": "控制器组件", "specification": "标准型 / 48V",
|
||
"receipt_date": "2026-08-05", "receipt_quantity": "1200", "source_code": "DBS-AWSBI"},
|
||
],
|
||
}
|
||
|
||
|
||
@pytest.fixture
|
||
def crane_ready_file() -> dict:
|
||
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。"""
|
||
return {
|
||
"source_code": "CRANE-SZ",
|
||
"business_date": "2026-08-06",
|
||
"file_purpose": "receipt",
|
||
"file_no": "REC-20260806-002",
|
||
"file_version": "v4",
|
||
"checksum": "c" * 64,
|
||
"status": "ready",
|
||
"rows": [
|
||
{"sheet": "Inbound", "row_no": 5, "invoice_no": "INV-008", "material_no": "MAT-200",
|
||
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
|
||
"receipt_date": "2026-08-05", "receipt_quantity": "600", "source_code": "CRANE-SZ"},
|
||
],
|
||
}
|
||
|
||
|
||
@pytest.fixture
|
||
def same_day_receipt_file() -> dict:
|
||
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。"""
|
||
return {
|
||
"source_code": "DBS-AWSSG",
|
||
"business_date": "2026-08-06",
|
||
"file_purpose": "receipt",
|
||
"file_no": "REC-20260806-003",
|
||
"file_version": "v2",
|
||
"checksum": "s" * 64,
|
||
"status": "ready",
|
||
"rows": [
|
||
{"sheet": "Receipt", "row_no": 3, "invoice_no": "INV-041", "material_no": "MAT-041",
|
||
"material_name": "连接器组件", "specification": "C 型",
|
||
"receipt_date": "2026-08-06", "receipt_quantity": "400", "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'
|
||
}
|