| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- """No-network regression of actual packaged hooks and atomic media patch recovery."""
- import hashlib
- import importlib.util
- import json
- import os
- from pathlib import Path
- import sys
- import tempfile
- import time
- from types import SimpleNamespace
- import unittest
- from unittest.mock import patch
- ROOT = Path(__file__).resolve().parents[2]
- RUNTIME = ROOT / 'cloud/onboarding/runtime'
- def load(name, path):
- spec = importlib.util.spec_from_file_location(name, path)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
- class DeliveryReuseTests(unittest.TestCase):
- def setUp(self):
- self.temp = tempfile.TemporaryDirectory()
- self.addCleanup(self.temp.cleanup)
- self.root = Path(self.temp.name)
- self.file = self.root / 'shared-result.md'
- self.file.write_text('same result')
- self.module = load('delivery_under_test', RUNTIME / 'scripts/fmode-deliverable-hook.py')
- self.module.log = lambda text: None
- self.module._thread_root = lambda: '$thread-B'
- self.module._resolve_agent_id = lambda: 'agent-fixture'
- self.module._remote_matches = lambda *args: True
- self.pusher_actions = []
- def call(params):
- self.pusher_actions.append(params['action'])
- if params['action'] != 'list':
- raise AssertionError('Historical content must not create or upload a new artifact')
- return {'deliverables': [{'id': 'old-A', 'artifacts': [{'name': self.file.name, 'url': 'https://s3.fmode.cn/shared.md'}]}]}
- self.module._load_pusher = lambda: SimpleNamespace(call=call)
- self.registrations = [{'id': 'file-A', 'roomId': '!room-A', 'agentId': 'agent-fixture'}]
- self.register_calls = []
- def hub(params):
- if params['action'] == 'listByUrl':
- return {'count': len(self.registrations), 'files': list(self.registrations)}
- self.register_calls.append(params)
- self.registrations.append({'id': 'file-B', 'roomId': params['roomId'], 'agentId': params['agentId']})
- return {'code': 200, 'id': 'file-B'}
- self.module._hub_call = hub
- self.env = patch.dict(os.environ, {'HERMES_SESSION_CHAT_ID': '!room-B'})
- self.env.start()
- self.addCleanup(self.env.stop)
- def run_upload(self):
- return self.module.upload_and_register([{'path': str(self.file)}], 'fixture', '')
- def test_room_B_reuses_bytes_but_registers_its_own_context(self):
- result = self.run_upload()[0]
- self.assertTrue(result['ok'])
- self.assertEqual(result['hub']['id'], 'file-B')
- self.assertEqual(result['sha256'], hashlib.sha256(self.file.read_bytes()).hexdigest())
- self.assertEqual(self.register_calls[0]['roomId'], '!room-B')
- self.assertEqual(self.register_calls[0]['threadRoot'], '$thread-B')
- self.assertEqual(self.pusher_actions, ['list'])
- def test_room_B_second_run_does_not_upload_or_register_again(self):
- self.run_upload()
- self.run_upload()
- self.assertEqual(len(self.register_calls), 1)
- self.assertEqual(self.pusher_actions, ['list', 'list'])
- def test_failed_reuse_registration_does_not_start_duplicate_upload(self):
- original = self.module._hub_call
- self.module._hub_call = lambda p: original(p) if p['action'] == 'listByUrl' else {'code': 500}
- result = self.run_upload()[0]
- self.assertFalse(result['ok'])
- self.assertEqual(result['detail'], 'reuse-register-failed')
- self.assertEqual(self.pusher_actions, ['list'])
- @unittest.skipIf(os.name == 'nt', 'real notifier is executed inside supported Linux image')
- def test_slow_notifier_does_not_block_hook_and_receives_complete_payload(self):
- receipt = self.root / 'notice-receipt.json'
- notifier = self.root / 'notice.py'
- 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')
- self.module.NOTICE_SCRIPT = notifier
- payload = {'tool_name': 'terminal', 'text': 'notice fixture ' * 10000}
- start = time.monotonic()
- self.module._spawn_process_notice(payload)
- self.assertLess(time.monotonic() - start, 0.8)
- deadline = time.monotonic() + 4
- while not receipt.exists() and time.monotonic() < deadline:
- time.sleep(0.03)
- self.assertEqual(json.loads(receipt.read_text()), payload)
- class MediaPatchTests(unittest.TestCase):
- def setUp(self):
- self.module = load('media_under_test', RUNTIME / '.fmode-media-patch/patch_spec.py')
- def test_malformed_or_incomplete_marker_is_not_success(self):
- for source in ['_is_allowed_media_url\ndef broken(', '_is_allowed_media_url = True\n']:
- with self.subTest(source=source), self.assertRaises((SyntaxError, ValueError)):
- self.module.build(source)
- def test_complete_media_patch_is_idempotent(self):
- m = self.module
- 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'
- updated, _, already = m.build(source)
- self.assertFalse(already)
- again, _, already = m.build(updated)
- self.assertTrue(already)
- self.assertEqual(updated, again)
- def test_interrupted_replace_preserves_previous_adapter(self):
- with tempfile.TemporaryDirectory() as directory:
- target = Path(directory) / 'adapter.py'
- target.write_text('value = 1\n')
- with patch.object(self.module.os, 'replace', side_effect=OSError('simulated interruption')):
- with self.assertRaises(OSError):
- self.module.write(str(target), 'value = 2\n')
- self.assertEqual(target.read_text(), 'value = 1\n')
- self.assertEqual(list(Path(directory).glob('.fmode-media-*')), [])
- with self.assertRaises(SyntaxError):
- self.module.write(str(target), 'def broken(')
- self.assertEqual(target.read_text(), 'value = 1\n')
- if __name__ == '__main__':
- unittest.main()
|