fix(client-python): CLI batch reuses one loop/channel; smoke attaches stream before advise (CPY-005, CPY-006, #257)

This commit is contained in:
Joseph Doherty
2026-12-03 09:47:40 -05:00
parent 3173ad7083
commit 855cd8a526
4 changed files with 334 additions and 11 deletions
+158
View File
@@ -973,3 +973,161 @@ def test_stream_events_renders_replay_gap(monkeypatch: pytest.MonkeyPatch) -> No
# The gap is rendered, never swallowed, and the normal event still follows it.
assert "replayGap" not in rows[1]
assert rows[1]["workerSequence"] == "43"
def test_batch_reuses_one_client_and_event_loop_across_lines(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""CPY-005: each batch line used to run a new loop and dial a new channel."""
import asyncio
connects: list[object] = []
loops: list[asyncio.AbstractEventLoop] = []
closes: list[int] = []
class _CountingGalaxy(_FakeGalaxyClient):
async def test_connection(self) -> bool:
loops.append(asyncio.get_running_loop())
return True
async def close(self) -> None:
closes.append(1)
fake = _CountingGalaxy(ok=True)
async def fake_connect(options, **_kwargs):
connects.append(options)
return fake
monkeypatch.setattr(commands_module.GalaxyRepositoryClient, "connect", fake_connect)
result = CliRunner().invoke(
main,
["batch"],
input=("galaxy-test-connection --plaintext --json\n" * 3),
)
assert result.exit_code == 0, result.output
assert result.output.count(_BATCH_EOR) == 3
assert len(connects) == 1, "one channel for all three lines"
assert len(set(map(id, loops))) == 1, "one event loop for all three lines"
assert closes == [1], "the shared client is closed once, when the batch ends"
assert commands_module._batch_context is None
def test_batch_dials_separate_clients_for_distinct_connections(
monkeypatch: pytest.MonkeyPatch,
) -> None:
connects: list[str] = []
async def fake_connect(options, **_kwargs):
connects.append(options.endpoint)
return _FakeGalaxyClient(ok=True)
monkeypatch.setattr(commands_module.GalaxyRepositoryClient, "connect", fake_connect)
result = CliRunner().invoke(
main,
["batch"],
input=(
"galaxy-test-connection --plaintext --endpoint a:1 --json\n"
"galaxy-test-connection --plaintext --endpoint b:1 --json\n"
"galaxy-test-connection --plaintext --endpoint a:1 --json\n"
),
)
assert result.exit_code == 0, result.output
assert connects == ["a:1", "b:1"]
class _SmokeSession:
"""Fake session that only delivers an initial event to a subscriber attached before advise."""
def __init__(self, *, attach_ack: bool) -> None:
from zb_mom_ww_mxgateway.generated import mxaccess_gateway_pb2 as pb
self._pb = pb
capabilities = ["stream-events-attached-ack"] if attach_ack else []
self.open_reply = pb.OpenSessionReply(session_id="s1", capabilities=capabilities)
self.session_id = "s1"
self.calls: list[str] = []
self.emit_requested: bool | None = None
self._subscribed = False
self._advised = asyncio_event()
async def __aenter__(self) -> "_SmokeSession":
return self
async def __aexit__(self, *_exc: object) -> None:
return None
async def register(self, _name: str) -> int:
self.calls.append("register")
return 1
async def add_item(self, _server: int, _item: str) -> int:
self.calls.append("add_item")
return 2
async def advise(self, _server: int, _item: int) -> None:
self.calls.append("advise")
self._advised.set()
def stream_events(self, *, emit_stream_attached: bool = False):
self.calls.append("stream_events")
self.emit_requested = emit_stream_attached
self._subscribed = True
pb = self._pb
async def _gen():
if emit_stream_attached:
yield pb.MxEvent(stream_attached=pb.StreamAttached())
await self._advised.wait()
# The initial value is only delivered to an already-registered subscriber.
yield pb.MxEvent(worker_sequence=7)
return _gen()
def asyncio_event():
import asyncio
return asyncio.Event()
class _SmokeClient:
def __init__(self, session: _SmokeSession) -> None:
self._session = session
async def __aenter__(self) -> "_SmokeClient":
return self
async def __aexit__(self, *_exc: object) -> None:
return None
async def open_session(self, **_kwargs):
return self._session
@pytest.mark.parametrize("attach_ack", [True, False])
def test_smoke_attaches_event_stream_before_advise(
monkeypatch: pytest.MonkeyPatch, attach_ack: bool
) -> None:
"""CPY-006: advising before the stream attaches can lose the initial value."""
session = _SmokeSession(attach_ack=attach_ack)
async def fake_connect(options, **_kwargs):
return _SmokeClient(session)
monkeypatch.setattr(commands_module.GatewayClient, "connect", fake_connect)
result = CliRunner().invoke(
main,
["smoke", "--plaintext", "--item", "Tag", "--max-events", "1", "--timeout", "2", "--json"],
)
assert result.exit_code == 0, result.output
assert session.calls.index("stream_events") < session.calls.index("advise")
assert session.emit_requested is attach_ack
payload = json.loads(result.output)
assert [event["workerSequence"] for event in payload["events"]] == ["7"]