Files
thd/hd-joe/test_shadow_text_sync.py
2026-10-15 17:27:46 +02:00

76 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Unit test for a bug found while tracing through the offline scenario:
Agent.handle_local() used to only update self._shadow_text on the success
path. But send_operation() (hd_client.py) already updates
client.document.text optimistically BEFORE attempting to send -- so when
sending raises (offline, or any other reason), document.text has already
moved but _shadow_text hadn't, until this was moved into a `finally`.
Left unfixed, the NEXT remote operation would get translated into JOE IPC
commands against a stale baseline -- a buffer-corruption risk, not just a
lost-edit one.
No real client/server needed: a minimal fake client that reproduces
exactly the one behavior this test cares about (document.text updates,
THEN the call raises) is enough, and keeps this fast and deterministic.
"""
import sys
from pathlib import Path
from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
sys.path.insert(0, str(Path(__file__).resolve().parent))
import hd_joe_agent
PASS = []
FAIL = []
def check(name, cond, detail=""):
if cond:
PASS.append(name)
else:
FAIL.append((name, detail))
print(f"FAIL: {name} {detail}")
class FakeClient:
"""Reproduces hd_client.HedgeDocClient.send_operation()'s real behavior
just enough for this test: document.text updates optimistically, THEN
the call raises -- exactly the order that made _shadow_text go stale."""
def __init__(self, text):
self.document = SimpleNamespace(text=text)
self.on_remote_operation_detail = None
self.on_connection_state_changed = None
def insert(self, cp, inserted):
t = self.document.text
self.document.text = t[:cp] + inserted + t[cp:]
raise ConnectionError("simulated: send failed after the local buffer already moved")
def send_operation(self, op):
raise ConnectionError("simulated: send failed")
def main():
client = FakeClient("hello world")
agent = hd_joe_agent.Agent(client, sock_path=Path("/tmp/unused.sock"), buffer_path=Path("/tmp/unused.md"))
# "hi " inserted at position 0 -> "hi hello world", hex-encoded per the
# real wire format JOE -> agent uses.
hexpayload = "hi ".encode("utf-8").hex()
agent.handle_local(f"I 0 {hexpayload}")
check("the fake client's optimistic insert happened despite the raise",
client.document.text == "hi hello world", client.document.text)
check("_shadow_text was updated to match, via the finally block, even though insert() raised",
getattr(agent, "_shadow_text", None) == client.document.text,
(getattr(agent, "_shadow_text", None), client.document.text))
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
return 0 if not FAIL else 1
if __name__ == "__main__":
raise SystemExit(main())