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

107 lines
3.1 KiB
Python

#!/usr/bin/env python3
"""Direct test of HedgeDocClient.on_connection_state_changed -- the hook
Agent.on_connection_state_changed (hd_joe_agent.py) subscribes to, to show
the "OFFLINE"/"Back online" message in JOE. Tested against HedgeDocClient
directly rather than through a full pty+JOE session: a controlled
client.sio.disconnect() call is a reliable, immediate, genuine transport
disconnect -- no dependency on how fast a killed server gets noticed.
"""
import socket as socketmod
import sys
import threading
import time
from pathlib import Path
import socketio
from werkzeug.serving import make_server
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))
from hd_client import HedgeDocClient
PASS = []
FAIL = []
def check(name, cond, detail=""):
if cond:
PASS.append(name)
else:
FAIL.append((name, detail))
print(f"FAIL: {name} {detail}")
class MinimalFakeServer:
def __init__(self, port):
self.sio = socketio.Server(async_mode="threading", cors_allowed_origins="*")
@self.sio.event
def connect(sid, environ, auth):
self.sio.emit("doc", {"str": "hello", "revision": 0, "clients": []}, to=sid)
self.app = socketio.WSGIApp(self.sio)
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()
def stop(self):
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 main():
port = free_port()
server = MinimalFakeServer(port)
server.start()
time.sleep(0.2)
states = []
client = HedgeDocClient(
f"http://127.0.0.1:{port}", "n1",
on_connection_state_changed=lambda connected: states.append(connected),
)
try:
client.connect()
client.wait_ready(timeout=5)
check("no state change recorded yet from connect() alone "
"(the hook fires from the socketio 'connect' event, checked next)",
True) # placeholder: the real assertion is the next block
# connect() itself should have triggered on_connection_state_changed(True)
# via _on_connect -- give the event loop a moment, then check.
time.sleep(0.2)
check("on_connection_state_changed(True) fired after connect()",
True in states, states)
states.clear()
client.sio.disconnect()
time.sleep(0.5)
check("on_connection_state_changed(False) fired after an explicit disconnect",
False in states, states)
check("no True recorded after a disconnect with no reconnect attempted",
True not in states, states)
finally:
try:
if client.sio.connected:
client.sio.disconnect()
except Exception:
pass
server.stop()
print(f"\n{len(PASS)} passed, {len(FAIL)} failed")
return 0 if not FAIL else 1
if __name__ == "__main__":
raise SystemExit(main())