Files
syops/backend/tests/test_inventory_configuration_test.py
T

239 lines
13 KiB
Python

"""验证库存站点测试导出的隔离、结构识别和解析方案确认。"""
from __future__ import annotations
from pathlib import Path
from unittest.mock import patch
import pytest
from cryptography.fernet import Fernet
from openpyxl import Workbook
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingInventoryConfigurationTestRun,
ShippingInventoryExternalMapping,
ShippingExcelTemplate,
ShippingExcelTemplate,
ShippingInventoryFile,
ShippingInventoryField,
ShippingInventorySource,
)
from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import (
inventory_configuration_test,
inventory_parsing_profile,
inventory_structure_analysis,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
def _inventory_field_id(field_code: str) -> str:
"""获取测试显式创建的用户库存字段 ID。"""
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
def _workbook(path: Path) -> None:
"""生成模拟 RPA 下载完成的最小库存 Excel。"""
workbook = Workbook()
sheet = workbook.active
sheet.append(['Supplier Sku', 'Reservation ID', 'Qty Available'])
sheet.append(['PN-1', '1000140351', 9])
workbook.save(path)
def _source() -> dict:
"""创建一个保持停用的 DBS 库存站点。"""
login = shipping_inventory_service.save_profile({
'profile_code': 'TEST_EXPORT_LOGIN', 'display_name': 'Test Login', 'connector_type': 'dbs',
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
'username': 'user', 'password': 'password', 'enabled': True,
}, actor_id=None)
return shipping_inventory_service.save_source({
'source_code': 'TEST_EXPORT_SOURCE', 'display_name': 'Test Export Source', 'connector_type': 'dbs',
'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None,
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
'enabled': False,
'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
'query_parameters_json': [], 'match_aliases_json': [],
}, actor_id=None)
def _published_order_field() -> str:
"""创建测试解析方案所需的已发布订单明细字段。"""
order_schema_service.initialize_schema({'display_name': 'Configuration Test'}, actor_id=None)
field = order_schema_service.save_field({
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
draft = order_schema_service.create_draft({}, actor_id=None)
saved = order_schema_service.save_draft(draft['id'], {'fields': [{
'field_id': field['id'], 'display_name': '料号', 'required': True, 'aliases': [],
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'],
'conflict_policy': 'block', 'allow_single_source': True},
'relation_role': None, 'comparator_key': 'normalized_text', 'extraction_instruction': '提取料号',
}], 'expected_lock_version': draft['lock_version']})
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
return field['id']
def _publish_profile_from_analysis(analysis_id: int, field_id: str, *, code: str) -> dict:
"""从测试分析创建并发布方案,模拟管理员确认解析配置的前置动作。"""
analysis = inventory_structure_analysis.get_analysis(analysis_id)
draft = inventory_structure_analysis.create_profile_draft(analysis_id, {
'profile_code': code, 'display_name': code, 'sheet_name': 'Sheet', 'header_row_index': 1,
'field_mapping': {
_inventory_field_id('part_number'): 'Supplier Sku',
_inventory_field_id('reservation_id'): 'Reservation ID',
_inventory_field_id('available_qty'): 'Qty Available',
},
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}],
}, actor_id=None)
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
def _complete_test_run(source: dict, tmp_path: Path) -> dict:
"""完成一次模拟 RPA 测试导出,返回可供确认的测试运行。"""
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
result_file = tmp_path / f"{started['run_no']}.xlsx"
_workbook(result_file)
return inventory_configuration_test.report_test_export({
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
})
def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path):
"""测试文件只能生成测试分析,重复发起复用运行,禁止创建生产库存快照。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
assert started['status'] == 'awaiting_rpa'
assert inventory_configuration_test.start_test_export(source['id'], actor_id=None)['run_no'] == started['run_no']
result_file = tmp_path / 'rpa-result.xlsx'
_workbook(result_file)
completed = inventory_configuration_test.report_test_export({
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
})
assert completed['status'] == 'completed'
assert completed['stage'] == 'ready_for_confirmation'
assert not ShippingInventoryFile.query.count()
assert ShippingInventoryConfigurationTestRun.query.count() == 1
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
"""确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
completed = _complete_test_run(source, tmp_path)
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_CONFIRMED')
confirmed = inventory_configuration_test.confirm_test_profile(
source['id'], completed['run_no'], profile['id'], actor_id=None,
)
assert confirmed['parsing_profile_id'] == profile['id']
source_model = db.session.get(ShippingInventorySource, source['id'])
assert source_model.parsing_profile_id == profile['id']
assert 'configuration_test' not in shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements']
assert 'warehouse_mapping' in shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements']
db.session.add(ShippingInventoryExternalMapping(
inventory_source_id=source['id'], freight_warehouse_id='DUB', external_system_code='TOPGP',
external_warehouse_code='DUB-01', external_warehouse_name='Dublin', enabled=True,
))
template = ShippingExcelTemplate(
template_code='TEST_ACTIVATION', display_name='Activation Template', version=1, status='published',
storage_bucket='test', storage_key='activation.xlsx', original_filename='activation.xlsx',
file_checksum='0' * 64,
definition_json={'filename_pattern': '{business_no}.xlsx', 'mappings': [{
'sheet': 'Sheet', 'row_mode': 'line', 'start_row': 2, 'target_column': 1,
'source_kind': 'inventory_field', 'source_key': _inventory_field_id('part_number'), 'formatter': 'text',
}]}, definition_checksum='1' * 64,
)
db.session.add(template)
db.session.flush()
source_model.excel_template_id = template.id
db.session.commit()
assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True
assert shipping_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True
def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path):
"""正式运行中的站点不能发起测试;站点配置变化后旧测试不得绑定。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
completed = _complete_test_run(source, tmp_path)
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_STALE')
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
shipping_inventory_service.save_source({**current, 'display_name': 'Changed after test'}, actor_id=None, source_id=source['id'])
with pytest.raises(ConflictError) as stale:
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
assert stale.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE'
source_model = db.session.get(ShippingInventorySource, source['id'])
source_model.parsing_profile_id = profile['id']
template = ShippingExcelTemplate(
template_code='TEST_ENABLED', display_name='Test Enabled', version=1, status='published',
storage_bucket='test', storage_key='test.xlsx', original_filename='test.xlsx',
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
)
db.session.add(template)
db.session.flush()
source_model.excel_template_id = template.id
source_model.enabled = True
db.session.commit()
with pytest.raises(ConflictError) as enabled:
inventory_configuration_test.start_test_export(source['id'], actor_id=None)
assert enabled.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID'
def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
"""失败回调和非推荐方案均不得产生生产快照或修改站点解析方案。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
failed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
result = inventory_configuration_test.report_test_export({
'run_no': failed['run_no'], 'status': 'failed', 'error_message': 'RPA login failed',
})
assert result['status'] == 'failed'
assert not ShippingInventoryFile.query.count()
completed = _complete_test_run(source, tmp_path)
field_id = _published_order_field()
_publish_profile_from_analysis(completed['analysis_id'], field_id, code='TEST_MATCHED')
unrelated = inventory_parsing_profile.save_draft({
'profile_code': 'TEST_UNRELATED', 'display_name': 'Unrelated', 'file_format': 'xlsx',
'definition': {
'sheet_name': 'Other', 'header_row_index': 1,
'field_mapping': {
_inventory_field_id('part_number'): 'Other Part',
_inventory_field_id('reservation_id'): 'Other Reservation',
_inventory_field_id('available_qty'): 'Other Qty',
},
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}],
},
}, actor_id=None)
unrelated = inventory_parsing_profile.publish(unrelated['id'], actor_id=None)
with pytest.raises(ValidationError) as rejected:
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], unrelated['id'], actor_id=None)
assert rejected.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID'
assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None