"""Tests for the atomic best-effort durable brief writer (BriefFile).""" import os from stt_daemon.assistant.brief_file import BriefFile def _path(tmp_path): return tmp_path / "brief.md" def _tmps(tmp_path): return [p.name for p in tmp_path.iterdir() if p.suffix == ".tmp"] def test_write_enabled_property(tmp_path): assert BriefFile(True, str(tmp_path)).write_enabled is True assert BriefFile(False, str(tmp_path)).write_enabled is False def test_disabled_write_and_clear_create_no_file(tmp_path): # misleading-success probe: disabled means the path must never appear. brief = BriefFile(False, str(tmp_path)) brief.write("hello") assert not _path(tmp_path).exists() brief.clear() assert not _path(tmp_path).exists() assert not any(tmp_path.iterdir()) def test_enabled_write_writes_exact_text(tmp_path): brief = BriefFile(True, str(tmp_path)) brief.write("hello") assert _path(tmp_path).read_text(encoding="utf-8") == "hello" assert _path(tmp_path).read_bytes() == b"hello" assert _tmps(tmp_path) == [] def test_second_write_replaces_atomically_no_tmp(tmp_path): # stale-state probe: only the newest text survives, no .tmp leaks. brief = BriefFile(True, str(tmp_path)) brief.write("first") brief.write("second") assert _path(tmp_path).read_text(encoding="utf-8") == "second" assert _tmps(tmp_path) == [] def test_clear_empties_file(tmp_path): brief = BriefFile(True, str(tmp_path)) brief.write("content") brief.clear() assert _path(tmp_path).read_text(encoding="utf-8") == "" assert _path(tmp_path).exists() def test_write_failure_path_swallowed_no_raise(tmp_path): # failure probe: parent is a regular file, so makedirs/open fail -> swallow. blocker = tmp_path / "blocker" blocker.write_text("x", encoding="utf-8") brief = BriefFile(True, str(blocker / "nested")) brief.write("hello") # must not raise assert not os.path.exists(str(blocker / "nested")) def test_clear_failure_path_swallowed_no_raise(tmp_path): brief = BriefFile(True, str(tmp_path / "missing")) brief.clear() # missing dir -> open fails -> swallowed, no raise