- AGENTS.md §8.1 红线改写:env 命名空间恢复 FREIGHT_RPA_*,SHIPPING_NOTICE_RPA_* 一刀切废弃、不设兼容层
- 全仓机械前缀替换(70 文件)并删除兼容层;4 个既有基线测试失败一并清零(过期桩/存储隔离/排程 fail-fast 接线)
- 运行期数据目录统一 freight_rpa/{inventory,receipt,common}:settings 默认、4 个 env、2 个 ps1 三侧一致
- 代码目录 scripts/rpa 更名 scripts/freight_rpa 与数据根对齐;全仓路径引用同步,README 部署走查与升级小节
- 收料部署对齐库存:计划任务注册脚本(独立任务名)、可选 -SessionReuse 会话复用、DSV 老别名链移除
- readiness 加固:排程离线立即 failed(不挂 awaiting);无 Redis 时追加进程内存储原因码与本地测试指引
- DSV 会话准备遇 SSO 重定向中止时改走自动登录,首源不再因未登录判死
690 lines
42 KiB
Python
690 lines
42 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,
|
|
ShippingInventoryValidationBatch,
|
|
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(code: str = 'TEST_EXPORT_SOURCE', profile_code: str = 'TEST_EXPORT_LOGIN') -> dict:
|
|
"""创建一个保持停用的 DBS 库存站点。"""
|
|
login = shipping_inventory_service.save_profile({
|
|
'profile_code': profile_code, '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': code, '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': [],
|
|
}, 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 _published_template(*, code: str) -> ShippingExcelTemplate:
|
|
"""创建引用库存料号字段的最小已发布发货模板,满足自动启用门禁。"""
|
|
template = ShippingExcelTemplate(
|
|
template_code=code, display_name=code, version=1, status='published',
|
|
storage_bucket='test', storage_key=f'{code}.xlsx', original_filename=f'{code}.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()
|
|
return template
|
|
|
|
|
|
def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path):
|
|
"""测试文件只能生成测试分析,重复发起复用运行,禁止创建生产库存快照。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
app.config['FREIGHT_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_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app, tmp_path):
|
|
"""Worker 回传 Windows drop 路径时,必须映射到 Linux 共享目录再分析,不能报「文件不存在」。"""
|
|
drop_dir = tmp_path / 'inventory_drop'
|
|
drop_dir.mkdir()
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
|
app.config['FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
|
|
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)
|
|
result_file = drop_dir / f"inventory_{started['run_no']}_DSV360_BYAWSPRD01.xlsx"
|
|
_workbook(result_file)
|
|
windows_path = rf'C:\HxopsRpaTest\data\inventory_drop\{result_file.name}'
|
|
completed = inventory_configuration_test.report_test_export({
|
|
'run_no': started['run_no'], 'status': 'success', 'file_path': windows_path,
|
|
})
|
|
assert completed['status'] == 'completed'
|
|
assert completed.get('error_message') in (None, '')
|
|
assert not ShippingInventoryFile.query.count()
|
|
|
|
|
|
def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
|
|
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
|
|
app.config['FREIGHT_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()
|
|
field_id = _published_order_field()
|
|
analysis_path = tmp_path / 'profile-evidence.xlsx'
|
|
_workbook(analysis_path)
|
|
seed_run = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
seeded = inventory_configuration_test.report_test_export({
|
|
'run_no': seed_run['run_no'], 'status': 'success', 'file_path': str(analysis_path),
|
|
})
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], field_id, code='EMPTY_RESULT_PROFILE')
|
|
shipping_inventory_service.bind_source_parsing_profile(
|
|
[source['id']], profile['id'], actor_id=None, reason='空结果前已确认同类报表结构', operation='direct',
|
|
)
|
|
|
|
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
result = inventory_configuration_test.report_test_export({
|
|
'run_no': started['run_no'], 'status': 'empty', 'message': 'no inventory rows',
|
|
})
|
|
|
|
# 关键断言:空结果保留数据质量待验证,而不是伪造失败或生成生产快照。
|
|
assert result['status'] == 'completed_empty'
|
|
assert result['stage'] == 'empty_data_pending_validation'
|
|
assert result['result']['data_validation'] == 'pending_first_non_empty_export'
|
|
assert not ShippingInventoryFile.query.count()
|
|
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
|
checks = {item['code']: item for item in current['activation']['checks']}
|
|
# 关键断言:连接测试已通过;数量与匹配字段仅待首次非空文件验证,不能伪装成失败。
|
|
assert checks['configuration_test']['status'] == 'empty'
|
|
assert checks['configuration_test']['blocking'] is False
|
|
assert checks['parsing_validation']['status'] == 'pending'
|
|
assert checks['parsing_validation']['blocking'] is False
|
|
assert checks['warehouse_mapping']['blocking'] is False
|
|
# 关键断言:无库存不会被行级解析或调拨映射阻断;本例仍缺发货模板,因此尚不可启用。
|
|
assert current['activation']['missing_requirements'] == ['excel_template']
|
|
|
|
|
|
def test_empty_configuration_export_without_published_profile_is_rejected(app):
|
|
"""没有受控解析定义时,空结果不能被用作站点可用性的替代证据。"""
|
|
app.config['FREIGHT_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)
|
|
result = inventory_configuration_test.report_test_export({
|
|
'run_no': started['run_no'], 'status': 'empty',
|
|
})
|
|
|
|
# 关键断言:没有已发布方案就无法验证空报表的格式,仍必须阻断。
|
|
assert result['status'] == 'failed'
|
|
assert '尚未绑定已发布库存解析方案' in result['error_message']
|
|
|
|
|
|
def test_configuration_test_automatically_verifies_compatible_bound_profile(app, tmp_path):
|
|
"""当前绑定方案的核心栏位仍在时,历史无关列缺失也必须直接成为验证证据。"""
|
|
app.config['FREIGHT_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()
|
|
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
seed_file = tmp_path / 'bound-profile-seed.xlsx'; _workbook(seed_file)
|
|
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BOUND_PROFILE_VERIFY')
|
|
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
|
|
|
|
verified = _complete_test_run(source, tmp_path)
|
|
# 关键断言:当前绑定方案无需再出现在候选确认列表,测试直接写入启用所需的确认事实。
|
|
assert verified['stage'] == 'current_profile_verified'
|
|
assert verified['result']['current_profile_verified'] is True
|
|
assert verified['result']['confirmed_profile_id'] == profile['id']
|
|
|
|
|
|
def test_verified_current_profile_automatically_enables_ready_source(app, tmp_path):
|
|
"""当前解析验证通过且必要条件齐全时,站点无需人工确认即可自动启用。"""
|
|
app.config['FREIGHT_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()
|
|
seeded = _complete_test_run(source, tmp_path)
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_PROFILE')
|
|
template = _published_template(code='AUTO_ENABLE_TEMPLATE')
|
|
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
|
shipping_inventory_service.save_source({
|
|
**current, 'parsing_profile_id': profile['id'], 'excel_template_id': template.id,
|
|
}, actor_id=None, source_id=source['id'])
|
|
|
|
verified = _complete_test_run(source, tmp_path)
|
|
source_model = db.session.get(ShippingInventorySource, source['id'])
|
|
# 关键断言:测试证据与完整门禁在同一事务提交,避免页面看到已验证但仍需手动启用。
|
|
assert verified['stage'] == 'current_profile_verified'
|
|
assert source_model.enabled is True
|
|
|
|
|
|
def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path):
|
|
"""解析测试通过不绕过发货模板门禁,条件不完整的站点必须保持停用。"""
|
|
app.config['FREIGHT_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()
|
|
seeded = _complete_test_run(source, tmp_path)
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_BLOCKED')
|
|
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
|
shipping_inventory_service.save_source({
|
|
**current, 'parsing_profile_id': profile['id'], 'excel_template_id': None,
|
|
}, actor_id=None, source_id=source['id'])
|
|
|
|
_complete_test_run(source, tmp_path)
|
|
source_model = db.session.get(ShippingInventorySource, source['id'])
|
|
# 关键断言:自动启用始终复用正式门禁,缺少模板不会被测试成功放行。
|
|
assert source_model.enabled is False
|
|
assert shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
|
|
|
|
|
|
def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path):
|
|
"""固定仓查询成功但无库存时,也能在完整门禁下自动启用站点。"""
|
|
app.config['FREIGHT_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()
|
|
seeded = _complete_test_run(source, tmp_path)
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_EMPTY')
|
|
template = _published_template(code='AUTO_ENABLE_EMPTY_TEMPLATE')
|
|
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
|
shipping_inventory_service.save_source({
|
|
**current, 'parsing_profile_id': profile['id'], 'excel_template_id': template.id,
|
|
}, actor_id=None, source_id=source['id'])
|
|
|
|
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
completed = inventory_configuration_test.report_test_export({'run_no': started['run_no'], 'status': 'empty'})
|
|
source_model = db.session.get(ShippingInventorySource, source['id'])
|
|
# 关键断言:无库存是成功查询事实,完整门禁下不再要求人工启用。
|
|
assert completed['status'] == 'completed_empty'
|
|
assert source_model.enabled is True
|
|
|
|
|
|
def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path):
|
|
"""同连接站点一次投递,混合成功、空库存及失败后仍独立汇总为部分失败。"""
|
|
app.config['FREIGHT_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',
|
|
) as write_trigger:
|
|
first = _source('BATCH_SOURCE_A', 'BATCH_LOGIN_A')
|
|
second = _source('BATCH_SOURCE_B', 'BATCH_LOGIN_B')
|
|
third = _source('BATCH_SOURCE_C', 'BATCH_LOGIN_C')
|
|
second_model = db.session.get(ShippingInventorySource, second['id'])
|
|
second_model.rpa_profile_id = first['rpa_profile_id']
|
|
second_model.config_version += 1
|
|
db.session.commit()
|
|
# 用首站既有测试证据创建发布方案,再作为三站批量验证的受控解析定义。
|
|
seed = inventory_configuration_test.start_test_export(first['id'], actor_id=None)
|
|
seed_file = tmp_path / 'batch-seed.xlsx'; _workbook(seed_file)
|
|
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BATCH_PROFILE')
|
|
shipping_inventory_service.bind_source_parsing_profile(
|
|
[first['id'], second['id'], third['id']], profile['id'], actor_id=None, reason='批量验证测试', operation='bulk',
|
|
)
|
|
|
|
write_trigger.reset_mock()
|
|
batch = inventory_configuration_test.start_batch_test_export([first['id'], second['id'], third['id']], actor_id=None)
|
|
# 关键断言:两个相同 Profile 的站点合并为一个 trigger,第三站独立触发。
|
|
assert write_trigger.call_count == 2
|
|
assert batch['total_count'] == 3
|
|
runs = {run['inventory_source_id']: run for run in batch['runs']}
|
|
result_file = tmp_path / 'batch-success.xlsx'; _workbook(result_file)
|
|
reported = inventory_configuration_test.report_batch_test_exports({
|
|
'validation_batch_id': batch['id'], 'results': [
|
|
{'validation_run_no': runs[first['id']]['run_no'], 'status': 'success', 'file_path': str(result_file)},
|
|
{'validation_run_no': runs[second['id']]['run_no'], 'status': 'skipped', 'skip_reason': 'no_inventory_data'},
|
|
{'validation_run_no': runs[third['id']]['run_no'], 'status': 'failed', 'error_message': 'login failed'},
|
|
],
|
|
})
|
|
# 关键断言:失败站点不影响其他站点,批次仅汇总为部分失败。
|
|
assert reported['status'] == 'partial_failed'
|
|
assert (reported['success_count'], reported['empty_count'], reported['failed_count']) == (1, 1, 1)
|
|
assert ShippingInventoryValidationBatch.query.get(batch['id']).status == 'partial_failed'
|
|
|
|
|
|
def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
|
"""批次重试只新建失败站点运行,成功和空库存结果不会被重复导出。"""
|
|
app.config['FREIGHT_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('RETRY_SOURCE', 'RETRY_LOGIN')
|
|
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
seed_file = tmp_path / 'retry-seed.xlsx'; _workbook(seed_file)
|
|
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RETRY_PROFILE')
|
|
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='重试测试', operation='bulk')
|
|
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
|
run = batch['runs'][0]
|
|
inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
|
{'validation_run_no': run['run_no'], 'status': 'failed', 'error_message': 'temporary failure'},
|
|
]})
|
|
retried = inventory_configuration_test.retry_failed_validation_batch(batch['id'], actor_id=None)
|
|
assert retried['retry_of_batch_id'] == batch['id']
|
|
assert retried['total_count'] == 1
|
|
|
|
|
|
def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app, tmp_path):
|
|
"""配置变更后的旧批次回调必须失效,未知运行号不能污染同批次状态。"""
|
|
app.config['FREIGHT_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('STALE_BATCH_SOURCE', 'STALE_BATCH_LOGIN')
|
|
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
seed_file = tmp_path / 'stale-batch-seed.xlsx'; _workbook(seed_file)
|
|
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='STALE_BATCH_PROFILE')
|
|
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='过期回调测试', operation='bulk')
|
|
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
|
run = batch['runs'][0]
|
|
source_model = db.session.get(ShippingInventorySource, source['id'])
|
|
source_model.config_version += 1
|
|
db.session.commit()
|
|
result_file = tmp_path / 'stale-batch-result.xlsx'; _workbook(result_file)
|
|
reported = inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
|
{'validation_run_no': 'UNKNOWN-RUN', 'status': 'success', 'file_path': str(result_file)},
|
|
{'validation_run_no': run['run_no'], 'status': 'success', 'file_path': str(result_file)},
|
|
]})
|
|
# 关键断言:旧配置只标记自身 stale,未知运行号不会写入或影响批次统计。
|
|
assert reported['ignored_count'] == 1
|
|
assert reported['stale_count'] == 1
|
|
assert reported['runs'][0]['result']['stale_configuration'] is True
|
|
|
|
|
|
def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
|
|
"""页面刷新只能恢复仍在执行的批次,已结束批次不会反复占用进度面板。"""
|
|
app.config['FREIGHT_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('RESTORE_BATCH_SOURCE', 'RESTORE_BATCH_LOGIN')
|
|
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
seed_file = tmp_path / 'restore-batch-seed.xlsx'; _workbook(seed_file)
|
|
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RESTORE_BATCH_PROFILE')
|
|
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
|
|
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
|
# 关键断言:刷新期间读取服务端 active batch,会返回待 Worker 处理的真实运行。
|
|
assert inventory_configuration_test.get_latest_active_validation_batch()['id'] == batch['id']
|
|
inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
|
{'validation_run_no': batch['runs'][0]['run_no'], 'status': 'empty'},
|
|
]})
|
|
# 关键断言:结束后不再恢复,避免管理端反复弹出旧批次。
|
|
assert inventory_configuration_test.get_latest_active_validation_batch() is None
|
|
|
|
|
|
def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path):
|
|
"""Worker 领取回调只更新本批次当前运行,终态运行不得被重新打开。"""
|
|
app.config['FREIGHT_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('PROGRESS_BATCH_SOURCE', 'PROGRESS_BATCH_LOGIN')
|
|
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
|
seed_file = tmp_path / 'progress-batch-seed.xlsx'; _workbook(seed_file)
|
|
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
|
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='PROGRESS_BATCH_PROFILE')
|
|
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
|
|
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
|
run = batch['runs'][0]
|
|
|
|
progressed = inventory_configuration_test.report_batch_test_progress({
|
|
'validation_batch_id': batch['id'], 'validation_run_no': run['run_no'], 'stage': 'rpa_exporting',
|
|
})
|
|
# 关键断言:页面可区分尚未领取与 Worker 已实际执行,批次仍等待最终结果。
|
|
assert (progressed['status'], progressed['stage']) == ('processing', 'rpa_exporting')
|
|
assert inventory_configuration_test.get_validation_batch(batch['id'])['status'] == 'running'
|
|
|
|
inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
|
{'validation_run_no': run['run_no'], 'status': 'empty'},
|
|
]})
|
|
unchanged = inventory_configuration_test.report_batch_test_progress({
|
|
'validation_batch_id': batch['id'], 'validation_run_no': run['run_no'], 'stage': 'rpa_exporting',
|
|
})
|
|
# 关键断言:迟到的 progress 不得覆盖已经确认的空库存终态。
|
|
assert (unchanged['status'], unchanged['stage']) == ('completed_empty', 'empty_data_pending_validation')
|
|
|
|
|
|
def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_path):
|
|
"""重开配置抽屉只能恢复当前版本测试;站点改动后可发起独立新测试而不复用旧运行。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
app.config['FREIGHT_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['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
|
app.config['FREIGHT_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_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
|
|
"""同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。"""
|
|
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
|
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
|
|
with app.app_context(), patch(
|
|
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
|
):
|
|
first = _source('TIMEOUT_QUEUE_A', 'TIMEOUT_QUEUE_LOGIN')
|
|
second = _source('TIMEOUT_QUEUE_B', 'TIMEOUT_QUEUE_LOGIN_B')
|
|
second_model = db.session.get(ShippingInventorySource, second['id'])
|
|
second_model.rpa_profile_id = first['rpa_profile_id']
|
|
second_model.config_version += 1
|
|
db.session.commit()
|
|
seed = _complete_test_run(first, tmp_path)
|
|
profile = _publish_profile_from_analysis(seed['analysis_id'], _published_order_field(), code='TIMEOUT_QUEUE_PROFILE')
|
|
shipping_inventory_service.bind_source_parsing_profile([first['id'], second['id']], profile['id'], actor_id=None, operation='bulk')
|
|
batch = inventory_configuration_test.start_batch_test_export([first['id'], second['id']], actor_id=None)
|
|
queued_run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=second['id']).one()
|
|
queued_run.created_at = datetime.utcnow() - timedelta(seconds=15)
|
|
db.session.commit()
|
|
|
|
recovered = inventory_configuration_test.get_validation_batch(batch['id'])
|
|
# 关键断言:第二站可等待同组第一站完成,20 秒总窗口内不应被单站 10 秒误判。
|
|
assert next(run for run in recovered['runs'] if run['inventory_source_id'] == second['id'])['status'] == 'awaiting_rpa'
|
|
|
|
|
|
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['FREIGHT_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 shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
|
|
|
|
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['FREIGHT_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['FREIGHT_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['FREIGHT_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
|