test_brief_file.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """Tests for the atomic best-effort durable brief writer (BriefFile)."""
  2. import os
  3. from stt_daemon.assistant.brief_file import BriefFile
  4. def _path(tmp_path):
  5. return tmp_path / "brief.md"
  6. def _tmps(tmp_path):
  7. return [p.name for p in tmp_path.iterdir() if p.suffix == ".tmp"]
  8. def test_write_enabled_property(tmp_path):
  9. assert BriefFile(True, str(tmp_path)).write_enabled is True
  10. assert BriefFile(False, str(tmp_path)).write_enabled is False
  11. def test_disabled_write_and_clear_create_no_file(tmp_path):
  12. # misleading-success probe: disabled means the path must never appear.
  13. brief = BriefFile(False, str(tmp_path))
  14. brief.write("hello")
  15. assert not _path(tmp_path).exists()
  16. brief.clear()
  17. assert not _path(tmp_path).exists()
  18. assert not any(tmp_path.iterdir())
  19. def test_enabled_write_writes_exact_text(tmp_path):
  20. brief = BriefFile(True, str(tmp_path))
  21. brief.write("hello")
  22. assert _path(tmp_path).read_text(encoding="utf-8") == "hello"
  23. assert _path(tmp_path).read_bytes() == b"hello"
  24. assert _tmps(tmp_path) == []
  25. def test_second_write_replaces_atomically_no_tmp(tmp_path):
  26. # stale-state probe: only the newest text survives, no .tmp leaks.
  27. brief = BriefFile(True, str(tmp_path))
  28. brief.write("first")
  29. brief.write("second")
  30. assert _path(tmp_path).read_text(encoding="utf-8") == "second"
  31. assert _tmps(tmp_path) == []
  32. def test_clear_empties_file(tmp_path):
  33. brief = BriefFile(True, str(tmp_path))
  34. brief.write("content")
  35. brief.clear()
  36. assert _path(tmp_path).read_text(encoding="utf-8") == ""
  37. assert _path(tmp_path).exists()
  38. def test_write_failure_path_swallowed_no_raise(tmp_path):
  39. # failure probe: parent is a regular file, so makedirs/open fail -> swallow.
  40. blocker = tmp_path / "blocker"
  41. blocker.write_text("x", encoding="utf-8")
  42. brief = BriefFile(True, str(blocker / "nested"))
  43. brief.write("hello") # must not raise
  44. assert not os.path.exists(str(blocker / "nested"))
  45. def test_clear_failure_path_swallowed_no_raise(tmp_path):
  46. brief = BriefFile(True, str(tmp_path / "missing"))
  47. brief.clear() # missing dir -> open fails -> swallowed, no raise