Files
ocr-server/tests/test_queue.py
T
zimoyin 5ddda545f5 init2
2026-10-12 11:00:09 +08:00

79 lines
2.8 KiB
Python

from pathlib import Path
from uuid import uuid4
from ocr_server.task_queue import OCRTaskQueue
class FakeOCR:
"""Fake engine that mirrors OCRService.recognize and reports progress."""
def __init__(self) -> None:
self.progress: list[int] = []
def recognize(self, _: Path, on_progress=None) -> list[dict]:
for percent, message in (
(5, "开始推理"),
(10, "模型已就绪"),
(20, "图片已解码,开始文字检测"),
(50, "文字检测完成"),
(80, "文字识别完成"),
):
self.progress.append(percent)
if on_progress is not None:
on_progress(percent, message)
return [
{"text": "Hello", "confidence": 0.95, "polygon": [[0, 0], [40, 0], [40, 10], [0, 10]]},
{"text": "世界", "confidence": 0.85, "polygon": [[45, 0], [85, 0], [85, 10], [45, 10]]},
{"text": "下一行", "confidence": 0.92, "polygon": [[0, 20], [50, 20], [50, 30], [0, 30]]},
]
def test_build_document_groups_segments_into_lines_and_paragraphs() -> None:
document = OCRTaskQueue.build_document(FakeOCR().recognize(Path("sample")))
assert document.text == "Hello世界\n下一行"
assert list(document.polygon) == ["text1", "text2", "text3"]
assert document.polygon["text1"].line == 1
assert document.polygon["text1"].paragraphs == 1
assert document.polygon["text3"].line == 2
def test_filter_document_rebuilds_groups() -> None:
document = OCRTaskQueue.build_document(FakeOCR().recognize(Path("sample")))
filtered = OCRTaskQueue.filter_document(document, 0.9)
assert [item.text for item in filtered.polygon.values()] == ["Hello", "下一行"]
assert filtered.text == "Hello\n下一行"
def test_queue_completes_task() -> None:
queue = OCRTaskQueue(lambda: FakeOCR(), worker_count=1)
file_id = uuid4()
task = queue.submit(file_id, Path("sample"))
queue._queue.join()
assert task.status == "completed"
assert task.progress == 100
assert task.ocr_started_at is not None
assert task.ocr_finished_at is not None
assert task.ocr_elapsed_ms is not None
assert queue.snapshot(file_id)[3] is not None
def test_progress_is_monotonic_and_includes_checkpoints() -> None:
from ocr_server.ocr import OCRService
service = OCRService()
seen: list[int] = []
service._progress_callback = lambda percent, message: seen.append(percent)
service._emit_progress(5, "开始推理")
service._emit_progress(10, "模型已就绪")
service._emit_progress(20, "图片已解码")
service._emit_progress(10, "重复的低进度应被忽略")
service._emit_progress(50, "文字检测完成")
service._emit_progress(80, "文字识别完成")
service._emit_progress(100, "识别完成")
assert seen == [5, 10, 20, 50, 80, 100]