Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

fix: stabilize unit tests across CI environments

myhloli6eb23e686be2
diff --git a/tests/conftest.py b/tests/conftest.py
index 58c983bf..4306a01d 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -11,6 +11,11 @@ import pytest
# 否则中文 locale 机器上既有的英文输出断言会失败。i18n 专项测试自行 monkeypatch 覆盖。
os.environ["MINERU_LANG"] = "en"
+# GitHub Actions 设置 GITHUB_ACTIONS=true 会使 typer/rich 强制彩色输出,
+# OptionHighlighter 会把 "--option" 拆成多段 ANSI 样式,破坏测试的子串断言;
+# 在导入 typer 前统一关闭终端强制模式,保证跨环境输出确定。
+os.environ.setdefault("_TYPER_FORCE_DISABLE_TERMINAL", "1")
+
@pytest.fixture(autouse=True)
def pin_cli_language() -> None:
diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.py
index 5098f004..c4f6ff2e 100644
--- a/tests/unittest/test_doclib_app_startup.py
+++ b/tests/unittest/test_doclib_app_startup.py
@@ -141,6 +141,8 @@ def test_config_set_managed_tier_rejects_missing_models(monkeypatch: pytest.Monk
monkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)
monkeypatch.setattr("mineru.doclib.server.ensure_tier_runtime_dependencies", lambda tier: None)
monkeypatch.setattr(model_download.config.model, "base_dir", str(tmp_path / "models"))
+ # 无 torch 环境会把小模型后端解析为 onnx,显式固定以保持仓库名断言确定。
+ monkeypatch.setattr(model_download.config.model, "small_backend", "torch")
cfg = PatchedConfig(doclib={"data_dir": str(tmp_path), "sqlite": {"path": str(tmp_path / "doclib.db")}})
with TestClient(doclib_app.create_app(cfg)) as client:
@@ -379,20 +381,18 @@ def test_shutdown_removes_only_endpoint_owned_by_current_server(tmp_path: Path)
assert not endpoint_path.exists()
-def test_shutdown_removes_only_uds_path_with_bound_identity(tmp_path: Path) -> None:
+def test_shutdown_removes_only_uds_path_with_bound_identity(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
uds_path = tmp_path / "doclib.sock"
uds_path.write_text("original", encoding="utf-8")
- original_identity = doclib_app._path_identity(str(uds_path))
- assert original_identity is not None
- uds_path.unlink()
- uds_path.write_text("replacement", encoding="utf-8")
- doclib_app._remove_owned_uds_path(str(uds_path), original_identity)
- assert uds_path.read_text(encoding="utf-8") == "replacement"
+ # Linux 会复用刚释放的 inode,真实 stat 无法稳定构造"同路径不同身份";用固定身份值验证清理契约。
+ identities = iter([(0, 2), (0, 2)])
+ monkeypatch.setattr(doclib_app, "_path_identity", lambda _path: next(identities))
- replacement_identity = doclib_app._path_identity(str(uds_path))
- assert replacement_identity is not None
- doclib_app._remove_owned_uds_path(str(uds_path), replacement_identity)
+ doclib_app._remove_owned_uds_path(str(uds_path), (0, 1))
+ assert uds_path.read_text(encoding="utf-8") == "original"
+
+ doclib_app._remove_owned_uds_path(str(uds_path), (0, 2))
assert not uds_path.exists()
diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.py
index d2c0e53e..a2ebb8a5 100644
--- a/tests/unittest/test_doclib_interface_contract.py
+++ b/tests/unittest/test_doclib_interface_contract.py
@@ -180,16 +180,26 @@ def test_list_methods_expose_consistent_pagination_contract() -> None:
assert "offset" in signature.parameters, method_name
+def _iter_effective_routes(app: Any) -> Any:
+ """FastAPI >=0.141 以惰性 _IncludedRouter 挂载 include_router,展开后再做契约断言。"""
+ for route in app.routes:
+ included = getattr(route, "original_router", None)
+ if included is not None:
+ yield from included.routes
+ else:
+ yield route
+
+
def test_interface_app_uses_doclib_server_routes(tmp_path) -> None:
cfg = PatchedConfig(doclib={"log": {"dir": str(tmp_path / "logs")}})
app = create_app(cfg)
- route_names = {getattr(route, "name", "") for route in app.routes}
+ route_names = {getattr(route, "name", "") for route in _iter_effective_routes(app)}
for method_name in AsyncDoclibInterface.__abstractmethods__:
assert method_name in route_names
- route_paths = {getattr(route, "path", "") for route in app.routes}
+ route_paths = {getattr(route, "path", "") for route in _iter_effective_routes(app)}
assert "/api/v1/server/status" in route_paths
assert "/api/v1/server/shutdown" in route_paths
assert "/api/v1/telemetry/status" in route_paths
diff --git a/tests/unittest/test_doclib_telemetry_core.py b/tests/unittest/test_doclib_telemetry_core.py
index f81b1550..f828c680 100644
--- a/tests/unittest/test_doclib_telemetry_core.py
+++ b/tests/unittest/test_doclib_telemetry_core.py
@@ -345,6 +345,12 @@ def test_parse_service_process_doc_records_task_metrics(tmp_path) -> None:
return None
class _Result:
+ # 写盘后的源数据回填会读取 middle_json 的 metadata 与 extensions,提供最小合法替身。
+ middle_json = SimpleNamespace(
+ metadata=SimpleNamespace(document=None, file_suffix="pdf"),
+ extensions={},
+ )
+
def to_dict(self, *, skip_defaults: bool = True) -> dict:
return {"pages": [{"page_idx": 0, "blocks": []}]}
diff --git a/tests/unittest/test_docvortex_routing.py b/tests/unittest/test_docvortex_routing.py
index 7f212d3d..3f051c30 100644
--- a/tests/unittest/test_docvortex_routing.py
+++ b/tests/unittest/test_docvortex_routing.py
@@ -27,6 +27,8 @@ def test_flash_routes_classification_and_native_analysis_explicitly(
class Document:
"""记录公开文档访问与分类,不依赖真实推理模型。"""
+ page_count = 1
+
def __init__(self, data: bytes) -> None:
"""接收由宿主传入的输入字节。"""
assert data == b"pdf"
@@ -36,6 +38,10 @@ def test_flash_routes_classification_and_native_analysis_explicitly(
calls.append("classify")
return classification
+ def page_size(self, index: int) -> tuple[float, float]:
+ """为 DocVortex 几何提取提供合法页面尺寸。"""
+ return 612.0, 792.0
+
def close(self) -> None:
"""记录文档在所有正常路径都及时关闭。"""
calls.append("close")
@@ -79,7 +85,11 @@ def test_hybrid_and_vlm_pdf_outputs_share_docvortex_text_cleanup(
) -> None:
"""推理和原生回填的编排留在宿主,所有非 Flash PDF 出口都使用相同文字清洗。"""
# 只隔离模型推理,真实执行 PDF 管线的公共出口与协议规范化。
- monkeypatch.setattr(pipeline, "PDFDocument", lambda _data: SimpleNamespace(close=lambda: None))
+ monkeypatch.setattr(
+ pipeline,
+ "PDFDocument",
+ lambda _data: SimpleNamespace(close=lambda: None, page_count=1, page_size=lambda _index: (612.0, 792.0)),
+ )
monkeypatch.setattr(
pipeline, "HybridLocalModelContextSingleton", lambda: SimpleNamespace(get_model=lambda: SimpleNamespace(device="cpu"))
)
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index e6bece53..5985f05a 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -2924,6 +2924,7 @@ def test_api_server_preflight_rejects_missing_tier_dependency(monkeypatch: pytes
return object()
monkeypatch.setattr(importlib, "import_module", fake_import_module)
+ monkeypatch.setattr(api_server.mineru_config.model, "small_backend", "torch")
monkeypatch.setattr(parser_tier.importlib_metadata, "packages_distributions", lambda: {"mineru": ["mineru"]})
with pytest.raises(api_server.ParseServerStartupError, match="tier 'basic'.*torch.*mineru\\[torch\\]"):
diff --git a/tests/unittest/test_parser_api_ocr.py b/tests/unittest/test_parser_api_ocr.py
index 153d2e5c..9b2c3c7b 100644
--- a/tests/unittest/test_parser_api_ocr.py
+++ b/tests/unittest/test_parser_api_ocr.py
@@ -10,6 +10,7 @@ from unittest.mock import AsyncMock, Mock
import httpx
import pytest
+import click
from click.testing import CliRunner
from fastapi.testclient import TestClient
@@ -105,4 +106,7 @@ def test_api_server_ocr_defaults_to_request_auto_without_startup_configuration(t
api_server.create_app(ocr_mode="ocr") # type: ignore[call-arg]
result = CliRunner().invoke(api_server.main, ["--ocr-mode", "ocr"])
assert result.exit_code != 0
- assert "No such option: --ocr-mode" in result.output
+ # click 8.5 起报错措辞变为 "No such option '--ocr-mode'. (...)",按两段内容断言。
+ plain_output = click.unstyle(result.output)
+ assert "No such option" in plain_output
+ assert "--ocr-mode" in plain_output