Files
syops/backend/tests/test_shipping_audit_query_service.py
T
hugo d0fe084999 feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验
- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全
- 引入审计事件的哈希链校验机制,支持数据完整性验证
- 增强订单抽取与审计功能,支持敏感快照的访问控制
- 更新相关模型与服务,确保新功能的完整性与可追溯性
- 完善文档与代码注释,反映新的业务逻辑与审计要求
2026-07-31 08:59:44 +08:00

197 lines
7.8 KiB
Python

"""
backend/tests/test_shipping_audit_query_service.py
用途:验证货代审计查询、白名单 Diff、受控导出与到期清理契约。
依赖:audit_query_service、audit_service、ShippingAuditEvent、进度审计契约。
逻辑:列表/详情/导出必须写访问审计且不泄露快照正文;清理经 Core DELETE 绕过 append-only 守卫。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from app import db
from app.models import ShippingAuditEvent
from app.services.shipping_notice.audit_query_service import (
export_shipping_audit_events,
get_shipping_audit_event,
list_shipping_audit_events,
purge_expired_shipping_audit_events,
)
from app.services.shipping_notice.audit_service import append_shipping_audit_event
def test_list_and_detail_write_access_audit_and_whitelist_diff(app):
"""列表不含快照全文;详情仅返回白名单 Diff,并分别写访问审计。"""
with app.app_context():
event = append_shipping_audit_event(
event_type='order_extraction_run_status_changed',
aggregate_type='order_extraction_run',
aggregate_id='SNER-AUDIT-Q1',
run_no='SNER-AUDIT-Q1',
operation_id='op-audit-q1',
before={'status': 'queued', 'progress_version': 1},
after={'status': 'processing', 'progress_version': 2},
metadata={'target_status': 'processing'},
)
db.session.commit()
listed = list_shipping_audit_events(
admin_user_id=9001,
request_id='req-list-1',
page=1,
page_size=25,
filters={'run_no': 'SNER-AUDIT-Q1'},
)
# 关键断言:列表可发现业务事件,但不回传 before/after 快照。
assert listed['total'] >= 1
summary = next(item for item in listed['items'] if item['id'] == event.id)
assert summary['has_snapshots'] is True
assert 'before_snapshot' not in summary
assert 'diff' not in summary
detail = get_shipping_audit_event(
admin_user_id=9001,
request_id='req-detail-1',
event_id=int(event.id),
)
# 关键断言:Diff 仅覆盖白名单键变化,不夹带订单正文类字段。
assert detail['before_snapshot'] == {'status': 'queued', 'progress_version': 1}
assert detail['after_snapshot'] == {'status': 'processing', 'progress_version': 2}
changed_keys = {row['key'] for row in detail['diff']}
assert changed_keys == {'progress_version', 'status'}
access_events = ShippingAuditEvent.query.filter_by(event_type='audit_access').all()
actions = {row.action for row in access_events}
assert 'list_audit_events' in actions
assert 'get_audit_event' in actions
def test_export_csv_omits_snapshots_and_writes_access_audit(app):
"""CSV 导出仅稳定列,禁止快照全文,并写导出访问审计。"""
with app.app_context():
append_shipping_audit_event(
event_type='candidate_promoted',
aggregate_type='shipping_task',
aggregate_id='ST-1',
run_no='SNER-AUDIT-Q2',
task_no='ST-1',
before={'status': 'candidate'},
after={'status': 'task_created'},
)
db.session.commit()
exported = export_shipping_audit_events(
admin_user_id=9002,
request_id='req-export-1',
filters={'run_no': 'SNER-AUDIT-Q2'},
limit=100,
format='csv',
)
# 关键断言:导出正文不含 snapshot / email_body 等敏感字段名。
content = exported['content']
assert 'event_type' in content
assert 'SNER-AUDIT-Q2' in content
assert 'before_snapshot' not in content
assert 'email_body' not in content
assert exported['exported'] >= 1
access = ShippingAuditEvent.query.filter_by(
event_type='audit_access',
action='export_audit_events',
).first()
assert access is not None
assert access.metadata_json.get('format') == 'csv'
def test_list_filters_workflow_item_context_fields(app):
"""Workflow 相关筛选:conversation / workflow_item / case / owner 精确匹配。"""
with app.app_context():
target = append_shipping_audit_event(
event_type='document_reparse_requested',
aggregate_type='shipping_notice_workflow_item',
aggregate_id='SPWI-FILTER-1',
conversation_id='conv-filter-1',
workflow_id='SWF-FILTER-1',
workflow_item_id='SPWI-FILTER-1',
review_case_no='SRC-FILTER-1',
owner_user_id='8801',
run_no='SNER-FILTER-1',
)
append_shipping_audit_event(
event_type='document_reparse_requested',
aggregate_type='shipping_notice_workflow_item',
aggregate_id='SPWI-FILTER-2',
conversation_id='conv-filter-2',
workflow_id='SWF-FILTER-2',
workflow_item_id='SPWI-FILTER-2',
review_case_no='SRC-FILTER-2',
owner_user_id='8802',
run_no='SNER-FILTER-2',
)
db.session.commit()
listed = list_shipping_audit_events(
admin_user_id=9003,
request_id='req-filter-1',
page=1,
page_size=25,
filters={
'conversation_id': 'conv-filter-1',
'workflow_item_id': 'SPWI-FILTER-1',
'review_case_no': 'SRC-FILTER-1',
'owner_user_id': '8801',
},
)
# 关键断言:四字段联合筛选仅命中目标事件。
assert listed['total'] == 1
assert listed['items'][0]['id'] == int(target.id)
assert listed['items'][0]['workflow_item_id'] == 'SPWI-FILTER-1'
assert listed['items'][0]['workflow_id'] == 'SWF-FILTER-1'
assert listed['items'][0]['owner_user_id'] == '8801'
assert listed['items'][0]['event_hash']
def test_purge_expired_supports_dry_run_and_core_delete(app):
"""到期清理支持 dry_run;正式删除经 Core DELETE 并写清理审计。"""
from sqlalchemy import update
with app.app_context():
expired = append_shipping_audit_event(
event_type='legacy_probe',
aggregate_type='order_extraction_run',
aggregate_id='SNER-EXPIRED',
run_no='SNER-EXPIRED',
)
db.session.commit()
expired_id = int(expired.id)
# 新写入永久保留;用 Core UPDATE 模拟历史遗留到期行(绕过 ORM 不可变守卫)。
db.session.execute(
update(ShippingAuditEvent)
.where(ShippingAuditEvent.id == expired_id)
.values(retention_expires_at=datetime.utcnow() - timedelta(days=1))
)
db.session.commit()
dry = purge_expired_shipping_audit_events(limit=100, dry_run=True)
# 关键断言:演练只扫描不删除。
assert dry['dry_run'] is True
assert dry['scanned'] >= 1
assert dry['deleted'] == 0
assert db.session.get(ShippingAuditEvent, expired_id) is not None
result = purge_expired_shipping_audit_events(limit=100, dry_run=False)
assert result['dry_run'] is False
assert result['deleted'] >= 1
# SQLite 可能复用已删主键;以业务事件类型断言清理结果,不以旧 id 缺失为准。
assert ShippingAuditEvent.query.filter_by(
event_type='legacy_probe',
aggregate_id='SNER-EXPIRED',
).first() is None
purge_audit = ShippingAuditEvent.query.filter_by(
event_type='audit_retention_purged',
).order_by(ShippingAuditEvent.id.desc()).first()
assert purge_audit is not None
assert purge_audit.metadata_json.get('deleted') >= 1