fix: 批量提交每批只同步一次磁盘
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import csv
|
||||
import io
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from app.features.download.journal import CsvJournal
|
||||
@@ -52,6 +53,56 @@ def test_clean_progress_is_not_rewritten(tmp_path: Path, monkeypatch):
|
||||
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 _patch_fsync(monkeypatch):
|
||||
calls = []
|
||||
original = os.fsync
|
||||
|
||||
Reference in New Issue
Block a user