354 lines
18 KiB
Python
354 lines
18 KiB
Python
"""
|
|
tests/test_shipping_inventory_configuration.py
|
|
|
|
用途:验证库存源主数据、外部系统映射约束和 RPA 凭据加密的阶段一契约。
|
|
依赖:Flask app/db、库存配置模型、credential_crypto、inventory_source_repository。
|
|
逻辑:阶段二前锁定最小数据安全与关系约束,避免错误配置进入路由或 RPA 执行链路。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from cryptography.fernet import Fernet
|
|
import pytest
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
from app.core.errors import ServiceUnavailableError, ValidationError
|
|
from app.extensions import db
|
|
from app.models import (
|
|
ShippingExcelTemplate, ShippingInventoryExternalMapping, ShippingInventoryFile,
|
|
ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
|
|
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
|
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
|
|
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
|
|
)
|
|
from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential
|
|
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
|
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source
|
|
from app.services.shipping_notice.inventory_external_mapping import resolve_external_warehouse
|
|
|
|
|
|
def _profile(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> ShippingRpaProfile:
|
|
"""构造最小可持久化 RPA Profile,避免测试包含明文真实凭据。"""
|
|
return ShippingRpaProfile(
|
|
profile_code=code,
|
|
display_name=code,
|
|
connector_type=connector_type,
|
|
login_url='https://example.invalid/login',
|
|
login_config_json={'auth_mode': 'password'},
|
|
)
|
|
|
|
|
|
def _source(profile: ShippingRpaProfile, *, code: str = 'DBS_DUB', mode: str = 'fixed') -> ShippingInventorySource:
|
|
"""构造固定或动态 Warehouse 的库存源,供约束测试复用。"""
|
|
parsing = ShippingInventoryParsingProfile(
|
|
profile_code=f'{code}_PARSING', display_name=f'{code} Parsing', version=1,
|
|
status='published', file_format='xlsx', definition_json={'match_keys': []},
|
|
)
|
|
template = ShippingExcelTemplate(
|
|
template_code=f'{code}_EXPORT', display_name=f'{code} Export', version=1,
|
|
status='published', storage_provider='minio', storage_bucket='test',
|
|
storage_key=f'test/{code}-export.xlsx', original_filename='template.xlsx',
|
|
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
|
|
)
|
|
return ShippingInventorySource(
|
|
source_code=code,
|
|
display_name=code,
|
|
connector_type=profile.connector_type,
|
|
rpa_profile=profile,
|
|
parsing_profile=parsing,
|
|
excel_template=template,
|
|
warehouse_resolution_mode=mode,
|
|
fixed_warehouse_id='DUB' if mode == 'fixed' else None,
|
|
)
|
|
|
|
|
|
def test_encrypt_credential_round_trip_requires_runtime_key(app):
|
|
"""凭据必须依赖环境主密钥加密,且可在受控运行时回读。"""
|
|
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
|
with app.app_context():
|
|
ciphertext = encrypt_credential('not-a-real-password')
|
|
assert ciphertext != 'not-a-real-password'
|
|
assert decrypt_credential(ciphertext) == 'not-a-real-password'
|
|
|
|
|
|
def test_encrypt_credential_rejects_missing_runtime_key(app):
|
|
"""关键加密主密钥缺失时拒绝写入凭据,避免产生不可恢复密文。"""
|
|
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = ''
|
|
with app.app_context(), pytest.raises(ServiceUnavailableError):
|
|
encrypt_credential('not-a-real-password')
|
|
|
|
|
|
def test_source_profile_connector_types_must_match(app):
|
|
"""Source 绑定不同 Driver 的 Profile 必须被服务层拒绝。"""
|
|
with app.app_context(), pytest.raises(ValidationError) as exc_info:
|
|
validate_source_profile(_source(_profile(connector_type='dbs')), _profile(code='CRANE_01', connector_type='crane'))
|
|
assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH'
|
|
|
|
|
|
def test_dynamic_source_disallows_fixed_warehouse_in_database(app):
|
|
"""动态仓 Source 不得保存固定 Warehouse,避免 Crane 配置被误建为单仓。"""
|
|
with app.app_context():
|
|
profile = _profile(connector_type='crane')
|
|
source = _source(profile, code='CRANE', mode='inventory_match')
|
|
source.fixed_warehouse_id = 'TZR'
|
|
db.session.add_all([profile, source])
|
|
with pytest.raises(IntegrityError):
|
|
db.session.commit()
|
|
db.session.rollback()
|
|
|
|
|
|
def test_external_mapping_allows_topgp_organization_code_to_be_null(app):
|
|
"""TOPGP 无公司代码概念时,映射必须允许 NULL 而非伪造占位值。"""
|
|
with app.app_context():
|
|
profile = _profile()
|
|
source = _source(profile)
|
|
mapping = ShippingInventoryExternalMapping(
|
|
inventory_source=source,
|
|
freight_warehouse_id='DUB',
|
|
external_system_code='TOPGP',
|
|
external_organization_code=None,
|
|
external_site_code='EU01',
|
|
external_warehouse_code='DUB01',
|
|
external_warehouse_name='Dublin Warehouse',
|
|
)
|
|
db.session.add(mapping)
|
|
db.session.commit()
|
|
assert mapping.id is not None
|
|
|
|
|
|
def test_database_source_snapshot_excludes_profile_credentials(app):
|
|
"""运行时 Source 快照只提供操作配置,禁止泄漏 Profile 凭据字段。"""
|
|
with app.app_context():
|
|
profile = _profile()
|
|
profile.username_ciphertext = 'ciphertext'
|
|
profile.password_ciphertext = 'ciphertext'
|
|
source = _source(profile)
|
|
db.session.add(source)
|
|
db.session.commit()
|
|
payload = get_database_inventory_source('DBS_DUB')
|
|
assert payload is not None
|
|
assert payload['source_code'] == 'DBS_DUB'
|
|
assert 'username_ciphertext' not in payload
|
|
assert 'password_ciphertext' not in payload
|
|
|
|
|
|
def test_database_source_snapshot_uses_source_business_report_configuration(app):
|
|
"""运行时快照必须从 Source 读取报表路径和查询条件,不得从 Profile 读取旧报表配置。"""
|
|
with app.app_context():
|
|
profile = _profile()
|
|
profile.login_config_json = {'auth_mode': 'password'}
|
|
source = _source(profile)
|
|
source.report_path_json = {
|
|
'program_group': 'Bison', 'program_label': 'AWSBI',
|
|
'report_group': 'Inventory', 'report_name': 'Source Report',
|
|
}
|
|
source.query_parameters_json = [
|
|
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
|
|
]
|
|
db.session.add(source)
|
|
db.session.commit()
|
|
|
|
payload = get_database_inventory_source('DBS_DUB')
|
|
assert payload is not None
|
|
assert payload['navigation']['report_name'] == 'Source Report'
|
|
assert payload['parameters'][0]['name'] == 'Warehouse'
|
|
assert 'operation_config' not in payload
|
|
assert payload['login_config'] == {'auth_mode': 'password'}
|
|
|
|
|
|
def test_rpa_trigger_snapshot_keeps_profile_credentials_encrypted(app):
|
|
"""RPA 专用快照可投递密文,但任何运行时普通读取不得获得该字段。"""
|
|
with app.app_context():
|
|
profile = _profile()
|
|
profile.username_ciphertext = 'encrypted-user'
|
|
profile.password_ciphertext = 'encrypted-password'
|
|
db.session.add(_source(profile))
|
|
db.session.commit()
|
|
payload = get_rpa_trigger_inventory_source('DBS_DUB')
|
|
assert payload is not None
|
|
assert payload['credential_envelope'] == {
|
|
'username_ciphertext': 'encrypted-user',
|
|
'password_ciphertext': 'encrypted-password',
|
|
}
|
|
|
|
|
|
def test_external_mapping_prefers_exact_warehouse_then_source_default(app):
|
|
"""同一 Source 的动态仓先命中精确映射,未命中时才回退默认外部系统仓库。"""
|
|
with app.app_context():
|
|
profile = _profile(code='CRANE_EU', connector_type='crane')
|
|
source = _source(profile, code='CRANE', mode='inventory_match')
|
|
exact = ShippingInventoryExternalMapping(
|
|
inventory_source=source, freight_warehouse_id='FRA', external_system_code='TOPGP',
|
|
external_warehouse_code='FRA01', external_warehouse_name='Frankfurt',
|
|
)
|
|
fallback = ShippingInventoryExternalMapping(
|
|
inventory_source=source, freight_warehouse_id=None, external_system_code='TOPGP',
|
|
external_warehouse_code='CRANE_DEFAULT', external_warehouse_name='Crane Default',
|
|
)
|
|
db.session.add_all([exact, fallback])
|
|
db.session.commit()
|
|
|
|
assert resolve_external_warehouse(source_code='CRANE', freight_warehouse_id='FRA')['external_warehouse_code'] == 'FRA01'
|
|
assert resolve_external_warehouse(source_code='CRANE', freight_warehouse_id='fra')['external_warehouse_code'] == 'FRA01'
|
|
assert resolve_external_warehouse(source_code='CRANE', freight_warehouse_id='SIN')['external_warehouse_code'] == 'CRANE_DEFAULT'
|
|
|
|
|
|
def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, tmp_path):
|
|
"""动态 Source 只能以订单键命中的库存行确定 Warehouse,不能按库存数量挑选。"""
|
|
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
|
|
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
|
from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context
|
|
|
|
with app.app_context():
|
|
source = _source(_profile(code='CRANE_PROFILE', connector_type='crane'), code='CRANE', mode='inventory_match')
|
|
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
|
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
|
db.session.add(schema)
|
|
db.session.flush()
|
|
from app.services.shipping_notice import field_asset_service
|
|
field_asset_service.ensure_standard_assets_seeded()
|
|
part_field = ShippingOrderField.query.filter_by(field_code='part_number', scope='line').one()
|
|
reservation_field = ShippingOrderField.query.filter_by(field_code='reservation_id', scope='line').one()
|
|
version = ShippingOrderSchemaVersion(
|
|
schema_id=schema.id, version=1, status='published', checksum='d' * 64,
|
|
definition_json={'fields': [
|
|
{'field_id': part_field.id, 'field_code': part_field.field_code, 'scope': 'line', 'value_type': 'string'},
|
|
{'field_id': reservation_field.id, 'field_code': reservation_field.field_code, 'scope': 'line', 'value_type': 'string'},
|
|
]},
|
|
)
|
|
source.parsing_profile.definition_json = {
|
|
'field_mapping': {
|
|
inventory_fields['part_number']: 'Part',
|
|
inventory_fields['reservation_id']: 'Reservation',
|
|
inventory_fields['available_qty']: 'Qty',
|
|
inventory_fields['warehouse_id']: 'Warehouse',
|
|
},
|
|
'match_keys': [
|
|
{'order_field_id': part_field.id, 'inventory_field_id': inventory_fields['part_number']},
|
|
{'order_field_id': reservation_field.id, 'inventory_field_id': inventory_fields['reservation_id']},
|
|
],
|
|
}
|
|
db.session.add(source)
|
|
db.session.add_all([schema, version])
|
|
db.session.flush()
|
|
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='d' * 64, status='accepted')
|
|
db.session.add(extraction)
|
|
db.session.flush()
|
|
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
|
|
db.session.add(order_line)
|
|
db.session.flush()
|
|
part_decision = ShippingOrderFieldDecision(
|
|
extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id,
|
|
decision_status='accepted', resolved_value_json='A001',
|
|
)
|
|
reservation_decision = ShippingOrderFieldDecision(
|
|
extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id,
|
|
decision_status='accepted', resolved_value_json='R-1',
|
|
)
|
|
db.session.add_all([part_decision, reservation_decision])
|
|
db.session.flush()
|
|
db.session.add_all([
|
|
ShippingOrderFieldValue(
|
|
extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id,
|
|
value_text='A001', decision_id=part_decision.id,
|
|
),
|
|
ShippingOrderFieldValue(
|
|
extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id,
|
|
value_text='R-1', decision_id=reservation_decision.id,
|
|
),
|
|
])
|
|
task = ShippingNotice(
|
|
task_no='SN-DYNAMIC-WH', source_type='manual', inventory_source_code='CRANE',
|
|
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
|
|
current_order_extraction_id=extraction.id,
|
|
)
|
|
task.inventory_source_config_version = inventory_sources_runtime_version()
|
|
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
|
db.session.add(task)
|
|
db.session.flush()
|
|
order_snapshot = ShippingOrderSnapshot(
|
|
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
|
|
order_data_version=1, rule_versions_json={}, header_values_json={},
|
|
)
|
|
db.session.add(order_snapshot)
|
|
db.session.flush()
|
|
db.session.add(ShippingOrderSnapshotLine(
|
|
snapshot_id=order_snapshot.id, position=1, part_number='A001', reservation_id='R-1',
|
|
field_values_json={str(part_field.id): 'A001', str(reservation_field.id): 'R-1'},
|
|
))
|
|
task.order_snapshot_id = order_snapshot.id
|
|
path = tmp_path / 'dynamic.xlsx'
|
|
path.write_bytes(b'not-parsed-in-this-test')
|
|
snapshot = ShippingInventoryFile(
|
|
inventory_file_no='SIF-DYNAMIC-WH', storage_path=str(path), snapshot_status='ready',
|
|
source_code='CRANE', warehouse_id='FALLBACK', share_mode='warehouse_pool',
|
|
inventory_lines_json=[
|
|
{
|
|
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
|
|
inventory_fields['warehouse_id']: 'FRA', inventory_fields['available_qty']: 1,
|
|
},
|
|
{
|
|
inventory_fields['part_number']: 'OTHER', inventory_fields['reservation_id']: 'R-2',
|
|
inventory_fields['warehouse_id']: 'SIN', inventory_fields['available_qty']: 999,
|
|
},
|
|
],
|
|
)
|
|
db.session.add(snapshot)
|
|
db.session.commit()
|
|
link = link_snapshot_to_task(task, snapshot, reason='dynamic_test')
|
|
assert link is not None
|
|
assert task.inventory_warehouse_id == 'FRA'
|
|
assert link.matched_warehouse_id == 'FRA'
|
|
|
|
|
|
def test_dynamic_source_rejects_ambiguous_warehouse_for_same_order_key(app, tmp_path):
|
|
"""同一 Reservation + PN 对应多个 Warehouse 时必须拒绝关联,防止错误业务路由。"""
|
|
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
|
|
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
|
from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context
|
|
|
|
with app.app_context():
|
|
source = _source(_profile(code='CRANE_AMBIG_PROFILE', connector_type='crane'), code='CRANE_AMBIG', mode='inventory_match')
|
|
db.session.add(source)
|
|
db.session.commit()
|
|
task = ShippingNotice(
|
|
task_no='SN-DYNAMIC-AMBIG', source_type='manual', inventory_source_code='CRANE_AMBIG',
|
|
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
|
|
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
|
|
)
|
|
task.inventory_source_config_version = inventory_sources_runtime_version()
|
|
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
|
path = tmp_path / 'ambiguous.xlsx'
|
|
path.write_bytes(b'not-parsed-in-this-test')
|
|
snapshot = ShippingInventoryFile(
|
|
inventory_file_no='SIF-DYNAMIC-AMBIG', storage_path=str(path), snapshot_status='ready',
|
|
source_code='CRANE_AMBIG', warehouse_id='FALLBACK', share_mode='warehouse_pool',
|
|
inventory_lines_json=[
|
|
{'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'FRA', 'available_qty': 1},
|
|
{'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'SIN', 'available_qty': 1},
|
|
],
|
|
)
|
|
db.session.add_all([task, snapshot])
|
|
db.session.commit()
|
|
assert link_snapshot_to_task(task, snapshot, reason='dynamic_test') is None
|
|
assert task.inventory_warehouse_id is None
|
|
|
|
|
|
def test_dynamic_snapshot_is_idempotent_per_rpa_run(app, tmp_path):
|
|
"""同一 RPA run 的动态多仓文件只能入库一次,避免回调重放产生重复快照。"""
|
|
with app.app_context():
|
|
first = ShippingInventoryFile(
|
|
inventory_file_no='SIF-DYNAMIC-IDEMPOTENT-1', storage_path=str(tmp_path / 'first.xlsx'),
|
|
snapshot_status='ready', source_code='CRANE', warehouse_id=None, rpa_run_no='RUN-DYNAMIC-1',
|
|
)
|
|
second = ShippingInventoryFile(
|
|
inventory_file_no='SIF-DYNAMIC-IDEMPOTENT-2', storage_path=str(tmp_path / 'second.xlsx'),
|
|
snapshot_status='ready', source_code='CRANE', warehouse_id=None, rpa_run_no='RUN-DYNAMIC-1',
|
|
)
|
|
db.session.add(first)
|
|
db.session.commit()
|
|
db.session.add(second)
|
|
with pytest.raises(IntegrityError):
|
|
db.session.commit()
|
|
db.session.rollback()
|