- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。 - 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。 - 更新 ORM 模型,增加出站报表相关的持久化模型。 - 统一命名规范,确保在手、入站与出站的概念一致性。
297 lines
11 KiB
Python
297 lines
11 KiB
Python
"""
|
|
backend/tests/test_freight_rpa_inbound_archive.py
|
|
|
|
用途:收料 RPA 原始收料 ZIP 归档、summary 可见性与 admin API 路由单测。
|
|
依赖:freight_rpa_inbound_archive、api/schedule/runs、freight_rpa_inbound_finalize。
|
|
逻辑:finalize 预生成 ZIP;下载 send_file 归档路径;包内条目为序号_source_code。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import zipfile
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
import pytest
|
|
|
|
from app import db
|
|
from app.core.auth.jwt import issue_local_access_token
|
|
from app.core.errors import NotFoundError
|
|
from app.models import (
|
|
ScheduleRun,
|
|
ScheduleTask,
|
|
FreightRpaSource,
|
|
FreightRpaInboundReportFile,
|
|
FreightRpaInboundUnitRun,
|
|
User,
|
|
)
|
|
from app.services.schedule.freight_rpa_inbound_archive import (
|
|
get_inbound_archive_dir,
|
|
persist_inbound_rpa_raw_zip_archive,
|
|
inbound_raw_zip_available_from_summary,
|
|
inbound_raw_zip_download_name,
|
|
inbound_rpa_attachment_stem,
|
|
resolve_inbound_raw_zip_download,
|
|
_build_zip_entry_name,
|
|
)
|
|
from tests.conftest import parse_api_error
|
|
|
|
|
|
@pytest.fixture
|
|
def admin_jwt_headers(app):
|
|
"""创建 admin 用户并签发 Bearer JWT。"""
|
|
with app.app_context():
|
|
user = db.session.query(User).filter_by(username='admin').first()
|
|
if not user:
|
|
user = User(
|
|
username='admin',
|
|
email='admin@example.com',
|
|
role='admin',
|
|
status='active',
|
|
)
|
|
user.set_password('admin')
|
|
db.session.add(user)
|
|
db.session.commit()
|
|
token = issue_local_access_token(user)
|
|
return {
|
|
'Authorization': f'Bearer {token}',
|
|
'Content-Type': 'application/json',
|
|
}
|
|
|
|
|
|
def _make_receipt_run_with_file(
|
|
*,
|
|
schedule_no: str,
|
|
run_no: str,
|
|
callback_id: str,
|
|
source_code: str = 'DSV360_AWSDU',
|
|
original_filename: str = 'receipt.xlsx',
|
|
) -> tuple[ScheduleRun, FreightRpaInboundReportFile]:
|
|
"""构造收料排程 run + 成功单元 + 归档文件。"""
|
|
source = FreightRpaSource.query.filter_by(source_code=source_code).one()
|
|
owner = db.session.query(User).filter_by(username='admin').first()
|
|
if owner is None:
|
|
owner = User(username=f'owner-{schedule_no}', email=f'{schedule_no}@example.com', role='admin', status='active')
|
|
owner.set_password('admin')
|
|
db.session.add(owner)
|
|
db.session.flush()
|
|
task = ScheduleTask(
|
|
schedule_no=schedule_no,
|
|
name=f'Receipt archive {schedule_no}',
|
|
schedule_type='platform_job',
|
|
platform_api_path='freight-rpa-inbound',
|
|
owner_user_id=owner.id,
|
|
cron_expr='0 8 * * *',
|
|
schedule_timezone='Asia/Shanghai',
|
|
)
|
|
db.session.add(task)
|
|
db.session.flush()
|
|
run = ScheduleRun(
|
|
run_no=run_no,
|
|
schedule_task_id=task.id,
|
|
trigger_type='manual',
|
|
status='success',
|
|
total_count=1,
|
|
success_count=1,
|
|
failed_count=0,
|
|
skipped_count=0,
|
|
)
|
|
db.session.add(run)
|
|
db.session.flush()
|
|
unit = FreightRpaInboundUnitRun(
|
|
schedule_run_id=run.id,
|
|
source_id=source.id,
|
|
source_code=source.source_code,
|
|
connector_type='dbs',
|
|
warehouse_id=None,
|
|
callback_id=callback_id,
|
|
status='success',
|
|
config_snapshot_json={},
|
|
)
|
|
db.session.add(unit)
|
|
db.session.flush()
|
|
report_file = FreightRpaInboundReportFile(
|
|
unit_run_id=unit.id,
|
|
storage_provider='minio',
|
|
storage_bucket='test',
|
|
storage_key=f'{callback_id}.xlsx',
|
|
original_filename=original_filename,
|
|
file_size=12,
|
|
sha256='d' * 64,
|
|
)
|
|
db.session.add(report_file)
|
|
db.session.commit()
|
|
return run, report_file
|
|
|
|
|
|
def test_inbound_raw_zip_available_from_summary_reads_persisted_flag():
|
|
"""列表可见性应只依赖 summary.raw_inbound_zip_available。"""
|
|
assert inbound_raw_zip_available_from_summary({'raw_inbound_zip_available': True}) is True
|
|
assert inbound_raw_zip_available_from_summary({'raw_inbound_zip_available': False}) is False
|
|
assert inbound_raw_zip_available_from_summary(None) is False
|
|
|
|
|
|
def test_get_inbound_archive_dir_falls_back_when_config_none(app, tmp_path, monkeypatch):
|
|
"""
|
|
Config 缺项时 Flask config 可能为 None;不得 Path(None) 导致 finalize ZIP 全空。
|
|
|
|
断言:显式 None 时回落到 Config 默认路径并可创建目录。
|
|
"""
|
|
from app.core.config.settings import Config
|
|
|
|
monkeypatch.setattr(
|
|
Config,
|
|
'FREIGHT_RPA_INBOUND_ARCHIVE_DIR',
|
|
str(tmp_path / 'receipt_archives_fallback'),
|
|
)
|
|
with app.app_context():
|
|
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = None
|
|
archive_dir = Path(get_inbound_archive_dir())
|
|
assert archive_dir.is_dir()
|
|
assert archive_dir == (tmp_path / 'receipt_archives_fallback').resolve()
|
|
|
|
|
|
def test_config_exposes_freight_rpa_receipt_archive_dir(app):
|
|
"""Flask Config 必须声明收料归档目录,否则 env 不会进 app.config。"""
|
|
with app.app_context():
|
|
value = app.config.get('FREIGHT_RPA_INBOUND_ARCHIVE_DIR')
|
|
assert value is not None
|
|
assert str(value).strip() != ''
|
|
|
|
|
|
def test_serialize_run_reads_inbound_raw_zip_available_from_summary(app):
|
|
"""serialize_run 应暴露 inbound_raw_zip_available 供管理端深链/按钮。"""
|
|
from app.services.schedule.query_service import serialize_run
|
|
|
|
with app.app_context():
|
|
user = User(username='arch_receipt_ser', email='arch_receipt_ser@example.com')
|
|
db.session.add(user)
|
|
db.session.flush()
|
|
task = ScheduleTask(
|
|
schedule_no='ARCH-RCP-SER',
|
|
name='Receipt archive serialize',
|
|
schedule_type='platform_job',
|
|
platform_api_path='freight-rpa-inbound',
|
|
owner_user_id=user.id,
|
|
cron_expr='0 8 * * *',
|
|
)
|
|
db.session.add(task)
|
|
db.session.flush()
|
|
run = ScheduleRun(
|
|
run_no='RUN-RCP-SER',
|
|
schedule_task_id=task.id,
|
|
status='success',
|
|
response_summary_json={'raw_inbound_zip_available': True},
|
|
)
|
|
db.session.add(run)
|
|
db.session.commit()
|
|
payload = serialize_run(run)
|
|
assert payload['inbound_raw_zip_available'] is True
|
|
assert payload['inventory_raw_zip_available'] is False
|
|
|
|
|
|
def test_build_zip_entry_name_prefers_source_code():
|
|
"""ZIP 条目名必须优先 source_code,序号三位补零。"""
|
|
assert _build_zip_entry_name(
|
|
index=1,
|
|
source_code='DSV360_AWSBI',
|
|
warehouse_id='BYAWSCM401',
|
|
original_suffix='.xlsx',
|
|
) == '001_DSV360_AWSBI.xlsx'
|
|
|
|
|
|
def test_persist_inbound_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path, monkeypatch):
|
|
"""finalize 预生成应落盘 ZIP(含 manifest)并返回 summary 字段。"""
|
|
archive_dir = tmp_path / 'receipt_archives'
|
|
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(archive_dir)
|
|
monkeypatch.setattr(
|
|
'app.services.schedule.freight_rpa_inbound_archive.file_asset_storage.get_bytes',
|
|
lambda _key: b'fake-receipt-xlsx',
|
|
)
|
|
|
|
with app.app_context():
|
|
run, report_file = _make_receipt_run_with_file(
|
|
schedule_no='SCH-RCP-ARCH-1',
|
|
run_no='RUNRCPARCH1',
|
|
callback_id='receipt-arch-1',
|
|
original_filename='receipt_RUN_DSV360_AWSDU_NA.xlsx',
|
|
)
|
|
summary = persist_inbound_rpa_raw_zip_archive(run)
|
|
|
|
# [断言意图] summary 标记可用且路径落在配置归档目录。
|
|
assert summary['raw_inbound_zip_available'] is True
|
|
assert summary['raw_inbound_file_count'] == 1
|
|
assert summary['raw_inbound_file_ids'] == [report_file.id]
|
|
zip_path = Path(summary['raw_inbound_zip_path'])
|
|
assert zip_path.is_file()
|
|
assert zip_path.parent.resolve() == archive_dir.resolve()
|
|
|
|
with zipfile.ZipFile(zip_path, 'r') as archive:
|
|
names = archive.namelist()
|
|
assert 'manifest.json' in names
|
|
assert '001_DSV360_AWSDU.xlsx' in names
|
|
manifest = json.loads(archive.read('manifest.json').decode('utf-8'))
|
|
assert manifest['run_no'] == run.run_no
|
|
assert manifest['files'][0]['source_code'] == 'DSV360_AWSDU'
|
|
assert manifest['files'][0]['file_id'] == report_file.id
|
|
|
|
|
|
def test_resolve_inbound_raw_zip_download_rejects_missing_summary(app, tmp_path):
|
|
"""summary 未标记可用时应 404。"""
|
|
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt_archives')
|
|
with app.app_context():
|
|
run, _ = _make_receipt_run_with_file(
|
|
schedule_no='SCH-RCP-ARCH-MISS',
|
|
run_no='RUNRCPARCHMISS',
|
|
callback_id='receipt-arch-miss',
|
|
)
|
|
run.response_summary_json = {'raw_inbound_zip_available': False}
|
|
db.session.commit()
|
|
with pytest.raises(NotFoundError):
|
|
resolve_inbound_raw_zip_download(run)
|
|
|
|
|
|
def test_receipt_attachment_stem_uses_local_timezone(app):
|
|
"""展示名前缀为入站RPA-日期-时刻(业务时区)。"""
|
|
with app.app_context():
|
|
run, _ = _make_receipt_run_with_file(
|
|
schedule_no='SCH-RCP-STEM',
|
|
run_no='RUN202609281530001234',
|
|
callback_id='receipt-stem',
|
|
)
|
|
stem = inbound_rpa_attachment_stem(run)
|
|
assert stem.startswith('入站RPA-')
|
|
assert inbound_raw_zip_download_name(run) == f'{stem}-入站.zip'
|
|
|
|
|
|
def test_admin_can_download_inbound_raw_zip(app, client, admin_jwt_headers, tmp_path, monkeypatch):
|
|
"""管理端 inbound-raw-zip 应返回 ZIP 与展示名。"""
|
|
archive_dir = tmp_path / 'receipt_archives'
|
|
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(archive_dir)
|
|
monkeypatch.setattr(
|
|
'app.services.schedule.freight_rpa_inbound_archive.file_asset_storage.get_bytes',
|
|
lambda _key: b'fake-receipt-xlsx',
|
|
)
|
|
|
|
with app.app_context():
|
|
run, _ = _make_receipt_run_with_file(
|
|
schedule_no='SCH-RCP-DL',
|
|
run_no='RUNRCPDL1',
|
|
callback_id='receipt-dl-1',
|
|
)
|
|
summary = persist_inbound_rpa_raw_zip_archive(run)
|
|
run.response_summary_json = summary
|
|
db.session.commit()
|
|
run_id = run.id
|
|
expected_name = inbound_raw_zip_download_name(run)
|
|
|
|
response = client.get(
|
|
f'/api/admin/schedule-runs/{run_id}/inbound-raw-zip',
|
|
headers=admin_jwt_headers,
|
|
)
|
|
assert response.status_code == 200
|
|
assert response.mimetype == 'application/zip'
|
|
disposition = response.headers.get('Content-Disposition') or ''
|
|
assert expected_name in disposition or quote(expected_name) in disposition
|