266 lines
9.3 KiB
Python
266 lines
9.3 KiB
Python
#!/usr/bin/env python3
|
|
"""End-to-end regression test for the BOF/EOF local-insert bugs.
|
|
|
|
Runs the real patched JOE binary under a pty, driven by hd_joe_agent.py,
|
|
against an in-process fake HedgeDoc server. No mocking of the OT engine or
|
|
the C code: this is the actual compiled binary and the actual Python agent,
|
|
exercised through real keystrokes.
|
|
"""
|
|
import json
|
|
import os
|
|
import socket as socketmod
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
import pexpect
|
|
import socketio
|
|
from werkzeug.serving import make_server
|
|
|
|
import sys as _sys
|
|
from pathlib import Path as _Path
|
|
_sys.path.insert(0, str(_Path(__file__).resolve().parent.parent / "hd_common"))
|
|
|
|
from hd_client import apply_operation
|
|
|
|
|
|
def apply_operation_strict(text, op):
|
|
"""Mirror ot.js's TextOperation.fromJSON validation exactly: a literal 0
|
|
of any kind anywhere in the op is invalid ("unknown operation: 0") per
|
|
isRetain/isInsert/isDelete in the real server's text-operation.js. This is
|
|
what makes the fake server catch what hd_client.py's own (lenient)
|
|
apply_operation does not -- it's the actual root cause of the BOF/EOF
|
|
bugs: insert_operation/replace_operation used to always emit a trailing
|
|
or leading 0 retain at the document boundaries.
|
|
"""
|
|
for c in op:
|
|
if isinstance(c, bool):
|
|
raise ValueError(f"unknown operation: {c!r}")
|
|
if isinstance(c, int) and c == 0:
|
|
raise ValueError(f"unknown operation: {c!r}")
|
|
return apply_operation(text, op)
|
|
|
|
JOE_BIN = os.environ.get("JOE_BIN", "/home/claude/work/build/joe-4.8/joe/joe")
|
|
AGENT = os.path.join(os.path.dirname(__file__), "hd_joe_agent.py")
|
|
|
|
|
|
class FakeServer:
|
|
"""One fake-HedgeDoc instance on its own port, run in a background thread.
|
|
|
|
Also simulates HedgeDoc's real persistence model: the live OT document
|
|
(self.text) and the DB-backed content served by /download (self.db_text)
|
|
are DELIBERATELY not the same thing. Real HedgeDoc only flushes live ->
|
|
DB once a second, and only if dirty (lib/realtime.js). db_flush_interval
|
|
reproduces that lag so tests can catch code that wrongly treats
|
|
/download as authoritative-and-current.
|
|
"""
|
|
|
|
def __init__(self, initial_text, port, ack_delay=0.0, db_flush_interval=1.0):
|
|
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
|
|
self.app = socketio.WSGIApp(self.sio)
|
|
self.text = initial_text
|
|
self.revision = 0
|
|
self.operations = []
|
|
self.rejections = []
|
|
self.lock = threading.Lock()
|
|
self.port = port
|
|
self.ack_delay = ack_delay
|
|
self.db_text = initial_text
|
|
self._dirty = False
|
|
self._stop_flush = threading.Event()
|
|
|
|
def flush_loop():
|
|
while not self._stop_flush.wait(db_flush_interval):
|
|
with self.lock:
|
|
if self._dirty:
|
|
self.db_text = self.text
|
|
self._dirty = False
|
|
|
|
self.flush_thread = threading.Thread(target=flush_loop, daemon=True)
|
|
|
|
@self.sio.event
|
|
def connect(sid, environ, auth):
|
|
with self.lock:
|
|
self.sio.emit("doc", {"str": self.text, "revision": self.revision, "clients": []}, to=sid)
|
|
|
|
@self.sio.on("operation")
|
|
def on_operation(sid, base_revision, operation, selection):
|
|
if self.ack_delay:
|
|
time.sleep(self.ack_delay) # simulate real network/server latency
|
|
with self.lock:
|
|
self.operations.append((base_revision, operation))
|
|
if base_revision != self.revision:
|
|
self.rejections.append((base_revision, operation, "bad base_revision"))
|
|
return
|
|
try:
|
|
self.text = apply_operation_strict(self.text, operation)
|
|
self._dirty = True
|
|
except Exception as exc:
|
|
self.rejections.append((base_revision, operation, repr(exc)))
|
|
return
|
|
self.revision += 1
|
|
self.sio.emit("ack", self.revision, to=sid)
|
|
# Real HedgeDoc broadcasts to every OTHER connected client in
|
|
# the note's room (EditorSocketIOServer.onOperation:
|
|
# socket.broadcast.in(this.docId).emit('operation', ...)).
|
|
# Without this, a second connected client (e.g. an AI
|
|
# integration, or another browser tab) never sees the edit --
|
|
# which single-client tests can never catch.
|
|
self.sio.emit(
|
|
"operation",
|
|
(sid, self.revision, operation, selection, None),
|
|
skip_sid=sid,
|
|
)
|
|
|
|
socketio_app = self.app
|
|
|
|
def wsgi_app(environ, start_response):
|
|
path = environ.get("PATH_INFO", "")
|
|
if path.endswith("/download"):
|
|
with self.lock:
|
|
body = self.db_text.encode("utf-8")
|
|
start_response("200 OK", [
|
|
("Content-Type", "text/markdown; charset=UTF-8"),
|
|
("Content-Length", str(len(body))),
|
|
])
|
|
return [body]
|
|
return socketio_app(environ, start_response)
|
|
|
|
self.app = wsgi_app
|
|
self.srv = make_server("127.0.0.1", port, self.app, threaded=True)
|
|
self.thread = threading.Thread(target=self.srv.serve_forever, daemon=True)
|
|
|
|
def start(self):
|
|
self.thread.start()
|
|
self.flush_thread.start()
|
|
|
|
def stop(self):
|
|
self._stop_flush.set()
|
|
self.srv.shutdown()
|
|
|
|
|
|
def free_port():
|
|
s = socketmod.socket(socketmod.AF_INET, socketmod.SOCK_STREAM)
|
|
s.bind(("127.0.0.1", 0))
|
|
port = s.getsockname()[1]
|
|
s.close()
|
|
return port
|
|
|
|
|
|
def run_case(name, initial_text, keys, settle=0.6, ack_delay=0.0):
|
|
port = free_port()
|
|
server = FakeServer(initial_text, port, ack_delay=ack_delay)
|
|
server.start()
|
|
time.sleep(0.2)
|
|
|
|
log_path = f"/tmp/hd-joe-{name}.log"
|
|
sock_path = f"/tmp/hd-joe-{name}.sock"
|
|
for p in (log_path, sock_path):
|
|
try:
|
|
os.remove(p)
|
|
except OSError:
|
|
pass
|
|
|
|
cmd = (
|
|
f"python3 {AGENT} http://127.0.0.1:{port} test-note "
|
|
f"--joe {JOE_BIN} --socket {sock_path} --log {log_path} --debug"
|
|
)
|
|
child = pexpect.spawn(cmd, cwd=os.path.dirname(__file__), env={**os.environ, "TERM": "xterm"},
|
|
dimensions=(24, 80), timeout=10)
|
|
time.sleep(1.0) # let JOE start, agent connect, initial doc load
|
|
|
|
for item in keys:
|
|
if isinstance(item, float):
|
|
time.sleep(item)
|
|
elif isinstance(item, tuple) and item[0] == "burst":
|
|
# Send a whole string in one write with no inter-key settle,
|
|
# simulating continuous fast typing rather than one keystroke
|
|
# at a time.
|
|
child.send(item[1])
|
|
else:
|
|
child.send(item)
|
|
time.sleep(0.15)
|
|
|
|
time.sleep(settle)
|
|
|
|
# Quit JOE: Ctrl-K X (save+exit). Send twice in case of an intervening prompt.
|
|
child.send("\x0bx")
|
|
time.sleep(0.5)
|
|
child.send("\r")
|
|
# Give the agent time to drain its pending queue and exit on its own
|
|
# (it now blocks on this deliberately) before falling back to a kill.
|
|
try:
|
|
child.wait()
|
|
except pexpect.TIMEOUT:
|
|
pass
|
|
if child.isalive():
|
|
child.terminate(force=True)
|
|
|
|
time.sleep(0.3)
|
|
server.stop()
|
|
|
|
log_tail = ""
|
|
if os.path.exists(log_path):
|
|
with open(log_path, encoding="utf-8", errors="replace") as f:
|
|
log_tail = f.read()[-4000:]
|
|
|
|
return {
|
|
"server_text": server.text,
|
|
"server_revision": server.revision,
|
|
"operations": server.operations,
|
|
"rejections": server.rejections,
|
|
"log_tail": log_tail,
|
|
}
|
|
|
|
|
|
def main():
|
|
print("=" * 70)
|
|
print("TEST A: insert newline at BOF (top-of-file), expect first char kept")
|
|
print("=" * 70)
|
|
a = run_case(
|
|
"bof",
|
|
initial_text="helloworld",
|
|
keys=["\r"], # cursor starts at BOF on a fresh file; press Enter
|
|
)
|
|
print("server text repr:", repr(a["server_text"]))
|
|
print("server revision:", a["server_revision"])
|
|
print("operations sent:", a["operations"])
|
|
print("rejections:", a["rejections"])
|
|
expected = "\nhelloworld"
|
|
ok_a = a["server_text"] == expected
|
|
print("EXPECTED:", repr(expected))
|
|
print("PASS" if ok_a else "FAIL", "- BOF test")
|
|
print()
|
|
|
|
print("=" * 70)
|
|
print("TEST B: type a character at EOF, expect it to reach the server")
|
|
print("=" * 70)
|
|
b = run_case(
|
|
"eof",
|
|
initial_text="helloworld",
|
|
keys=["\x0bv", 0.3, ("burst", "continued typing")], # Ctrl-K V = goto EOF, then type continuously
|
|
settle=1.5,
|
|
ack_delay=float(os.environ.get("ACK_DELAY", "0")),
|
|
)
|
|
print("server text repr:", repr(b["server_text"]))
|
|
print("server revision:", b["server_revision"])
|
|
print("operations sent:", b["operations"])
|
|
print("rejections:", b["rejections"])
|
|
expected_b = "helloworldcontinued typing"
|
|
ok_b = b["server_text"] == expected_b
|
|
print("EXPECTED:", repr(expected_b))
|
|
print("PASS" if ok_b else "FAIL", "- EOF test")
|
|
|
|
if not ok_a:
|
|
print("\n--- bof agent log tail ---")
|
|
print(a["log_tail"])
|
|
if not ok_b:
|
|
print("\n--- eof agent log tail ---")
|
|
print(b["log_tail"])
|
|
|
|
sys.exit(0 if (ok_a and ok_b) else 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|