test_patch_app_reporter.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import ast
  2. import json
  3. import os
  4. from pathlib import Path
  5. import tempfile
  6. import unittest
  7. import importlib.util
  8. from unittest.mock import patch
  9. spec = importlib.util.spec_from_file_location("patch_app_reporter", Path(__file__).resolve().parents[1] / "skills/container-provision-job/patch_app_reporter.py")
  10. module = importlib.util.module_from_spec(spec)
  11. spec.loader.exec_module(module)
  12. patch_text = module.patch_text
  13. class ReporterPatchTests(unittest.TestCase):
  14. def source(self):
  15. return '''def _heartbeat_once(jitter):
  16. try:
  17. fields = {"heartbeatAt": {"__type": "Date", "iso": _now_iso()}}
  18. return _push_with_sessions(fields)
  19. except Exception:
  20. return False
  21. def register(ctx):
  22. _start_heartbeat()
  23. '''
  24. def test_keeps_business_status_out_of_heartbeat(self):
  25. updated = patch_text(self.source())
  26. ast.parse(updated)
  27. self.assertIn('_start_app_channels()', updated)
  28. self.assertIn('fields["channels"]', updated)
  29. self.assertNotIn('fields["status"]', updated)
  30. self.assertNotIn('MATRIX_PASSWORD', updated)
  31. self.assertNotIn('FMODE_SESSION_TOKEN', updated)
  32. sent = []
  33. scope = {"_now_iso": lambda: "2026-11-27T00:00:00Z", "json": __import__("json"),
  34. "_push_with_sessions": lambda fields: sent.append(fields) or True}
  35. exec(updated, scope)
  36. scope["_fmode_channel_snapshot"] = lambda: {"matrix": True}
  37. self.assertTrue(scope["_heartbeat_once"](0))
  38. self.assertEqual(set(sent[0]), {"heartbeatAt", "channels"})
  39. def test_idempotent(self):
  40. updated = patch_text(self.source())
  41. self.assertEqual(patch_text(updated), updated)
  42. def test_refuses_partial_patch(self):
  43. updated = patch_text(self.source())
  44. incomplete = updated.replace(' _start_app_channels()\n', '')
  45. with self.assertRaisesRegex(ValueError, "incomplete App-channel patch"):
  46. patch_text(incomplete)
  47. def test_channel_snapshot_reads_the_persistent_gateway_state(self):
  48. updated = patch_text(self.source())
  49. with tempfile.TemporaryDirectory() as temp:
  50. Path(temp, "gateway_state.json").write_text(json.dumps({
  51. "platforms": {"matrix": {"state": "connected"}},
  52. }), encoding="utf-8")
  53. scope = {}
  54. with patch.dict(os.environ, {
  55. "HERMES_HOME": temp,
  56. "MATRIX_HOMESERVER": "https://matrix.fmode.cn",
  57. "MATRIX_USER_ID": "@agent:fmode.cn",
  58. }, clear=False):
  59. exec(updated, scope)
  60. channels = scope["_fmode_channel_snapshot"]()
  61. self.assertEqual(channels["matrix"], True)
  62. self.assertEqual(channels["matrixConfig"]["channelState"], "connected")
  63. self.assertEqual(channels["matrixConfig"]["userId"], "@agent:fmode.cn")
  64. self.assertNotIn("MATRIX_PASSWORD", channels)
  65. self.assertNotIn("FMODE_SESSION_TOKEN", channels)
  66. def test_startup_channel_registration_retries_until_matrix_is_connected(self):
  67. updated = patch_text(self.source())
  68. sent = []
  69. logs = []
  70. snapshots = iter([{"matrix": False}, {"matrix": True, "matrixConfig": {"userId": "@agent:fmode.cn"}}])
  71. scope = {
  72. "_push_with_sessions": lambda fields: sent.append(fields) or True,
  73. "_log": logs.append,
  74. }
  75. exec(updated, scope)
  76. scope["_fmode_channel_snapshot"] = lambda: next(snapshots)
  77. class ImmediateThread:
  78. def __init__(self, *, target, name, daemon):
  79. self.target = target
  80. self.name = name
  81. self.daemon = daemon
  82. def start(self):
  83. self.target()
  84. with patch("threading.Thread", ImmediateThread), patch("time.sleep", lambda _seconds: None):
  85. scope["_start_app_channels"]()
  86. self.assertEqual(len(sent), 1)
  87. self.assertEqual(set(sent[0]), {"channels"})
  88. self.assertIn("app matrix channels registered", logs)
  89. def test_refuses_unknown_source(self):
  90. with self.assertRaises(ValueError):
  91. patch_text("def register(ctx):\n pass\n")
  92. def test_heartbeat_starts_once_immediately_then_uses_configured_jitter(self):
  93. scope = {"_log": lambda _: None}
  94. exec(patch_text(self.source()), scope)
  95. threads, sent, sleeps = [], [], []
  96. class CapturedThread:
  97. def __init__(self, *, target, name, daemon):
  98. self.target = target
  99. threads.append(self)
  100. def start(self):
  101. pass
  102. class StopAfterFirstInterval(Exception):
  103. pass
  104. def sleep(seconds):
  105. sleeps.append(seconds)
  106. raise StopAfterFirstInterval()
  107. scope["_heartbeat_once"] = lambda jitter: sent.append(jitter)
  108. with patch.dict(os.environ, {"AGENT_STATUS_ENABLED": "true", "AGENT_STATUS_HEARTBEAT": "3600",
  109. "AGENT_STATUS_JITTER": "900"}), \
  110. patch("threading.Thread", CapturedThread), patch("random.uniform", return_value=900), \
  111. patch("time.sleep", side_effect=sleep):
  112. scope["_start_fmode_heartbeat"]()
  113. scope["_start_fmode_heartbeat"]()
  114. self.assertEqual(len(threads), 1)
  115. with self.assertRaises(StopAfterFirstInterval):
  116. threads[0].target()
  117. self.assertEqual(sent, [0])
  118. self.assertEqual(sleeps, [4500])
  119. def test_explicitly_disabled_heartbeat_does_not_start_a_thread(self):
  120. scope = {"_log": lambda _: None}
  121. exec(patch_text(self.source()), scope)
  122. with patch.dict(os.environ, {"AGENT_STATUS_ENABLED": "false"}), patch("threading.Thread") as thread:
  123. scope["_start_fmode_heartbeat"]()
  124. thread.assert_not_called()
  125. def test_refuses_heartbeat_that_overwrites_running_turn(self):
  126. source = self.source().replace(" return _push_with_sessions(fields)",
  127. ' fields["status"] = "idle"\n return _push_with_sessions(fields)')
  128. with self.assertRaisesRegex(ValueError, "business state"):
  129. patch_text(source)
  130. if __name__ == '__main__':
  131. unittest.main()