| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200 |
- import ast
- import json
- import os
- from pathlib import Path
- import tempfile
- import unittest
- import importlib.util
- from unittest.mock import patch
- spec = importlib.util.spec_from_file_location("patch_app_reporter", Path(__file__).resolve().parents[1] / "skills/container-provision-job/patch_app_reporter.py")
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- patch_text = module.patch_text
- class ReporterPatchTests(unittest.TestCase):
- def source(self):
- return '''def _heartbeat_once(jitter):
- try:
- fields = {"heartbeatAt": {"__type": "Date", "iso": _now_iso()}}
- return _push_with_sessions(fields)
- except Exception:
- return False
- def register(ctx):
- _start_heartbeat()
- '''
- def test_keeps_business_status_out_of_heartbeat(self):
- updated = patch_text(self.source())
- ast.parse(updated)
- self.assertIn('_start_app_channels()', updated)
- self.assertIn('fields["channels"]', updated)
- self.assertNotIn('fields["status"]', updated)
- self.assertNotIn('MATRIX_PASSWORD', updated)
- self.assertNotIn('FMODE_SESSION_TOKEN', updated)
- sent = []
- scope = {"_now_iso": lambda: "2026-11-27T00:00:00Z", "json": __import__("json"),
- "_push_with_sessions": lambda fields: sent.append(fields) or True}
- exec(updated, scope)
- scope["_fmode_channel_snapshot"] = lambda: {"matrix": True}
- self.assertTrue(scope["_heartbeat_once"](0))
- self.assertEqual(set(sent[0]), {"heartbeatAt", "channels"})
- def test_idempotent(self):
- updated = patch_text(self.source())
- self.assertEqual(patch_text(updated), updated)
- def test_refuses_partial_patch(self):
- updated = patch_text(self.source())
- incomplete = updated.replace(' _start_app_channels()\n', '')
- with self.assertRaisesRegex(ValueError, "incomplete App-channel patch"):
- patch_text(incomplete)
- def test_channel_snapshot_reads_the_persistent_gateway_state(self):
- updated = patch_text(self.source())
- with tempfile.TemporaryDirectory() as temp:
- Path(temp, "gateway_state.json").write_text(json.dumps({
- "platforms": {"matrix": {"state": "connected"}},
- }), encoding="utf-8")
- scope = {}
- with patch.dict(os.environ, {
- "HERMES_HOME": temp,
- "MATRIX_HOMESERVER": "https://matrix.fmode.cn",
- "MATRIX_USER_ID": "@agent:fmode.cn",
- }, clear=False):
- exec(updated, scope)
- channels = scope["_fmode_channel_snapshot"]()
- self.assertEqual(channels["matrix"], True)
- self.assertEqual(channels["matrixConfig"]["channelState"], "connected")
- self.assertEqual(channels["matrixConfig"]["userId"], "@agent:fmode.cn")
- self.assertNotIn("MATRIX_PASSWORD", channels)
- self.assertNotIn("FMODE_SESSION_TOKEN", channels)
- def test_startup_channel_registration_retries_until_matrix_is_connected(self):
- updated = patch_text(self.source())
- sent = []
- logs = []
- snapshots = iter([{"matrix": False}, {"matrix": True, "matrixConfig": {"userId": "@agent:fmode.cn"}}])
- scope = {
- "_push_with_sessions": lambda fields: sent.append(fields) or True,
- "_log": logs.append,
- }
- exec(updated, scope)
- scope["_fmode_channel_snapshot"] = lambda: next(snapshots)
- class ImmediateThread:
- def __init__(self, *, target, name, daemon):
- self.target = target
- self.name = name
- self.daemon = daemon
- def start(self):
- self.target()
- with patch("threading.Thread", ImmediateThread), patch("time.sleep", lambda _seconds: None):
- scope["_start_app_channels"]()
- self.assertEqual(len(sent), 1)
- self.assertEqual(set(sent[0]), {"channels"})
- self.assertIn("app matrix channels registered", logs)
- def test_refuses_unknown_source(self):
- with self.assertRaises(ValueError):
- patch_text("def register(ctx):\n pass\n")
- def test_heartbeat_starts_once_immediately_then_uses_configured_jitter(self):
- scope = {"_log": lambda _: None}
- exec(patch_text(self.source()), scope)
- threads, sent, sleeps = [], [], []
- class CapturedThread:
- def __init__(self, *, target, name, daemon):
- self.target = target
- threads.append(self)
- def start(self):
- pass
- class StopAfterFirstInterval(Exception):
- pass
- def sleep(seconds):
- sleeps.append(seconds)
- raise StopAfterFirstInterval()
- scope["_heartbeat_once"] = lambda jitter: sent.append(jitter)
- with patch.dict(os.environ, {"AGENT_STATUS_ENABLED": "true", "AGENT_STATUS_HEARTBEAT": "3600",
- "AGENT_STATUS_JITTER": "900"}), \
- patch("threading.Thread", CapturedThread), patch("random.uniform", return_value=900), \
- patch("time.sleep", side_effect=sleep):
- scope["_start_fmode_heartbeat"]()
- scope["_start_fmode_heartbeat"]()
- self.assertEqual(len(threads), 1)
- with self.assertRaises(StopAfterFirstInterval):
- threads[0].target()
- self.assertEqual(sent, [0])
- self.assertEqual(sleeps, [4500])
- def test_explicitly_disabled_heartbeat_does_not_start_a_thread(self):
- scope = {"_log": lambda _: None}
- exec(patch_text(self.source()), scope)
- with patch.dict(os.environ, {"AGENT_STATUS_ENABLED": "false"}), patch("threading.Thread") as thread:
- scope["_start_fmode_heartbeat"]()
- thread.assert_not_called()
- def test_refuses_heartbeat_that_overwrites_running_turn(self):
- source = self.source().replace(" return _push_with_sessions(fields)",
- ' fields["status"] = "idle"\n return _push_with_sessions(fields)')
- with self.assertRaisesRegex(ValueError, "business state"):
- patch_text(source)
- def _snapshot_from(self, code, platforms, extra_env=None):
- with tempfile.TemporaryDirectory() as temp:
- Path(temp, "gateway_state.json").write_text(json.dumps({"platforms": platforms}), encoding="utf-8")
- env = {"HERMES_HOME": temp, "MATRIX_USER_ID": "@agent:fmode.cn", **(extra_env or {})}
- scope = {}
- with patch.dict(os.environ, env, clear=False):
- exec(code, scope)
- return scope["_fmode_channel_snapshot"]()
- def _snapshot_sources(self):
- plugin = Path(__file__).resolve().parents[1] / "onboarding/runtime/plugins/plugin-active-reporter/__init__.py"
- text = plugin.read_text(encoding="utf-8")
- start = text.index("def _fmode_channel_snapshot():")
- shipped = text[start:text.index("\n\n\ndef _start_app_channels", start)]
- return {"patch": patch_text(self.source()), "bundle": shipped}
- def test_snapshot_reports_wecom_and_matrix_together(self):
- for name, code in self._snapshot_sources().items():
- with self.subTest(source=name):
- channels = self._snapshot_from(code, {"matrix": {"state": "connected"}, "wecom": {"state": "connected"},
- "api_server": {"state": "connected"}},
- {"WECOM_BOT_ID": "bot-fixture", "WECOM_SECRET": "never-report"})
- self.assertTrue(channels["matrix"])
- self.assertTrue(channels["wecom"])
- self.assertEqual(channels["wecomBotId"], "bot-fixture")
- self.assertEqual(channels["wecomConfig"]["channelState"], "connected")
- self.assertEqual(channels["platformStates"], {"api_server": "connected", "matrix": "connected", "wecom": "connected"})
- self.assertNotIn("never-report", json.dumps(channels))
- def test_snapshot_without_wecom_does_not_claim_wecom(self):
- for name, code in self._snapshot_sources().items():
- with self.subTest(source=name):
- with patch.dict(os.environ, {}, clear=False):
- os.environ.pop("WECOM_BOT_ID", None)
- channels = self._snapshot_from(code, {"matrix": {"state": "connected"}})
- self.assertNotIn("wecom", channels)
- self.assertTrue(channels["matrix"])
- def test_snapshot_reports_disconnected_wecom_as_false(self):
- for name, code in self._snapshot_sources().items():
- with self.subTest(source=name):
- channels = self._snapshot_from(code, {"matrix": {"state": "connected"}, "wecom": {"state": "disconnected"}})
- self.assertFalse(channels["wecom"])
- self.assertTrue(channels["matrix"])
- if __name__ == '__main__':
- unittest.main()
|