""" backend/tests/test_shipping_notice_intakes.py 用途:验证 FileAsset + ShippingNoticeIntake 创建、消费与幂等回放主路径。 依赖:pytest、conftest app fixture、MinIO/建批路径 mock。 逻辑:覆盖上传≠建单、parsed 才可建单、消费后幂等键可恢复、异常 kwargs 不抛 TypeError。 """ from __future__ import annotations from datetime import datetime from unittest.mock import patch import pytest from werkzeug.datastructures import FileStorage from io import BytesIO from app import db from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError from app.models import FileAsset, ShippingBatch, ShippingNoticeIntake, ShippingTask, User from app.services.file_assets.service import upload_file_asset from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes from app.services.shipping_notice.intake_service import create_shipping_notice_intake @pytest.fixture def shipping_user(app): with app.app_context(): user = User(username='intake-user', email='intake@example.com', password_hash='x') db.session.add(user) db.session.commit() yield user def _make_upload(content: bytes = b'customer order line', filename: str = 'notice.txt') -> FileStorage: return FileStorage(stream=BytesIO(content), filename=filename, content_type='text/plain') def test_upload_file_asset_creates_ready_record(app, shipping_user): with app.app_context(): with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): result = upload_file_asset(user_id=shipping_user.id, upload=_make_upload()) asset = db.session.query(FileAsset).filter_by(asset_no=result['asset_no']).one() assert asset.upload_status == 'ready' assert asset.lifecycle_status == 'temporary' assert asset.content_hash assert 'storage_key' not in result def test_create_intake_queues_parse_job(app, shipping_user): with app.app_context(): with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): asset = upload_file_asset(user_id=shipping_user.id, upload=_make_upload()) with patch('app.services.shipping_notice.intake_service.enqueue', return_value=101) as enqueue_mock: intake_data = create_shipping_notice_intake( user_id=shipping_user.id, asset_no=asset['asset_no'], conversation_id='conv-intake-1', ) assert intake_data['parse_status'] == 'queued' enqueue_mock.assert_called_once() intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_data['intake_no']).one() assert intake.parse_job_id == 101 def test_error_classes_accept_custom_code_kwargs(app): """业务异常支持 code= 关键字,避免新分支抛 TypeError → 500。""" with app.app_context(): err = NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在') assert err.code == 'FILE_ASSET.NOT_FOUND' err2 = ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问') assert err2.code == 'FILE_ASSET.FORBIDDEN' err3 = ValidationError(code='FILE_ASSET.EXPIRED', message='已过期') assert err3.code == 'FILE_ASSET.EXPIRED' def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_value: str = 'abc123'): asset = FileAsset( asset_no=f'FA-{intake_no}', owner_user_id=user_id, original_filename='notice.txt', storage_provider='minio', storage_bucket='hxops-file-assets', storage_key=f'temporary/{user_id}/test/{intake_no}.txt', content_hash=hash_value, file_size=12, mime_type='text/plain', upload_status='ready', lifecycle_status='temporary', reference_count=0, ) db.session.add(asset) db.session.flush() intake = ShippingNoticeIntake( intake_no=intake_no, asset_id=asset.id, user_id=user_id, purpose='shipping_notice', parse_status='parsed', parser_version='v1', extracted_text='SKU001 qty 10', ) db.session.add(intake) db.session.commit() return asset, intake def test_create_batch_from_intakes_marks_consumed_and_links_task(app, shipping_user, monkeypatch): with app.app_context(): asset, intake = _seed_parsed_intake(shipping_user.id) def _fake_create_batch_from_notice_items(**kwargs): notice_items = kwargs['notice_items'] batch = ShippingBatch( batch_no='SB-TEST-0001', user_id=shipping_user.id, file_count=1, create_idempotency_key=kwargs.get('create_idempotency_key'), ) db.session.add(batch) db.session.flush() item = notice_items[0] task = ShippingTask( task_no='SN-TEST-0001', batch_id=batch.id, user_id=shipping_user.id, source_type='manual', source_content_hash=item.get('source_content_hash'), source_asset_id=item.get('source_asset_id'), source_intake_id=item.get('source_intake_id'), raw_content=item.get('raw_text'), process_status='created', ) db.session.add(task) db.session.commit() return { 'status': 'ok', 'batch_no': batch.batch_no, 'data': { 'batch': {'batch_no': batch.batch_no, 'id': batch.id}, 'tasks': [{'task_id': task.task_no}], }, } monkeypatch.setattr( 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', _fake_create_batch_from_notice_items, ) result = create_shipping_batch_from_intakes( user_id=shipping_user.id, conversation_id='conv-intake-1', intake_nos=[intake.intake_no], create_idempotency_key='idem-1', ) assert result['batch_no'] == 'SB-TEST-0001' refreshed = db.session.get(ShippingNoticeIntake, intake.id) assert refreshed.parse_status == 'consumed' assert refreshed.consumed_batch_id is not None assert refreshed.consumed_task_id is not None task = db.session.query(ShippingTask).filter_by(task_no='SN-TEST-0001').one() assert task.source_asset_id == asset.id assert task.source_intake_id == intake.id asset_ref = db.session.get(FileAsset, asset.id) assert asset_ref.lifecycle_status == 'referenced' assert int(asset_ref.reference_count or 0) >= 1 def test_create_batch_from_intakes_idempotent_replay_after_consumed(app, shipping_user, monkeypatch): with app.app_context(): asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-REPLAY') batch = ShippingBatch( batch_no='SB-TEST-REPLAY', user_id=shipping_user.id, file_count=1, create_idempotency_key='idem-replay', ) db.session.add(batch) db.session.flush() task = ShippingTask( task_no='SN-TEST-REPLAY', batch_id=batch.id, user_id=shipping_user.id, source_type='manual', source_asset_id=asset.id, source_intake_id=intake.id, process_status='created', ) intake.parse_status = 'consumed' intake.consumed_at = datetime.utcnow() intake.consumed_batch_id = batch.id intake.consumed_task_id = None db.session.add(task) db.session.commit() intake.consumed_task_id = task.id db.session.commit() called = {'count': 0} def _should_not_create(**kwargs): called['count'] += 1 raise AssertionError('idempotent replay must not create again') monkeypatch.setattr( 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', _should_not_create, ) result = create_shipping_batch_from_intakes( user_id=shipping_user.id, conversation_id='conv-replay', intake_nos=['SNI-TEST-REPLAY'], create_idempotency_key='idem-replay', ) assert result.get('idempotent_replay') is True assert result['batch_no'] == 'SB-TEST-REPLAY' assert called['count'] == 0 def test_queued_intake_cannot_create_batch(app, shipping_user): with app.app_context(): _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-QUEUED') intake.parse_status = 'queued' db.session.commit() with pytest.raises(Exception) as excinfo: create_shipping_batch_from_intakes( user_id=shipping_user.id, conversation_id=None, intake_nos=[intake.intake_no], create_idempotency_key='idem-queued', ) assert 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' in str(getattr(excinfo.value, 'code', '')) or True from app.core.errors import ConflictError assert isinstance(excinfo.value, ConflictError) assert excinfo.value.code == 'SHIPPING_NOTICE.INTAKE_PARSE_PENDING' def test_create_batch_failure_rolls_back_preconsume(app, shipping_user, monkeypatch): """建批业务异常后预占 consumed 须回滚,否则用户无法重试。""" with app.app_context(): _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-TEST-ROLLBACK') def _raise_conflict(**kwargs): raise ConflictError( '精确重复通知', code='SHIPPING.EXACT_DUPLICATE', ) monkeypatch.setattr( 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', _raise_conflict, ) with pytest.raises(ConflictError) as excinfo: create_shipping_batch_from_intakes( user_id=shipping_user.id, conversation_id='conv-rollback', intake_nos=[intake.intake_no], create_idempotency_key='idem-rollback', ) assert excinfo.value.code == 'SHIPPING.EXACT_DUPLICATE' refreshed = db.session.get(ShippingNoticeIntake, intake.id) assert refreshed.parse_status == 'parsed' assert refreshed.consumed_at is None assert refreshed.consumed_batch_id is None def test_create_batch_dedupes_same_content_hash_intakes(app, shipping_user, monkeypatch): """相同 content_hash 的多个 intake:只建一个任务,附属 intake 也关联到同一任务。""" with app.app_context(): asset1, intake1 = _seed_parsed_intake( shipping_user.id, intake_no='SNI-DEDUP-1', hash_value='same-hash-xx' ) asset2, intake2 = _seed_parsed_intake( shipping_user.id, intake_no='SNI-DEDUP-2', hash_value='same-hash-xx' ) def _fake_create(**kwargs): notice_items = kwargs['notice_items'] assert len(notice_items) == 1 batch = ShippingBatch( batch_no='SB-DEDUP-1', user_id=shipping_user.id, file_count=1, create_idempotency_key=kwargs.get('create_idempotency_key'), ) db.session.add(batch) db.session.flush() item = notice_items[0] task = ShippingTask( task_no='SN-DEDUP-1', batch_id=batch.id, user_id=shipping_user.id, source_type='manual', source_content_hash=item.get('source_content_hash'), source_asset_id=item.get('source_asset_id'), source_intake_id=item.get('source_intake_id'), raw_content=item.get('raw_text'), process_status='created', ) db.session.add(task) db.session.commit() return { 'status': 'ok', 'batch_no': batch.batch_no, 'data': { 'batch': {'batch_no': batch.batch_no, 'id': batch.id}, 'tasks': [{'task_id': task.task_no}], }, } monkeypatch.setattr( 'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items', _fake_create, ) result = create_shipping_batch_from_intakes( user_id=shipping_user.id, conversation_id='conv-dedup', intake_nos=[intake1.intake_no, intake2.intake_no], create_idempotency_key='idem-dedup', ) assert result['batch_no'] == 'SB-DEDUP-1' r1 = db.session.get(ShippingNoticeIntake, intake1.id) r2 = db.session.get(ShippingNoticeIntake, intake2.id) assert r1.parse_status == 'consumed' assert r2.parse_status == 'consumed' assert r1.consumed_batch_id == r2.consumed_batch_id assert r1.consumed_task_id == r2.consumed_task_id assert r1.consumed_task_id is not None # 同键重放不应因「请求 2 个 intake / 任务只绑 1 个」而冲突 replay = create_shipping_batch_from_intakes( user_id=shipping_user.id, conversation_id='conv-dedup', intake_nos=[intake1.intake_no, intake2.intake_no], create_idempotency_key='idem-dedup', ) assert replay.get('idempotent_replay') is True def test_parse_worker_skips_cancelled_intake(app, shipping_user): """已取消的 intake 不应被 worker 重新写回 parsed。""" with app.app_context(): import logging from app.jobs.context import JobContext from app.jobs.handlers.shipping_notice_parse import run_shipping_notice_parse _, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-WORKER') intake.parse_status = 'cancelled' db.session.commit() ctx = JobContext(config={}, logger=logging.getLogger('test.shipping_notice_parse')) run_shipping_notice_parse(ctx, {'intake_no': intake.intake_no}) refreshed = db.session.get(ShippingNoticeIntake, intake.id) assert refreshed.parse_status == 'cancelled' def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeypatch): """抽取期间他事务取消后,即使 Session 缓存仍为 parsing,也不得覆盖为 parsed。""" with app.app_context(): from sqlalchemy import text from app.services.shipping_notice.intake_parse_workflow import run_intake_parse from app.services.shipping_notice.notice_upload import NoticeIntakeResult asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-CANCEL-RACE') intake.parse_status = 'parsing' db.session.commit() local = db.session.get(ShippingNoticeIntake, intake.id) assert local.parse_status == 'parsing' # 他连接直接改库,模拟 cancel_intake 已提交;当前 Session 身份映射仍缓存 parsing with db.engine.begin() as conn: conn.execute( text( "UPDATE shipping_notice_intakes " "SET parse_status = 'cancelled' WHERE id = :id" ), {'id': intake.id}, ) assert local.parse_status == 'parsing' monkeypatch.setattr( 'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset', lambda _asset: NoticeIntakeResult( filename='notice.txt', source_type='manual', source_file_type='text/plain', text='SKU001 qty 10', warnings=[], meta={}, content_hash=asset.content_hash, file_size=12, status='accepted', saved_path=None, ), ) result = run_intake_parse(local, asset) assert result['status'] == 'skipped' db.session.expire_all() refreshed = db.session.get(ShippingNoticeIntake, intake.id) assert refreshed.parse_status == 'cancelled' def test_ensure_default_file_asset_cleanup_schedule(app, shipping_user): """有用户时可幂等补建默认 TTL 清理排程。""" with app.app_context(): from app.models import ScheduleTask from app.services.file_assets.cleanup_schedule import ( DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO, ensure_default_file_asset_cleanup_schedule, ) first = ensure_default_file_asset_cleanup_schedule() assert first is not None assert first.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO assert first.platform_api_path == 'file-asset-cleanup' assert first.enabled is True second = ensure_default_file_asset_cleanup_schedule() assert second is not None assert second.id == first.id count = ( db.session.query(ScheduleTask) .filter(ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO) .count() ) assert count == 1 def test_user_insert_hook_seeds_cleanup_schedule(app): """首个用户 commit 后应立即补建清理排程,无需重启。""" with app.app_context(): from app.models import ScheduleTask, User from app.services.file_assets.cleanup_schedule import ( DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO, register_file_asset_cleanup_schedule_hooks, ) register_file_asset_cleanup_schedule_hooks() # 确保环境干净 db.session.query(ScheduleTask).filter( ScheduleTask.schedule_no == DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO ).delete() db.session.commit() user = User(username='seed-hook-user', email='seed-hook@example.com', password_hash='x') db.session.add(user) db.session.commit() task = ( db.session.query(ScheduleTask) .filter_by(schedule_no=DEFAULT_FILE_ASSET_CLEANUP_SCHEDULE_NO) .first() ) assert task is not None assert task.platform_api_path == 'file-asset-cleanup' assert task.enabled is True assert task.next_run_at is not None # Cron 整点:分钟应为 0(允许时区转换后的 UTC 分钟非 0,但应等于 compute_next_run_at 结果) from app.services.schedule.timezone_util import compute_next_run_at expected = compute_next_run_at('0 * * * *', timezone_name='Asia/Shanghai') assert expected is not None # 钩子执行时刻与断言时刻可能跨整点边界,允许在同一小时窗口内 assert abs((task.next_run_at - expected).total_seconds()) < 3700