Files
WoW-Hybrid-gateway/tests/windows_owned_bootstrap_resume_test.py
praxisandClaude Fable 5.2 7f2139d8d0 Offline test fixtures
883 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

70 lines
6.1 KiB
Python

"""Focused owned startup299 readiness and explicit same-process continuation."""
import json,struct,sys,tempfile,unittest
from pathlib import Path
from types import SimpleNamespace as N
from unittest.mock import patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
import windows_native_bootstrap as B
def winerror(n):
e=OSError('synthetic startup snapshot error');e.winerror=n;return e
class LoadThreadObservation(unittest.TestCase):
def test_completed_thread_return_is_saved_before_close_without_claiming_module(self):
for value in (0,0xc0000409):
with self.subTest(exit_dword=value):
calls=[];pending=[]
def create(*args):B.C.cast(args[-1],B.C.POINTER(B.W.DWORD)).contents.value=7;return 99
def exit_code(handle,out):
self.assertNotIn('close',calls);B.C.cast(out,B.C.POINTER(B.W.DWORD)).contents.value=value;calls.append('exit');return 1
k=N(VirtualAllocEx=lambda *a:2048,CreateRemoteThread=create,WaitForSingleObject=lambda *a:0,
GetExitCodeThread=exit_code,CloseHandle=lambda *a:calls.append('close'),
VirtualFreeEx=lambda *a:(calls.append('free')or 1))
api=N(k=k,checked=lambda x:self.assertTrue(x),write=lambda *a:None,loader=lambda pid:4096,modules=lambda pid:[])
with self.assertRaisesRegex(ValueError,'Exact remote module identity unavailable'):B.inject(api,5,77,Path('bridge.dll'),pending)
self.assertEqual(api._last_load_attempt['exit_dword'],value);self.assertFalse(api._last_load_attempt['exact_module_present'])
self.assertFalse(api._last_load_attempt['full_width_module_handle_observed']);self.assertFalse(api._last_load_attempt['remote_last_error_observed'])
self.assertEqual(calls,['exit','close','free']);self.assertEqual(pending,[])
class Wait(unittest.TestCase):
def fake(self,events,closed=False,deadline=1):
api=B.Kernel.__new__(B.Kernel);now=[0];calls=[]
def snap(pid):
calls.append(pid);v=events.pop(0)if len(events)>1 else events[0]
if isinstance(v,Exception):raise v
return v
api._module_snapshot=snap;api.k=N(WaitForSingleObject=lambda h,ms:0 if closed else 258);api.identity=lambda h:(123,'owned');api._startup_owner=dict(pid=77,process=5,identity=(123,'owned'),deadline=deadline)
clock=N(monotonic=lambda:now[0],sleep=lambda n:now.__setitem__(0,now[0]+n));return api,clock,calls
def test_transient299and24_then_one_success(self):
rows=[dict(base=1,size=2,path='owned')];api,clock,calls=self.fake([winerror(299),winerror(24),rows])
with patch.object(B,'time',clock):self.assertEqual(api.modules(77),rows)
self.assertEqual(calls,[77]*3);self.assertIs(api._last_modules,rows)
def test_deadline_and_owned_exit_are_terminal(self):
for closed,expected in [(False,TimeoutError),(True,RuntimeError)]:
api,clock,calls=self.fake([winerror(299)],closed=closed,deadline=.2)
with patch.object(B,'time',clock),self.assertRaises(expected):api.modules(77)
self.assertLessEqual(len(calls),3)
def test_no_general_snapshot_retry_without_owned_startup(self):
api,clock,calls=self.fake([winerror(299)]);api._startup_owner=None
with self.assertRaises(OSError):api.modules(77)
self.assertEqual(len(calls),1)
class SameProcess(unittest.TestCase):
def test_explicit_resume_uses_same_owner_no_create_auth_or_held_buffer_free(self):
with tempfile.TemporaryDirectory()as d:
r=Path(d);(r/'compat').mkdir();(r/'build').mkdir();(r/'runtime').mkdir();(r/'compat/native-engine-template.json').write_text('{}')
profile=dict(schema=1,backend_transport='owned-stdio-ipc-v1')
for name in ['client','bridge','wire','backend','codec']:
p=r/'build'/(name+'.dll');p.write_bytes(name.encode());profile[name]=dict(path=str(p.relative_to(r)),sha256=B.digest(p))
worker=r/'build/windows-backend-host.exe';worker.write_bytes(b'worker');profile['backend_host']=dict(path='build/windows-backend-host.exe',sha256=B.digest(worker));(r/'compat/windows-native.json').write_text(json.dumps(profile))
m=dict(windows_native_bootstrap=True,pid=77,starttime=123,image_path=str(r/'build/client.dll'),dll_sha256=profile['bridge']['sha256'],bootstrap_handoff=False,credentials_submitted=False,loader_allocations_held_until_process_exit=1,wire_unix_library={})
for key,name in [('core','backend'),('wire_unix','backend'),('source_codec','codec')]:m['wire_unix_library'].update({key+'_sha256':profile[name]['sha256'],key+'_path':str(r/profile[name]['path'])})
(r/'runtime/windows-bootstrap-failure.json').write_text(json.dumps(m));calls=[];wire=dict(base=0x180000000,size=1000,path=str(r/'build/wire.dll'));bridge=dict(base=0x190000000,size=1000,path=str(r/'build/bridge.dll'));modules=[wire,bridge]
def forbidden(*a):raise AssertionError('CreateProcess/auth/termination/unknown buffer free must not occur')
api=N(k=N(OpenProcess=lambda *a:calls.append(('open',a[-1]))or 501,WaitForSingleObject=lambda *a:258,CloseHandle=lambda h:calls.append(('close',h)),CreateProcessW=forbidden,TerminateProcess=forbidden,VirtualFreeEx=forbidden),identity=lambda h:(123,str(r/'build/client.dll')),checked=lambda x:None,read=lambda *a:struct.pack('<II',1,1080)+bytes(48))
def inject(*a):
name=a[3].name;calls.append(('inject',a[2],name));api._last_modules=[bridge]if name=='bridge.dll'else modules;return bridge if name=='bridge.dll'else wire
snapshot=dict(status='CURRENT_OWNED_MODULE_SNAPSHOT_PASS',pid=77,starttime=123,modules=[dict(base=1,size=1000,path='/kernel.dll')])
with patch.object(B,'os',N(name='nt',environ={})),patch.object(B,'pe_exports',return_value={'gw_wire_frame_data':16}),patch.object(B,'inject',side_effect=inject):
owned=B.resume_owned(r,77,123,module_snapshot=snapshot,_api=api)
self.assertEqual(calls,[('open',77),('inject',77,'bridge.dll'),('inject',77,'wire.dll'),('close',501)]);self.assertEqual(owned['pid'],77);self.assertFalse(owned['authentication_attempted']);meta=json.loads((r/'runtime/native-engine-pe.json').read_text());self.assertFalse(meta['resumed_owned_bootstrap']['new_process_created']);self.assertEqual(meta['resumed_owned_bootstrap']['previous_held_loader_allocations'],1)
with patch.object(B,'os',N(name='nt',environ={})),patch.object(B,'pe_exports',return_value={'gw_wire_frame_data':16}),self.assertRaises(ValueError):B.resume_owned(r,78,123,_api=api)
if __name__=='__main__':unittest.main()