- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。 - 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。 - 更新 ORM 模型,增加出站报表相关的持久化模型。 - 统一命名规范,确保在手、入站与出站的概念一致性。
341 lines
16 KiB
Python
341 lines
16 KiB
Python
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验 + 迁移往返)。
|
||
|
||
用途:验证 onhand_parsing_profile._validate_definition(purpose=...) 分支——
|
||
inbound/outbound 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
|
||
不查库存字段目录、无 match_keys);onhand 维持库存字段目录 + match_keys 校验。
|
||
并用 app fixture 校验模型
|
||
purpose 列默认 'onhand'、CHECK 约束三元枚举,以及 tt15 迁移 SQLite 真实往返。
|
||
依赖:onhand_parsing_profile._validate_definition / save_draft(纯 + app SQLite)、
|
||
migrations/versions/tt15(batch_alter_table 改枚举)、app_ctx(根 conftest app
|
||
fixture 上下文别名)。
|
||
逻辑:_required_movement_field_ids 纯函数校验;模型列默认值/约束经 app fixture 校验;
|
||
迁移往返按 tt13/tt14 同款模式(手工复刻前置表结构 + upgrade→downgrade→upgrade)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import importlib.util
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
import sqlalchemy as sa
|
||
from alembic.migration import MigrationContext
|
||
from alembic.operations import Operations
|
||
|
||
from app.core.errors import ValidationError
|
||
from app.services.freight_rpa.parsing_profile import _validate_definition, save_draft
|
||
|
||
pytestmark = pytest.mark.pure_unit
|
||
|
||
REVISION = "tt15b6a7b8c9d0"
|
||
DOWN_REVISION = "tt14a5f6a7b8c9"
|
||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" / "versions"
|
||
|
||
|
||
@pytest.fixture
|
||
def app_ctx(app):
|
||
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
|
||
return app
|
||
|
||
|
||
def _inbound_definition() -> dict:
|
||
return {
|
||
'sheet_name': 'Inbound',
|
||
'header_row_index': 1,
|
||
'field_mapping': {
|
||
'doc_no': '单据编号',
|
||
'line_no': '项次',
|
||
'in_out_flag': '进出库别',
|
||
'material_code': '料号',
|
||
'material_name': '品名',
|
||
'warehouse_code': '仓库',
|
||
'storage_code': '储位',
|
||
'lot_no': '批号',
|
||
'quantity': '数量',
|
||
'movement_date': '异动日期',
|
||
},
|
||
}
|
||
|
||
|
||
def test_inbound_definition_validates_fixed_fields():
|
||
"""inbound 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。"""
|
||
definition = _validate_definition(_inbound_definition(), purpose='inbound')
|
||
assert definition['field_mapping']['doc_no'] == '单据编号'
|
||
assert definition['field_mapping']['quantity'] == '数量'
|
||
assert definition['match_keys'] == []
|
||
|
||
|
||
def test_inbound_definition_missing_fixed_field_rejected():
|
||
"""inbound 缺 movement_date → 阻断。"""
|
||
raw = dict(_inbound_definition())
|
||
raw['field_mapping'] = {k: v for k, v in raw['field_mapping'].items() if k != 'movement_date'}
|
||
with pytest.raises(ValidationError):
|
||
_validate_definition(raw, purpose='inbound')
|
||
|
||
|
||
def test_inbound_definition_rejects_unknown_field():
|
||
"""inbound 引用非定死领域字段 → 阻断。"""
|
||
raw = dict(_inbound_definition())
|
||
raw['field_mapping'] = {**raw['field_mapping'], 'free_text': '随意列'}
|
||
with pytest.raises(ValidationError):
|
||
_validate_definition(raw, purpose='inbound')
|
||
|
||
|
||
def test_outbound_definition_uses_movement_fields():
|
||
"""outbound 定义完整 → 走异动字段路径,match_keys 空。"""
|
||
definition = _validate_definition(_inbound_definition(), purpose='outbound')
|
||
assert definition['match_keys'] == []
|
||
assert definition['field_mapping']['doc_no'] == '单据编号'
|
||
|
||
|
||
def test_outbound_onhand_shaped_definition_rejected(app_ctx):
|
||
"""库存目录形态(含 match_keys)在 outbound 下应失败。"""
|
||
from app.models import FreightRpaOnhandField, ShippingOrderField
|
||
from app import db
|
||
|
||
rows = {item.field_code: item for item in FreightRpaOnhandField.query.filter_by(status='active').all()}
|
||
field_mapping = {
|
||
str(rows['part_number'].id): 'Supplier Sku',
|
||
str(rows['reservation_id'].id): 'Reservation ID',
|
||
str(rows['available_qty'].id): 'Qty Available',
|
||
}
|
||
order_field = ShippingOrderField(field_code='part_number', scope='line', value_type='string')
|
||
db.session.add(order_field)
|
||
db.session.flush()
|
||
raw = {
|
||
'header_row_index': 1,
|
||
'field_mapping': field_mapping,
|
||
'match_keys': [{'order_field_id': order_field.id, 'inventory_field_id': next(iter(field_mapping))}],
|
||
}
|
||
with pytest.raises(ValidationError):
|
||
_validate_definition(raw, purpose='outbound')
|
||
|
||
|
||
def test_purpose_enum_values():
|
||
"""模型 purpose 列:default/server_default 均为 'onhand',CHECK 名为批次 S 新约束,枚举恰为三元。"""
|
||
from app.models.freight_rpa_config import FreightRpaParsingProfile
|
||
col = FreightRpaParsingProfile.__table__.columns["purpose"]
|
||
assert col.default.arg == "onhand" and col.server_default.arg == "onhand"
|
||
check = next(c for c in FreightRpaParsingProfile.__table__.constraints
|
||
if getattr(c, "name", "") == "ck_freight_rpa_parsing_profiles_purpose")
|
||
sql = str(getattr(check, "sqltext", check))
|
||
for value in ("onhand", "inbound", "outbound"):
|
||
assert value in sql
|
||
for legacy in ("'inventory'", "'movement'"):
|
||
assert legacy not in sql
|
||
|
||
|
||
def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_format: str = 'xlsx') -> int:
|
||
"""构造最小化样本结构证据,使 save_draft 遵循生产环境的表头绑定门禁。"""
|
||
from app import db
|
||
from app.models import FreightRpaOnhandStructureAnalysis
|
||
|
||
item = FreightRpaOnhandStructureAnalysis(
|
||
source_kind='sample_upload', source_file_name='sample.xlsx', storage_path=None,
|
||
file_checksum='c' * 64, file_format=file_format, analysis_status='ready',
|
||
structure_json={'candidates': [{
|
||
'sheet_name': sheet_name, 'header_row_index': 1, 'headers': headers,
|
||
'columns': [{'header': header, 'duplicate': False} for header in headers],
|
||
}]},
|
||
suggested_mapping_json={}, validation_summary_json={}, sample_rows_json=[], warning_json=[],
|
||
)
|
||
db.session.add(item)
|
||
db.session.flush()
|
||
return item.id
|
||
|
||
|
||
def _catalog_mapping() -> dict[str, str]:
|
||
"""以库存字段目录 ID 构造 onhand/outbound 用解析映射(目录分支端点)。"""
|
||
from app.models import FreightRpaOnhandField
|
||
|
||
rows = {item.field_code: item for item in FreightRpaOnhandField.query.filter_by(status='active').all()}
|
||
return {
|
||
str(rows['part_number'].id): 'Supplier Sku',
|
||
str(rows['reservation_id'].id): 'Reservation ID',
|
||
str(rows['available_qty'].id): 'Qty Available',
|
||
}
|
||
|
||
|
||
def test_draft_accepts_outbound_and_rejects_legacy(app_ctx):
|
||
"""save_draft purpose='outbound' 通过校验;purpose='movement' 报 SHIPPING.ONHAND_PARSING_PROFILE_INVALID。"""
|
||
headers = [value for value in _inbound_definition()['field_mapping'].values()]
|
||
|
||
outbound = save_draft({
|
||
'profile_code': 'OUT_STD', 'display_name': '出站异动解析', 'purpose': 'outbound',
|
||
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers, sheet_name='Inbound'),
|
||
'definition': _inbound_definition(),
|
||
}, actor_id=None)
|
||
assert outbound['purpose'] == 'outbound'
|
||
assert outbound['definition']['match_keys'] == []
|
||
|
||
with pytest.raises(ValidationError) as exc_info:
|
||
save_draft({
|
||
'profile_code': 'LEGACY_MOVE', 'display_name': '旧异动用途', 'purpose': 'movement',
|
||
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers),
|
||
'definition': {'header_row_index': 1, 'field_mapping': _catalog_mapping(), 'match_keys': []},
|
||
}, actor_id=None)
|
||
# 关键断言:旧枚举 movement 已从白名单移除,fail-closed 报统一错误码。
|
||
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_INVALID'
|
||
|
||
|
||
def test_model_purpose_column_defaults_to_onhand(app):
|
||
"""模型 purpose 列默认 'onhand'(存量 inventory 行由 tt15 数据迁移回填)。"""
|
||
from app.models import FreightRpaParsingProfile
|
||
|
||
existing = FreightRpaParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first()
|
||
assert existing is not None and existing.purpose == 'onhand'
|
||
|
||
|
||
def _load_migration(revision: str):
|
||
"""按 revision 加载迁移模块(test_migration_widen_transfer_run_type 同款,不加载 Flask 应用)。"""
|
||
for path in MIGRATIONS_DIR.glob("*.py"):
|
||
if path.name.startswith(f"{revision}_"):
|
||
spec = importlib.util.spec_from_file_location(f"migration_{revision}", path)
|
||
assert spec is not None and spec.loader is not None
|
||
module = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(module)
|
||
return module
|
||
raise AssertionError(f"migration file for revision {revision} not found")
|
||
|
||
|
||
def test_tt15_revision_chains_from_tt14_head():
|
||
"""tt15 必须存在且挂在 tt14a5f6a7b8c9(实施时实际单 head)之后,且用 batch 模式保 SQLite 往返。"""
|
||
for path in MIGRATIONS_DIR.glob("*.py"):
|
||
if path.name.startswith(f"{REVISION}_"):
|
||
text = path.read_text(encoding="utf-8")
|
||
assert f"revision = '{REVISION}'" in text or f'revision = "{REVISION}"' in text
|
||
assert f"down_revision = '{DOWN_REVISION}'" in text or f'down_revision = "{DOWN_REVISION}"' in text
|
||
# SQLite 不支持裸 DROP CONSTRAINT / ALTER COLUMN SET DEFAULT:必须走 batch_alter_table。
|
||
assert "batch_alter_table" in text
|
||
return
|
||
raise AssertionError(f"migration file for revision {REVISION} not found")
|
||
|
||
|
||
def _prestate_metadata() -> sa.MetaData:
|
||
"""复刻 tt15 前置(tt14 末态)的 shipping_inventory_parsing_profiles 表结构。
|
||
|
||
按建表迁移 b17e3d4c5a60 与后续加列迁移(fc1d2e3f4a5b/f83d9e0f1a2b/a4c7e9f1b2d3/
|
||
if1b2c3d4e5g)汇总列集,purpose 保持旧枚举(default 'inventory' + 旧 CHECK),
|
||
作为 tt15 往返的真实前置。历史链祖先众多(a0b1c2d3e4f6…),整链重放不成比例,
|
||
手工复刻与 tt13 前置基线做法一致。
|
||
"""
|
||
md = sa.MetaData()
|
||
sa.Table("users", md, sa.Column("id", sa.Integer(), primary_key=True))
|
||
sa.Table(
|
||
"shipping_inventory_structure_analyses", md,
|
||
sa.Column("id", sa.Integer(), primary_key=True),
|
||
)
|
||
sa.Table(
|
||
"shipping_inventory_parsing_profiles", md,
|
||
sa.Column("id", sa.Integer(), primary_key=True),
|
||
sa.Column("purpose", sa.String(length=16), nullable=False, server_default="inventory"),
|
||
sa.Column("profile_code", sa.String(length=64), nullable=False),
|
||
sa.Column("display_name", sa.String(length=128), nullable=False),
|
||
sa.Column("version", sa.Integer(), server_default="1", nullable=False),
|
||
sa.Column("status", sa.String(length=16), server_default="draft", nullable=False),
|
||
sa.Column("file_format", sa.String(length=16), server_default="xlsx", nullable=False),
|
||
sa.Column("definition_json", sa.JSON(), nullable=False),
|
||
sa.Column("checksum", sa.String(length=64), nullable=True),
|
||
sa.Column("structure_definition_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False),
|
||
sa.Column("exact_structure_fingerprint", sa.String(length=64), nullable=True),
|
||
sa.Column("compatibility_fingerprint", sa.String(length=64), nullable=True),
|
||
sa.Column("fingerprint_version", sa.String(length=32), nullable=True),
|
||
sa.Column("sample_analysis_id", sa.Integer(), nullable=True),
|
||
sa.Column("sample_evidence_history_json", sa.JSON(), server_default=sa.text("'[]'"), nullable=False),
|
||
sa.Column("created_by", sa.Integer(), nullable=True),
|
||
sa.Column("published_by", sa.Integer(), nullable=True),
|
||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||
sa.Column("published_at", sa.DateTime(), nullable=True),
|
||
sa.UniqueConstraint("profile_code", "version", name="uq_inventory_parsing_profiles_code_version"),
|
||
sa.CheckConstraint(
|
||
"purpose IN ('inventory', 'movement')",
|
||
name="ck_shipping_inventory_parsing_profiles_purpose",
|
||
),
|
||
sa.ForeignKeyConstraint(["sample_analysis_id"], ["shipping_inventory_structure_analyses.id"]),
|
||
sa.ForeignKeyConstraint(["created_by"], ["users.id"]),
|
||
sa.ForeignKeyConstraint(["published_by"], ["users.id"]),
|
||
)
|
||
return md
|
||
|
||
|
||
_LEGACY_ROW_COLUMNS = (
|
||
"purpose, profile_code, display_name, version, status, file_format, "
|
||
"definition_json, structure_definition_json, sample_evidence_history_json, created_at"
|
||
)
|
||
|
||
|
||
def _insert_profile(connection, *, purpose: str, profile_code: str) -> None:
|
||
"""按旧枚举直接插入一条解析规则行(旧 CHECK 放行 inventory/movement)。"""
|
||
connection.execute(sa.text(
|
||
f"INSERT INTO shipping_inventory_parsing_profiles ({_LEGACY_ROW_COLUMNS}) "
|
||
f"VALUES ('{purpose}', '{profile_code}', '{profile_code} 规则', 1, 'published', 'xlsx', "
|
||
f"'{{}}', '{{}}', '[]', '2026-01-01 00:00:00')"
|
||
))
|
||
|
||
|
||
def _purpose_by_code(connection) -> dict[str, str]:
|
||
rows = connection.execute(sa.text(
|
||
"SELECT profile_code, purpose FROM shipping_inventory_parsing_profiles"
|
||
)).fetchall()
|
||
return {code: purpose for code, purpose in rows}
|
||
|
||
|
||
def _column_default(connection, column: str) -> str:
|
||
columns = {c["name"]: c for c in sa.inspect(connection).get_columns("shipping_inventory_parsing_profiles")}
|
||
return str(columns[column].get("default") or "")
|
||
|
||
|
||
def test_tt15_sqlite_roundtrip_upgrade_downgrade_upgrade():
|
||
"""SQLite 真实往返:upgrade 换枚举并迁数据 / downgrade 对称还原 / 再 upgrade。
|
||
|
||
[断言意图] 前置表(旧枚举 default 'inventory' + 旧 CHECK)就位后,tt15 的
|
||
batch DROP CHECK → 数据 UPDATE → ADD CHECK → SET DEFAULT 不丢列、不丢数据;
|
||
存量 inventory→onhand、movement→inbound 精确映射;新 CHECK 真实生效
|
||
(outbound 放行、旧值拒写);downgrade 对称(outbound/inbound→movement 结构就位
|
||
语义最接近),default/CHECK 翻转可回滚。
|
||
"""
|
||
engine = sa.create_engine("sqlite:///:memory:")
|
||
with engine.begin() as connection:
|
||
context = MigrationContext.configure(connection)
|
||
operations = Operations(context)
|
||
_prestate_metadata().create_all(connection)
|
||
|
||
_insert_profile(connection, purpose='inventory', profile_code='LEG_INV')
|
||
_insert_profile(connection, purpose='movement', profile_code='LEG_MOVE')
|
||
# 前置基线:旧 CHECK 放行 inventory/movement、拒新枚举。
|
||
_insert_profile(connection, purpose='movement', profile_code='BASE_MOVE')
|
||
assert "inventory" in _column_default(connection, "purpose")
|
||
|
||
migration = _load_migration(REVISION)
|
||
migration.op = operations
|
||
|
||
migration.upgrade()
|
||
# [断言意图] 数据迁移:inventory→onhand、movement→inbound。
|
||
assert _purpose_by_code(connection) == {
|
||
'LEG_INV': 'onhand', 'LEG_MOVE': 'inbound', 'BASE_MOVE': 'inbound',
|
||
}
|
||
# [断言意图] 列默认值翻转为 'onhand'。
|
||
assert "onhand" in _column_default(connection, "purpose")
|
||
# [断言意图] 新 CHECK 真实生效:outbound 放行、旧值 inventory 拒写。
|
||
_insert_profile(connection, purpose='outbound', profile_code='NEW_OUT')
|
||
with pytest.raises(sa.exc.IntegrityError):
|
||
_insert_profile(connection, purpose='inventory', profile_code='REJECT_OLD')
|
||
|
||
migration.downgrade()
|
||
# [断言意图] downgrade 对称:onhand→inventory,inbound/outbound→movement。
|
||
assert _purpose_by_code(connection) == {
|
||
'LEG_INV': 'inventory', 'LEG_MOVE': 'movement', 'BASE_MOVE': 'movement', 'NEW_OUT': 'movement',
|
||
}
|
||
assert "inventory" in _column_default(connection, "purpose")
|
||
# [断言意图] 旧 CHECK 还原:inventory 放行、新值 onhand 拒写。
|
||
_insert_profile(connection, purpose='inventory', profile_code='BACK_INV')
|
||
with pytest.raises(sa.exc.IntegrityError):
|
||
_insert_profile(connection, purpose='onhand', profile_code='REJECT_NEW')
|
||
|
||
migration.upgrade()
|
||
assert _purpose_by_code(connection) == {
|
||
'LEG_INV': 'onhand', 'LEG_MOVE': 'inbound', 'BASE_MOVE': 'inbound',
|
||
'NEW_OUT': 'inbound', 'BACK_INV': 'onhand',
|
||
}
|
||
assert "onhand" in _column_default(connection, "purpose")
|