示例工程 31-io-files-struct-socket-sqlite

31-io-files-struct-socket-sqlite/02-atomic-write/test_atomic_write.py

python · 0.9 KB

"""test_atomic_write.py"""
 
from __future__ import annotations
 
from pathlib import Path
 
import pytest
from atomic_write import main, write_atomic
 
 
def test_atomic_write_replaces(tmp_path: Path) -> None:
    target = tmp_path / "data.txt"
    write_atomic(target, "old")
    write_atomic(target, "new")
    assert target.read_text(encoding="utf-8") == "new"
    assert list(tmp_path.glob("*.tmp")) == []
 
 
def test_failure_keeps_original(tmp_path: Path) -> None:
    target = tmp_path / "data.txt"
    write_atomic(target, "keep")
    with pytest.raises(RuntimeError, match="simulated failure"):
        write_atomic(target, "bad", fail=True)
    assert target.read_text(encoding="utf-8") == "keep"
    assert list(tmp_path.glob("*.tmp")) == []
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    main()
    out = capsys.readouterr().out
    assert "content: new" in out
    assert "temp files: 0" in out