152 lines
8.4 KiB
Python
152 lines
8.4 KiB
Python
"""
|
||
用途:验证发货 Excel 批次 ZIP 的权限、全部有效 Artifact、重名、校验和与 manifest 契约。
|
||
依赖:export_archive、ShippingBatch/Task/ExportArtifact、zipfile。
|
||
逻辑:构造同批次有效、缺失及损坏产物,断言 ZIP 仅包含可信文件并完整列出排除原因。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
from zipfile import ZipFile
|
||
|
||
import pytest
|
||
|
||
from app import db
|
||
from app.core.errors import NotFoundError, ValidationError
|
||
from app.models import (
|
||
ShippingBatch, ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile,
|
||
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingTask, User,
|
||
)
|
||
from app.services.shipping_notice.export_archive import build_export_archive
|
||
from app.core.auth.jwt import issue_local_access_token
|
||
|
||
|
||
def _seed_artifact_dependencies():
|
||
"""创建 Artifact 外键所需的最小发布版本。"""
|
||
template = ShippingExcelTemplate(
|
||
template_code='ZIP', display_name='ZIP', version=1, status='published',
|
||
storage_provider='minio', storage_bucket='test', storage_key='test/zip-template.xlsx',
|
||
original_filename='template.xlsx', file_checksum='t' * 64, definition_json={}, definition_checksum='d' * 64,
|
||
)
|
||
parsing = ShippingInventoryParsingProfile(
|
||
profile_code='ZIP', display_name='ZIP', version=1, status='published', file_format='xlsx', definition_json={},
|
||
)
|
||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||
db.session.add_all([template, parsing, schema]); db.session.flush()
|
||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||
db.session.add(version); db.session.flush()
|
||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
||
db.session.add(extraction); db.session.flush()
|
||
return template, parsing, version, extraction
|
||
|
||
|
||
def _artifact(task, path, dependencies, *, no: str, checksum: str | None = None):
|
||
"""为任务新增 ready Artifact,checksum 默认按文件内容计算。"""
|
||
template, parsing, version, extraction = dependencies
|
||
content = path.read_bytes() if path.is_file() else b''
|
||
item = ShippingExportArtifact(
|
||
artifact_no=no, task_id=task.id, batch_id=task.batch_id, template_id=template.id,
|
||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||
inventory_parsing_profile_id=parsing.id, input_checksum='x' * 64,
|
||
file_path=str(path), file_name='shipment.xlsx', file_checksum=checksum or hashlib.sha256(content).hexdigest(),
|
||
file_size=len(content), status='ready',
|
||
)
|
||
db.session.add(item)
|
||
task.export_file_path = str(path)
|
||
task.export_file_name = 'shipment.xlsx'
|
||
return item
|
||
|
||
|
||
def test_batch_archive_manifest_and_duplicate_names(app, tmp_path):
|
||
"""同一任务多轮有效 Excel 都进入 ZIP,缺失/损坏 Artifact 保留明确审计状态。"""
|
||
with app.app_context():
|
||
user = User(username='zip-owner', email='zip@example.com', role='user', status='approved')
|
||
batch = ShippingBatch(batch_no='SB-ZIP', user_id=None, file_count=4)
|
||
db.session.add_all([user, batch]); db.session.flush(); batch.user_id = user.id
|
||
tasks = [ShippingTask(task_no=f'TASK-{index}', user_id=user.id, batch_id=batch.id, batch_index=index, batch_total=4) for index in range(1, 5)]
|
||
db.session.add_all(tasks); db.session.flush()
|
||
first = tmp_path / 'first.xlsx'; first.write_bytes(b'first')
|
||
first_second_round = tmp_path / 'first-second-round.xlsx'; first_second_round.write_bytes(b'first-second-round')
|
||
second = tmp_path / 'second.xlsx'; second.write_bytes(b'second')
|
||
corrupt = tmp_path / 'corrupt.xlsx'; corrupt.write_bytes(b'changed')
|
||
dependencies = _seed_artifact_dependencies()
|
||
_artifact(tasks[0], first, dependencies, no='EXP-1')
|
||
_artifact(tasks[0], first_second_round, dependencies, no='EXP-1-SECOND')
|
||
_artifact(tasks[1], second, dependencies, no='EXP-2')
|
||
_artifact(tasks[2], tmp_path / 'missing.xlsx', dependencies, no='EXP-3')
|
||
_artifact(tasks[3], corrupt, dependencies, no='EXP-4', checksum='0' * 64)
|
||
db.session.commit()
|
||
|
||
stream, filename, manifest = build_export_archive(user_id=user.id, batch_no=batch.batch_no)
|
||
with ZipFile(stream) as archive:
|
||
names = archive.namelist()
|
||
assert 'shipment.xlsx' in names
|
||
assert 'shipment_TASK-2.xlsx' in names # 同名按任务号消歧,避免覆盖。
|
||
assert 'shipment_TASK-1.xlsx' in names # 同一任务第二轮滚动 Artifact 不得遗漏。
|
||
archived_manifest = json.loads(archive.read('manifest.json'))
|
||
assert filename.startswith('shipping_exports_SB-ZIP_')
|
||
assert archived_manifest['included_count'] == 3
|
||
assert [entry['status'] for entry in manifest['entries']] == [
|
||
'included', 'included', 'included', 'missing_file', 'checksum_mismatch',
|
||
]
|
||
|
||
|
||
def test_archive_rejects_foreign_task_and_invalid_selection(app):
|
||
"""任一越权任务整体拒绝,且 batch_no/task_nos 不能同时或同时不传。"""
|
||
with app.app_context():
|
||
owner = User(username='archive-owner', email='archive-owner@example.com', role='user', status='approved')
|
||
other = User(username='archive-other', email='archive-other@example.com', role='user', status='approved')
|
||
task = ShippingTask(task_no='FOREIGN-TASK', user_id=owner.id)
|
||
db.session.add_all([owner, other]); db.session.flush(); task.user_id = owner.id; db.session.add(task); db.session.commit()
|
||
with pytest.raises(NotFoundError):
|
||
build_export_archive(user_id=other.id, task_nos=[task.task_no])
|
||
with pytest.raises(ValidationError):
|
||
build_export_archive(user_id=owner.id)
|
||
with pytest.raises(ValidationError):
|
||
build_export_archive(user_id=owner.id, batch_no='SB', task_nos=[task.task_no])
|
||
|
||
|
||
def test_archive_excludes_superseded_artifact_after_task_export_is_invalidated(app, tmp_path):
|
||
"""任务纠错必须显式作废旧 Artifact;仅清空旧 Task 指针不能影响滚动履约历史。"""
|
||
with app.app_context():
|
||
user = User(username='archive-reset', email='archive-reset@example.com', role='user', status='approved')
|
||
batch = ShippingBatch(batch_no='SB-RESET', user_id=None, file_count=1)
|
||
db.session.add_all([user, batch]); db.session.flush(); batch.user_id = user.id
|
||
task = ShippingTask(task_no='TASK-RESET', user_id=user.id, batch_id=batch.id, batch_index=1, batch_total=1)
|
||
db.session.add(task); db.session.flush()
|
||
path = tmp_path / 'old.xlsx'; path.write_bytes(b'old')
|
||
_artifact(task, path, _seed_artifact_dependencies(), no='EXP-OLD')
|
||
artifact = ShippingExportArtifact.query.filter_by(artifact_no='EXP-OLD').one()
|
||
artifact.status = 'superseded'
|
||
task.export_file_path = None
|
||
task.export_file_name = None
|
||
db.session.commit()
|
||
|
||
_stream, _filename, manifest = build_export_archive(user_id=user.id, batch_no=batch.batch_no)
|
||
assert manifest['included_count'] == 0
|
||
assert manifest['entries'][0]['status'] == 'missing_artifact'
|
||
|
||
|
||
def test_workspace_archive_api_returns_zip(app, client, tmp_path):
|
||
"""Workspace API 必须以当前用户权限生成 attachment ZIP,而不是暴露服务器文件路径。"""
|
||
with app.app_context():
|
||
user = User(username='archive-api', email='archive-api@example.com', role='user', status='approved')
|
||
db.session.add(user); db.session.flush()
|
||
batch = ShippingBatch(batch_no='SB-API-ZIP', user_id=user.id, file_count=1)
|
||
db.session.add(batch); db.session.flush()
|
||
task = ShippingTask(task_no='TASK-API-ZIP', user_id=user.id, batch_id=batch.id, batch_index=1, batch_total=1)
|
||
db.session.add(task); db.session.flush()
|
||
path = tmp_path / 'api.xlsx'; path.write_bytes(b'api-content')
|
||
_artifact(task, path, _seed_artifact_dependencies(), no='EXP-API')
|
||
db.session.commit()
|
||
token = issue_local_access_token(user)
|
||
|
||
response = client.post(
|
||
'/api/workspace/shipping-exports/archive', json={'batch_no': 'SB-API-ZIP'},
|
||
headers={'Authorization': f'Bearer {token}'},
|
||
)
|
||
assert response.status_code == 200
|
||
assert response.mimetype == 'application/zip'
|
||
assert 'attachment' in response.headers['Content-Disposition']
|