""" backend/tests/test_shipping_document_layout_mineru.py 用途:验证 MinerU 客户端资源门禁、字符串 JSON 解包、HTML 表格候选和单元格证据准入。 依赖:document_layout.mineru、统一 AppError、requests Response 协议最小替身。 逻辑:全部使用脱敏构造响应,不访问真实 MinerU 服务,也不把文件正文写入失败输出。 """ from __future__ import annotations import json import pytest from app.core.errors import ServiceUnavailableError, ValidationError from app.services.shipping_notice.document_layout.mineru import ( MinerUClient, MinerUClientConfig, parse_mineru_candidate, ) def _mineru_payload(*, with_cell_coordinates: bool = False) -> dict: """构造与 MinerU 3.1.14 pipeline 相同的字符串 JSON 包装。""" cell_coordinate = ([ {'row_idx': 0, 'col_idx': 0, 'bbox': [10, 20, 50, 40]}, {'row_idx': 0, 'col_idx': 1, 'bbox': [50, 20, 90, 40]}, {'row_idx': 1, 'col_idx': 0, 'bbox': [10, 40, 50, 60]}, {'row_idx': 1, 'col_idx': 1, 'bbox': [50, 40, 90, 60]}, ] if with_cell_coordinates else []) return { 'task_id': 'task-layout-fixture', 'status': 'completed', 'backend': 'pipeline', 'version': '3.1.14', 'results': { 'fixture': { 'middle_json': json.dumps({ 'pdf_info': [{ 'page_idx': 0, 'page_size': [100, 200], 'blocks': [{'type': 'text', 'bbox': [5, 5, 20, 15]}], }], 'cell_coordinates': cell_coordinate, }), 'model_output': json.dumps([{ 'page_info': {'page_no': 0, 'width': 100, 'height': 200}, 'layout_dets': [{'label': 'table', 'bbox': [10, 20, 90, 120]}], }]), 'content_list': json.dumps([{ 'type': 'table', 'page_idx': 0, 'bbox': [10, 20, 90, 120], 'table_body': ( '' '
PartQty
A-12
' ), }, { 'type': 'text', 'page_idx': 0, 'bbox': [5, 5, 20, 15], 'text': 'Header context', }]), }, }, } class _FakeResponse: """实现 MinerUClient 使用的 requests.Response 最小协议。""" def __init__(self, payload: dict, *, status_code: int = 200, content_length: int | None = None): self.status_code = status_code self.encoding = 'utf-8' self.raw = json.dumps(payload, separators=(',', ':')).encode('utf-8') self.headers = { 'Content-Length': str(len(self.raw) if content_length is None else content_length), } self.closed = False def iter_content(self, chunk_size: int): """按客户端指定大小分块返回构造 JSON。""" for index in range(0, len(self.raw), chunk_size): yield self.raw[index:index + chunk_size] def close(self): """记录响应已关闭,验证资源上限分支不泄漏连接。""" self.closed = True class _FakeSession: """记录 multipart 调用并返回预设响应。""" def __init__(self, response: _FakeResponse): self.response = response self.calls: list[dict] = [] def post(self, url: str, **kwargs): """保存非敏感调用元数据;文件字节仅验证长度,不保存到测试输出。""" files = kwargs.get('files') or [] self.calls.append({ 'url': url, 'timeout': kwargs.get('timeout'), 'stream': kwargs.get('stream'), 'file_size': len(files[0][1][1]) if files else 0, 'data': list(kwargs.get('data') or []), }) return self.response class _AsyncSession: """模拟 `/tasks` 提交、状态轮询和结果读取。""" def __init__(self, result: dict): self.result = result self.calls: list[str] = [] def post(self, url: str, **_kwargs): """返回异步任务 ID。""" self.calls.append(url) return _FakeResponse({'task_id': 'task-async'}, status_code=202) def get(self, url: str, **_kwargs): """第一次读取终态,结果接口返回完整 MinerU payload。""" self.calls.append(url) if url.endswith('/result'): return _FakeResponse(self.result) return _FakeResponse({'task_id': 'task-async', 'status': 'completed'}) def test_mineru_candidate_preserves_table_structure_but_blocks_cell_evidence(): """只有整表 bbox + HTML 时必须保留行列候选并阻止确定性单元格证据。""" candidate = parse_mineru_candidate(_mineru_payload()) assert len(candidate.pages) == 1 assert candidate.pages[0].text_blocks[0].text == 'Header context' assert candidate.pages[0].tables[0].row_count == 2 assert candidate.pages[0].tables[0].cell_count == 4 assert candidate.pages[0].tables[0].normalized_bbox.model_dump() == { 'x0': 0.01, 'y0': 0.02, 'x1': 0.09, 'y1': 0.12, } assert candidate.pages[0].tables[0].bbox.model_dump() == { 'x0': 1.0, 'y0': 4.0, 'x1': 9.0, 'y1': 24.0, } assert candidate.capability.has_page_coordinates is True assert candidate.capability.has_table_structure is True assert candidate.capability.has_cell_coordinates is False assert candidate.capability.deterministic_cell_evidence_ready is False assert candidate.capability.issues == ['mineru_cell_coordinates_missing'] def test_mineru_candidate_accepts_async_table_html_and_page_no_fields(): """异步结果使用 table_html/content_type/page_no 时仍须恢复同一表格候选。""" payload = _mineru_payload() content = json.loads(payload['results']['fixture']['content_list']) table = content[0] table['content_type'] = table.pop('type') table['table_html'] = table.pop('table_body') table['page_no'] = table.pop('page_idx') + 1 payload['results']['fixture']['content_list'] = json.dumps(content) candidate = parse_mineru_candidate(payload) assert len(candidate.pages[0].tables) == 1 assert candidate.pages[0].tables[0].row_count == 2 def test_mineru_capability_accepts_explicit_cell_coordinate_objects(): """服务未来直接返回带行列身份的 cell bbox 时能力报告才能标记证据就绪。""" candidate = parse_mineru_candidate(_mineru_payload(with_cell_coordinates=True)) assert candidate.capability.cell_bbox_count == 4 assert candidate.capability.has_cell_coordinates is True assert candidate.capability.deterministic_cell_evidence_ready is True assert candidate.capability.issues == [] def test_mineru_capability_rejects_partial_cell_coordinates(): """部分单元格有坐标仍不足以证明整表,必须保持确定性证据未就绪。""" payload = _mineru_payload(with_cell_coordinates=True) middle = json.loads(payload['results']['fixture']['middle_json']) middle['cell_coordinates'] = middle['cell_coordinates'][:1] payload['results']['fixture']['middle_json'] = json.dumps(middle) candidate = parse_mineru_candidate(payload) assert candidate.capability.cell_bbox_count == 1 assert candidate.capability.html_cell_count == 4 assert candidate.capability.has_cell_coordinates is False assert candidate.capability.deterministic_cell_evidence_ready is False assert candidate.capability.issues == ['mineru_cell_coordinates_incomplete'] def test_mineru_client_sends_bounded_single_file_request(): """客户端只提交单文件、关闭图片/公式输出,并使用配置化超时。""" response = _FakeResponse(_mineru_payload()) session = _FakeSession(response) client = MinerUClient( MinerUClientConfig( base_url='http://mineru.internal:8100/', backend='pipeline', connect_timeout_seconds=3, read_timeout_seconds=45, ), session=session, ) payload = client.parse_file(filename='fixture.pdf', content=b'%PDF-fixture') assert payload['status'] == 'completed' assert session.calls == [{ 'url': 'http://mineru.internal:8100/file_parse', 'timeout': (3, 45), 'stream': True, 'file_size': 12, 'data': [ ('backend', 'pipeline'), ('parse_method', 'auto'), ('formula_enable', 'false'), ('table_enable', 'true'), ('image_analysis', 'false'), ('return_md', 'false'), ('return_middle_json', 'true'), ('return_model_output', 'true'), ('return_content_list', 'true'), ('return_images', 'false'), ('response_format_zip', 'false'), ('lang_list', 'ch'), ], }] assert response.closed is True def test_mineru_async_client_submits_polls_and_reads_result_without_long_post(): """生产调用应使用 `/tasks` 短提交,再通过状态和结果接口获取 completed payload。""" session = _AsyncSession(_mineru_payload()) client = MinerUClient(MinerUClientConfig( base_url='http://mineru.internal:8100', poll_interval_seconds=0.01, ), session=session) payload = client.parse_file_async(filename='fixture.pdf', content=b'%PDF') assert payload['status'] == 'completed' assert session.calls == [ 'http://mineru.internal:8100/tasks', 'http://mineru.internal:8100/tasks/task-async', 'http://mineru.internal:8100/tasks/task-async/result', ] def test_mineru_client_rejects_unsupported_empty_and_large_files_before_network(): """文件类型、空内容和上传上限必须在 HTTP 请求前拒绝。""" session = _FakeSession(_FakeResponse(_mineru_payload())) client = MinerUClient( MinerUClientConfig(base_url='http://mineru.internal:8100', max_upload_bytes=4), session=session, ) with pytest.raises(ValidationError) as unsupported: client.parse_file(filename='fixture.xlsx', content=b'1234') assert unsupported.value.code == 'SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED' with pytest.raises(ValidationError) as empty: client.parse_file(filename='fixture.pdf', content=b'') assert empty.value.code == 'SHIPPING_NOTICE.LAYOUT_FILE_EMPTY' with pytest.raises(ValidationError) as large: client.parse_file(filename='fixture.pdf', content=b'12345') assert large.value.code == 'SHIPPING_NOTICE.LAYOUT_FILE_TOO_LARGE' assert session.calls == [] def test_mineru_client_stops_oversized_response_and_closes_connection(): """Content-Length 已超限时不得读取响应正文,并必须关闭连接。""" response = _FakeResponse(_mineru_payload(), content_length=10_000) client = MinerUClient( MinerUClientConfig(base_url='http://mineru.internal:8100', max_response_bytes=100), session=_FakeSession(response), ) with pytest.raises(ServiceUnavailableError) as caught: client.parse_file(filename='fixture.pdf', content=b'%PDF') assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_RESPONSE_TOO_LARGE' assert response.closed is True def test_mineru_client_classifies_terminal_provider_error_without_filename_leak(): """MinerU 409 终态失败应返回稳定非重试错误,details 不得包含上传文件名。""" response = _FakeResponse({ 'task_id': 'failed-task', 'status': 'failed', 'backend': 'hybrid-auto-engine', 'file_names': ['sensitive-order-name'], 'error': 'Device string must not be empty', }, status_code=409) client = MinerUClient( MinerUClientConfig(base_url='http://mineru.internal:8100'), session=_FakeSession(response), ) with pytest.raises(ValidationError) as caught: client.parse_file(filename='sensitive-order-name.pdf', content=b'%PDF') assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED' assert caught.value.retryable is False assert 'sensitive-order-name' not in json.dumps(caught.value.details) assert caught.value.details['provider_error_code'] == 'device_not_configured' def test_mineru_candidate_rejects_invalid_nested_json_and_multiple_files(): """嵌套 JSON 损坏或批量结果不得被单 Document 适配器接受。""" invalid_json = _mineru_payload() invalid_json['results']['fixture']['middle_json'] = 'not-json' with pytest.raises(ValidationError) as caught: parse_mineru_candidate(invalid_json) assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE' multiple = _mineru_payload() multiple['results']['other'] = dict(multiple['results']['fixture']) with pytest.raises(ValidationError, match='exactly one file'): parse_mineru_candidate(multiple) def test_mineru_candidate_rejects_content_bbox_outside_provider_canvas(): """content_list bbox 超过 MinerU 0..1000 画布时不得截断或猜测坐标。""" payload = _mineru_payload() content = json.loads(payload['results']['fixture']['content_list']) content[0]['bbox'] = [10, 20, 1001, 120] payload['results']['fixture']['content_list'] = json.dumps(content) with pytest.raises(ValidationError) as caught: parse_mineru_candidate(payload) assert caught.value.code == 'SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE'