import csv import io import os import threading from pathlib import Path from app.features.download.journal import CsvJournal, explain_os_error from app.platform.client import NqiError def test_progress_recovers_by_streaming_and_truncates_only_a_bad_tail(tmp_path: Path, monkeypatch): csv_path = tmp_path / "out.csv" progress = tmp_path / "progress.jsonl" journal = CsvJournal(csv_path, progress, ["栅格", "小区"]) journal.open() assert journal.write_rows("1", [["1", "a"], ["1", "b"]]) == 2 assert journal.write_rows("2", [["2", ""]]) == 1 journal.close() assert all(isinstance(item, int) for item in journal.completed) good_progress = progress.read_bytes() with progress.open("ab") as handle: handle.write(b"{bad\n") with csv_path.open("ab") as handle: handle.write("垃圾,数据\r\n".encode("utf-8")) def fail_read_text(*_args, **_kwargs): raise AssertionError("恢复进度不应整份读入") monkeypatch.setattr(Path, "read_text", fail_read_text) journal.open() monkeypatch.undo() assert progress.read_bytes() == good_progress assert "垃圾" not in csv_path.read_text(encoding="utf-8") assert 1 in journal.completed and "1" in journal.completed assert journal.write_rows("1", [["1", "again"]]) == 0 journal.close() body = list(csv.reader(io.StringIO(csv_path.read_text(encoding="utf-8-sig")))) assert body == [["栅格", "小区"], ["1", "a"], ["1", "b"], ["2", ""]] def test_clean_progress_is_not_rewritten(tmp_path: Path, monkeypatch): csv_path = tmp_path / "out.csv" progress = tmp_path / "progress.jsonl" journal = CsvJournal(csv_path, progress, ["栅格"]) journal.open() journal.write_rows("9", [["9"]]) journal.close() before = progress.read_bytes() calls = _patch_fsync(monkeypatch) journal.open() journal.close() assert progress.read_bytes() == before assert calls == [] def test_commit_many_fsyncs_once_per_batch_and_keeps_progress_open(tmp_path: Path, monkeypatch): journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["栅格"]) journal.open() handle = journal._progress calls = _patch_fsync(monkeypatch) written = journal.commit_many( [ ("1", [["1"], ["1"]]), ("1", [["1"]]), ("2", [["2"]]), ] ) assert written == 3 assert calls == [journal._file.fileno(), handle.fileno()] assert journal._progress is handle assert handle.closed is False calls.clear() assert journal.commit_many([("1", [["1"]])]) == 0 assert calls == [] try: journal.commit_many([("3", [])]) except ValueError as exc: assert "至少要写出一行" in str(exc) else: raise AssertionError("空行应该拒绝") journal.close() rows = list(csv.reader(io.StringIO((tmp_path / "out.csv").read_text(encoding="utf-8-sig")))) assert rows == [["栅格"], ["1"], ["1"], ["2"]] def test_commit_many_is_thread_safe(tmp_path: Path): journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["组", "序号", "内容"]) journal.open() def write_group(name: str) -> None: items = [(f"{name}-{index}", [[name, str(index), "甲" * 20]]) for index in range(20)] journal.commit_many(items) threads = [threading.Thread(target=write_group, args=(name,)) for name in ("甲", "乙")] for thread in threads: thread.start() for thread in threads: thread.join() journal.close() rows = list(csv.reader(io.StringIO((tmp_path / "out.csv").read_text(encoding="utf-8-sig")))) assert len(rows) == 41 assert all(len(row) == 3 for row in rows) assert {row[0] for row in rows[1:]} == {"甲", "乙"} def test_file_errors_use_chinese(tmp_path: Path, monkeypatch): busy = OSError("busy") busy.winerror = 32 locked = OSError("locked") locked.winerror = 33 full = OSError("full") full.winerror = 112 full_errno = OSError("full") full_errno.errno = 28 assert explain_os_error(busy) == "文件被占用,请先关闭 Excel 等程序" assert explain_os_error(locked) == "文件被占用,请先关闭 Excel 等程序" assert explain_os_error(full) == "磁盘空间不足" assert explain_os_error(full_errno) == "磁盘空间不足" journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["栅格"]) journal.open() def deny(_fd): error = PermissionError(13, "busy") error.winerror = 32 raise error monkeypatch.setattr("app.features.download.journal.os.fsync", deny) try: journal.write_rows("1", [["1"]]) except NqiError as exc: assert str(exc) == "文件被占用,请先关闭 Excel 等程序" else: raise AssertionError("占用文件时应给出中文") journal.close() def _patch_fsync(monkeypatch): calls = [] original = os.fsync def spy(fd): calls.append(fd) return original(fd) monkeypatch.setattr("app.features.download.journal.os.fsync", spy) return calls