Files
hermes-agent/tests/hermes_cli/test_atomic_json_write.py
alt-glitch a1bbd329ea refactor: split utils.py into the utils package
utils.py held three subjects in one 871-line file. It is now a package with
one module per subject: utils/files.py (atomic writes, temp files, file mode
and owner, signatures and digests, JSON and YAML file helpers), utils/urls.py
(the base_url helpers) and utils/env.py (truthy values, env numbers, proxy
env helpers). utils/__init__.py re-exports every public name, so no importer
changes. Function bodies are unchanged, no function-level import moved, and
the logger keeps the name "utils".

Tests patch a name in the module that now defines it. Patches stay on the
package where production reads the name through a function-level
"from utils import". The tests of utils itself move to tests/utils/.

A root module that becomes a folder drops out of anything that copies root
*.py files plus a fixed list of packages, so the fixtures that build a partial
source tree now list utils, as do pyproject's packages.find, three check
scripts and the CI change classifier.
2026-11-16 17:16:20 +05:30

56 lines
1.6 KiB
Python

"""Tests for utils.atomic_json_write — crash-safe JSON file writes."""
import json
from unittest.mock import patch
import pytest
from utils import atomic_json_write
class TestAtomicJsonWrite:
"""Core atomic write behavior."""
def test_cleans_up_temp_file_on_baseexception(self, tmp_path):
class SimulatedAbort(BaseException):
pass
target = tmp_path / "data.json"
original = {"preserved": True}
target.write_text(json.dumps(original), encoding="utf-8")
with patch("utils.files.json.dumps", side_effect=SimulatedAbort):
with pytest.raises(SimulatedAbort):
atomic_json_write(target, {"new": True})
tmp_files = [f for f in tmp_path.iterdir() if ".tmp" in f.name]
assert len(tmp_files) == 0
assert json.loads(target.read_text(encoding="utf-8")) == original
def test_concurrent_writes_dont_corrupt(self, tmp_path):
"""Multiple rapid writes should each produce valid JSON."""
import threading
target = tmp_path / "concurrent.json"
errors = []
def writer(n):
try:
atomic_json_write(target, {"writer": n, "data": list(range(100))})
except Exception as e:
errors.append(e)
threads = [threading.Thread(target=writer, args=(i,)) for i in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
assert not errors
# File should contain valid JSON from one of the writers
result = json.loads(target.read_text())
assert "writer" in result
assert len(result["data"]) == 100