test_onboarding_runtime.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. """No-network regression of actual packaged hooks and atomic media patch recovery."""
  2. import hashlib
  3. import importlib.util
  4. import json
  5. import os
  6. from pathlib import Path
  7. import sys
  8. import tempfile
  9. import time
  10. from types import SimpleNamespace
  11. import unittest
  12. from unittest.mock import patch
  13. ROOT = Path(__file__).resolve().parents[2]
  14. RUNTIME = ROOT / 'cloud/onboarding/runtime'
  15. def load(name, path):
  16. spec = importlib.util.spec_from_file_location(name, path)
  17. module = importlib.util.module_from_spec(spec)
  18. spec.loader.exec_module(module)
  19. return module
  20. class DeliveryReuseTests(unittest.TestCase):
  21. def setUp(self):
  22. self.temp = tempfile.TemporaryDirectory()
  23. self.addCleanup(self.temp.cleanup)
  24. self.root = Path(self.temp.name)
  25. self.file = self.root / 'shared-result.md'
  26. self.file.write_text('same result')
  27. self.module = load('delivery_under_test', RUNTIME / 'scripts/fmode-deliverable-hook.py')
  28. self.module.log = lambda text: None
  29. self.module._thread_root = lambda: '$thread-B'
  30. self.module._resolve_agent_id = lambda: 'agent-fixture'
  31. self.module._remote_matches = lambda *args: True
  32. self.pusher_actions = []
  33. def call(params):
  34. self.pusher_actions.append(params['action'])
  35. if params['action'] != 'list':
  36. raise AssertionError('Historical content must not create or upload a new artifact')
  37. return {'deliverables': [{'id': 'old-A', 'artifacts': [{'name': self.file.name, 'url': 'https://s3.fmode.cn/shared.md'}]}]}
  38. self.module._load_pusher = lambda: SimpleNamespace(call=call)
  39. self.registrations = [{'id': 'file-A', 'roomId': '!room-A', 'agentId': 'agent-fixture'}]
  40. self.register_calls = []
  41. def hub(params):
  42. if params['action'] == 'listByUrl':
  43. return {'count': len(self.registrations), 'files': list(self.registrations)}
  44. self.register_calls.append(params)
  45. self.registrations.append({'id': 'file-B', 'roomId': params['roomId'], 'agentId': params['agentId']})
  46. return {'code': 200, 'id': 'file-B'}
  47. self.module._hub_call = hub
  48. self.env = patch.dict(os.environ, {'HERMES_SESSION_CHAT_ID': '!room-B'})
  49. self.env.start()
  50. self.addCleanup(self.env.stop)
  51. def run_upload(self):
  52. return self.module.upload_and_register([{'path': str(self.file)}], 'fixture', '')
  53. def test_room_B_reuses_bytes_but_registers_its_own_context(self):
  54. result = self.run_upload()[0]
  55. self.assertTrue(result['ok'])
  56. self.assertEqual(result['hub']['id'], 'file-B')
  57. self.assertEqual(result['sha256'], hashlib.sha256(self.file.read_bytes()).hexdigest())
  58. self.assertEqual(self.register_calls[0]['roomId'], '!room-B')
  59. self.assertEqual(self.register_calls[0]['threadRoot'], '$thread-B')
  60. self.assertEqual(self.pusher_actions, ['list'])
  61. def test_room_B_second_run_does_not_upload_or_register_again(self):
  62. self.run_upload()
  63. self.run_upload()
  64. self.assertEqual(len(self.register_calls), 1)
  65. self.assertEqual(self.pusher_actions, ['list', 'list'])
  66. def test_failed_reuse_registration_does_not_start_duplicate_upload(self):
  67. original = self.module._hub_call
  68. self.module._hub_call = lambda p: original(p) if p['action'] == 'listByUrl' else {'code': 500}
  69. result = self.run_upload()[0]
  70. self.assertFalse(result['ok'])
  71. self.assertEqual(result['detail'], 'reuse-register-failed')
  72. self.assertEqual(self.pusher_actions, ['list'])
  73. @unittest.skipIf(os.name == 'nt', 'real notifier is executed inside supported Linux image')
  74. def test_slow_notifier_does_not_block_hook_and_receives_complete_payload(self):
  75. receipt = self.root / 'notice-receipt.json'
  76. notifier = self.root / 'notice.py'
  77. notifier.write_text('import sys,time,json,pathlib\npayload=json.load(sys.stdin)\ntime.sleep(1.2)\npathlib.Path(' + repr(str(receipt)) + ').write_text(json.dumps(payload))\n')
  78. self.module.NOTICE_SCRIPT = notifier
  79. payload = {'tool_name': 'terminal', 'text': 'notice fixture ' * 10000}
  80. start = time.monotonic()
  81. self.module._spawn_process_notice(payload)
  82. self.assertLess(time.monotonic() - start, 0.8)
  83. deadline = time.monotonic() + 4
  84. while not receipt.exists() and time.monotonic() < deadline:
  85. time.sleep(0.03)
  86. self.assertEqual(json.loads(receipt.read_text()), payload)
  87. class MediaPatchTests(unittest.TestCase):
  88. def setUp(self):
  89. self.module = load('media_under_test', RUNTIME / '.fmode-media-patch/patch_spec.py')
  90. def test_malformed_or_incomplete_marker_is_not_success(self):
  91. for source in ['_is_allowed_media_url\ndef broken(', '_is_allowed_media_url = True\n']:
  92. with self.subTest(source=source), self.assertRaises((SyntaxError, ValueError)):
  93. self.module.build(source)
  94. def test_complete_media_patch_is_idempotent(self):
  95. m = self.module
  96. source = 'import logging\n\nclass MatrixAdapter:\n async def _download_and_cache_media(self, url, event_id):\n' + m.A1 + '\n if True:\n' + m.A2 + '\n' + m.A3 + '\n'
  97. updated, _, already = m.build(source)
  98. self.assertFalse(already)
  99. again, _, already = m.build(updated)
  100. self.assertTrue(already)
  101. self.assertEqual(updated, again)
  102. def test_interrupted_replace_preserves_previous_adapter(self):
  103. with tempfile.TemporaryDirectory() as directory:
  104. target = Path(directory) / 'adapter.py'
  105. target.write_text('value = 1\n')
  106. with patch.object(self.module.os, 'replace', side_effect=OSError('simulated interruption')):
  107. with self.assertRaises(OSError):
  108. self.module.write(str(target), 'value = 2\n')
  109. self.assertEqual(target.read_text(), 'value = 1\n')
  110. self.assertEqual(list(Path(directory).glob('.fmode-media-*')), [])
  111. with self.assertRaises(SyntaxError):
  112. self.module.write(str(target), 'def broken(')
  113. self.assertEqual(target.read_text(), 'value = 1\n')
  114. if __name__ == '__main__':
  115. unittest.main()