336 lines
19 KiB
Python
336 lines
19 KiB
Python
"""验证库存站点测试导出的隔离、结构识别和解析方案确认。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timedelta
|
|
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,
|
|
ShippingRpaProfile,
|
|
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_latest_configuration_test_recovers_only_current_configuration(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()
|
|
first = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
assert inventory_configuration_test.get_latest_test_run(source['id'])['run_no'] == first['run_no']
|
|
|
|
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 before callback'}, actor_id=None, source_id=source['id'])
|
|
|
|
# 关键断言:旧运行不再属于当前配置,重新测试必须创建新运行而不是误复用。
|
|
assert inventory_configuration_test.get_latest_test_run(source['id']) is None
|
|
second = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
assert second['run_no'] != first['run_no']
|
|
assert inventory_configuration_test.get_latest_test_run(source['id'])['run_no'] == second['run_no']
|
|
|
|
|
|
def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
|
"""RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
|
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
|
|
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)
|
|
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one()
|
|
run.created_at = datetime.utcnow() - timedelta(seconds=2)
|
|
db.session.commit()
|
|
|
|
recovered = inventory_configuration_test.get_latest_test_run(source['id'])
|
|
# 关键断言:超时是明确失败终态,客户端无需自行推断或继续轮询。
|
|
assert recovered['status'] == 'failed'
|
|
assert recovered['stage'] == 'failed'
|
|
assert '超时' in recovered['error_message']
|
|
|
|
result_file = tmp_path / 'late-rpa-result.xlsx'
|
|
_workbook(result_file)
|
|
late_callback = inventory_configuration_test.report_test_export({
|
|
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
|
|
})
|
|
# 关键断言:超时后的迟到回调不能将失败任务重新写成完成,也不能生成结构分析证据。
|
|
assert late_callback['status'] == 'failed'
|
|
assert ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one().analysis_id is None
|
|
|
|
|
|
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
|
|
assert next(
|
|
item for item in shipping_inventory_service.get_source_activation_status(source_model)['checks']
|
|
if item['code'] == 'configuration_test'
|
|
)['status'] == 'passed'
|
|
|
|
|
|
def test_rpa_profile_change_stales_completed_configuration_test(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='PROFILE_STALE')
|
|
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
|
|
|
|
rpa_profile = db.session.get(ShippingRpaProfile, source['rpa_profile_id'])
|
|
shipping_inventory_service.save_profile({
|
|
'profile_code': rpa_profile.profile_code, 'display_name': rpa_profile.display_name,
|
|
'connector_type': rpa_profile.connector_type, 'login_url': rpa_profile.login_url,
|
|
'login_config_json': rpa_profile.login_config_json, 'enabled': True,
|
|
'username': 'updated-user', 'password': 'updated-password',
|
|
}, actor_id=None, profile_id=rpa_profile.id)
|
|
|
|
source_model = db.session.get(ShippingInventorySource, source['id'])
|
|
test_check = next(
|
|
item for item in shipping_inventory_service.get_source_activation_status(source_model)['checks']
|
|
if item['code'] == 'configuration_test'
|
|
)
|
|
# 关键断言:连接配置版本变更使已完成测试失效,不能继续放行正式运行。
|
|
assert test_check['status'] == 'stale'
|
|
assert test_check['blocking'] 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'
|
|
|
|
# 关键断言:旧配置版本的测试只能作为过期证据展示,不能被误判为当前测试通过。
|
|
stale_status = shipping_inventory_service.get_source_activation_status(
|
|
db.session.get(ShippingInventorySource, source['id']),
|
|
)
|
|
test_check = next(item for item in stale_status['checks'] if item['code'] == 'configuration_test')
|
|
assert test_check['status'] == 'stale'
|
|
assert test_check['blocking'] is True
|
|
assert test_check['evidence']['run_no'] == completed['run_no']
|
|
|
|
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',
|
|
'sample_analysis_id': completed['analysis_id'],
|
|
'definition': {
|
|
'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)
|
|
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
|