test_upload_path.py 2.27 KB
"""上传文件定位:跨环境(Windows 开发 ↔ Linux 容器)必须能找到同一个文件。

这组测试来自一个真实事故:迁移脚本在 Windows 上把 `data\\uploads\\x.md` 写进库,
容器里 DATA_DIR 是 `/app/data`,抽取直接报「文件不存在」。
"""
from __future__ import annotations
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from app.ingest.filename import resolve_upload_path   # noqa: E402


def _make(tmp_path: Path, name: str = "deadbeefdeadbeef.md") -> Path:
    uploads = tmp_path / "uploads"
    uploads.mkdir(parents=True, exist_ok=True)
    f = uploads / name
    f.write_text("内容", encoding="utf-8")
    return uploads


class TestResolveUploadPath:
    def test_prefers_stored_name(self, tmp_path: Path):
        uploads = _make(tmp_path)
        doc = {"stored_name": "deadbeefdeadbeef.md",
               "stored_path": "/somewhere/else/deadbeefdeadbeef.md"}
        assert resolve_upload_path(doc, uploads).read_text(encoding="utf-8") == "内容"

    def test_recovers_from_windows_path_written_on_another_host(self, tmp_path: Path):
        """库里是 Windows 相对路径,当前是 Linux 容器 —— 必须还能定位到。"""
        uploads = _make(tmp_path)
        doc = {"stored_name": "", "stored_path": "data\\uploads\\deadbeefdeadbeef.md"}
        assert resolve_upload_path(doc, uploads).exists()

    def test_recovers_from_container_path_on_host(self, tmp_path: Path):
        uploads = _make(tmp_path)
        doc = {"stored_name": "", "stored_path": "/app/data/uploads/deadbeefdeadbeef.md"}
        assert resolve_upload_path(doc, uploads).exists()

    def test_falls_back_to_hash_prefix(self, tmp_path: Path):
        """v1 的落盘名是 `{hash}_{原名}`,stored_name 还没有。"""
        uploads = _make(tmp_path, "55129606dd8e6e0b_旧文件名.md")
        doc = {"stored_name": "", "stored_path": "", "file_hash": "55129606dd8e6e0b"}
        assert resolve_upload_path(doc, uploads).exists()

    def test_missing_file_returns_a_path_not_an_exception(self, tmp_path: Path):
        uploads = tmp_path / "uploads"
        uploads.mkdir()
        got = resolve_upload_path({"stored_name": "nope.md"}, uploads)
        assert isinstance(got, Path) and not got.exists()