Files
cbb-refresh-verify-795/tests/test_registered_startup_release.py
T

304 lines
18 KiB
Python

from contextlib import nullcontext
import json
from pathlib import Path
import pytest
from cbb_refresh_verify import diagnostic_open, residual_sessions as sessions, session_record
from test_cancelled_loaded_startup import loaded_fixture
def registered_fixture(tmp_path,monkeypatch,*,closed=False,obstacle=''):
import win32con,win32event
kernel_wait=win32event.WaitForSingleObject
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
state.update(tip=False,closing=closed)
state['observer_requests']=[]
monkeypatch.setattr(session_record,'handoff_session',lambda path,**kw:
state['observer_requests'].append((path,list(messages),kw)))
job.update(operation_id='verify-old',operation='verify',library=job['lmc_file'],block='IP101GR',
session_record_path=str(tmp_path/'session.json'),interactive_input=False)
state['prelaunch_baseline']=job['diagnostic_log_baseline']
job.pop('diagnostic_log_baseline') # Old builds never persisted this; do not invent it.
identity=dict(pid=12,created_handle='native-created',image=records[0][1],owner_sid='current',session_id=1)
worker=dict(pid=11,created_handle='worker-created',image='C:/App/CbbRefreshVerify.exe',owner_sid='current',session_id=1)
session_record.write_session_record(tmp_path/'session.json',dict(operation_id='verify-old',operation='verify',
library=job['library'],block=job['block'],desktop=job['desktop'],cancel_signal=job['cancel_signal'],
processes=[dict(role='worker',**worker)],resource_scope=dict(scope_state='DECLARED',
library=job['library'],operation_id='verify-old',projects=[job['project']])))
session_record.write_session_record(tmp_path/'worker-state.json',dict(operation_id='verify-old',
phase='UNCONFIRMED',processes=[dict(role='native',**identity)]))
result=dict(status='CANCELLED',error_stage='PCB_STARTING',safe_to_continue=False,
write_outcome=dict(save_state='UNKNOWN'))
events=[dict(stage='pcb_baseline',pids=[]),dict(stage='pcb_worker_started',pcb_pid=12,command=records[0][2])]
if closed:events.append(dict(stage='startup_close_requested',pcb_pid=12,hwnd=100))
if obstacle=='ordinary':job['diagnostic_only']=False
if obstacle=='interactive':job['interactive_input']=True
if obstacle=='other_project':job['project']=str(tmp_path/'Other.prj')
if obstacle=='wrong_operation':job['operation_id']='other'
if obstacle=='missing_cancel':Path(job['cancel_signal']).unlink()
if obstacle=='save':(tmp_path/'save.log').write_text('SAVE_ENTERED')
if obstacle=='save_event':events.append(dict(stage='save_start'))
if obstacle=='not_cancelled':result['status']='FAIL'
if obstacle=='wrong_stage':result['error_stage']='SAVING'
(tmp_path/'request.json').write_text(json.dumps(job))
(tmp_path/'result.json').write_text(json.dumps(result))
(tmp_path/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
row=dict(pid=12,name='ExpeditionPCB.exe',command=records[0][2],created='native-created',
executable=identity['image'],library=job['library'],scope_confirmed=True,runtime_phase='UNCONFIRMED',
session_records=[dict(path=str(tmp_path/'session.json'),operation_id='verify-old')],**{k:v for k,v in identity.items() if k!='pid'})
if obstacle=='foreign_identity':row['created_handle']='replacement'
if obstacle=='unscoped':row['scope_confirmed']=False
monkeypatch.setattr(sessions,'_process_handle',lambda pid,**kw:nullcontext(pid))
monkeypatch.setattr(sessions,'_handle_identity',lambda handle:{k:v for k,v in (worker if handle==11 else identity).items() if k in ('created_handle','image')})
monkeypatch.setattr(sessions,'_force_ownership',lambda h,p:{'owner_sid':'current','session_id':1,'force_user_confirmed':True})
def wait(handle,ms):
if handle not in (11,12):return kernel_wait(handle,ms)
state['ticks']+=ms/1000
return win32con.WAIT_OBJECT_0 if handle==11 and obstacle!='live_worker' or handle==12 and not records else win32con.WAIT_TIMEOUT
monkeypatch.setattr(win32event,'WaitForSingleObject',wait)
monkeypatch.setattr(sessions,'time',diagnostic_open.time)
monkeypatch.setattr(sessions,'query_process_snapshot',lambda:[row])
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',lambda r:diagnostic_open._windows(r['pid']),raising=False)
monkeypatch.setattr(sessions,'_window_desktop',lambda *a,**kw:nullcontext())
monkeypatch.setattr(sessions,'_post_window_message',lambda w,h,p,m:__import__('win32gui').PostMessage(h,m,0,0))
monkeypatch.setattr(session_record,'active_write_records',lambda library:
[dict(operation_id='other-write' if obstacle=='other_write' else 'verify-old',phase='UNCONFIRMED')])
monkeypatch.setattr(diagnostic_open,'_load_evidence',lambda *a,**kw:
pytest.fail('legacy cleanup may not manufacture missing prelaunch log evidence'))
return job,row,records,messages,state
@pytest.mark.parametrize('closed',[False,True])
def test_normal_release_finishes_exact_registered_cancelled_startup_without_save_or_second_close(tmp_path,monkeypatch,closed):
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch,closed=closed)
original=(tmp_path/'result.json').read_bytes()
result=sessions._request_close(row)
assert result['release_status']=='RELEASED'
assert messages==([(31,245)] if closed else [(31,245),(100,16)])
assert not records and (tmp_path/'result.json').read_bytes()==original
@pytest.mark.parametrize('obstacle',['ordinary','interactive','other_project','wrong_operation','missing_cancel',
'save','save_event','not_cancelled','wrong_stage','foreign_identity','unscoped','live_worker','other_write'])
def test_registered_startup_release_rejects_partial_foreign_or_writing_evidence(tmp_path,monkeypatch,obstacle):
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch,obstacle=obstacle)
assert sessions._request_close(row)['release_status'] in ('WAITING','IDENTITY_CHANGED')
assert not messages and records
@pytest.mark.parametrize('error_code',[87,5])
def test_registered_worker_exit_requires_kernel_exit_or_missing_pid_not_access_denial(tmp_path,monkeypatch,error_code):
import pywintypes
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
original=sessions._process_handle
def open_process(pid,**kwargs):
if pid==11:raise pywintypes.error(error_code,'OpenProcess','worker probe')
return original(pid,**kwargs)
monkeypatch.setattr(sessions,'_process_handle',open_process)
result=sessions._request_close(row)
assert result['release_status']==('RELEASED' if error_code==87 else 'WAITING')
assert messages==([(31,245),(100,16)] if error_code==87 else [])
def test_completed_identity_snapshots_fit_existing_release_budget_without_duplicate_polling(tmp_path,monkeypatch):
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
def snapshot():
state['ticks']+=.4
return [row]
monkeypatch.setattr(sessions,'query_process_snapshot',snapshot)
assert sessions._request_close(row)['release_status']=='RELEASED'
assert messages==[(31,245),(100,16)] and state['ticks']<3
@pytest.mark.parametrize('change',['result','stop','identity'])
def test_legacy_no_rechecks_registered_state_after_fresh_windows(tmp_path,monkeypatch,change):
from threading import Event
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
stop=Event();reads=[]
original=sessions._legacy_diagnostic_windows
def windows(bound):
value=original(bound);reads.append(1)
if len(reads)==2:
if change=='result':(tmp_path/'result.json').write_text('{"status":"PASS"}')
if change=='stop':stop.set()
if change=='identity':row['created_handle']='replacement'
return value
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows)
assert sessions._request_close(row,stop=stop)['release_status']=='WAITING'
assert records and not messages
@pytest.mark.parametrize('frame_handle',[100,999])
def test_normal_release_clears_registered_late_tip_despite_historical_unknown_phase(tmp_path,monkeypatch,frame_handle):
import win32con,win32gui
from copy import deepcopy
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch,closed=True)
state['tip']=True
windows=[dict(hwnd=frame_handle,**{'class':'Afx:main'},title='Expedition PCB',enabled=False,
desktop=job['desktop'],children=[],documents=[]),
dict(hwnd=200,**{'class':'#32770'},title='Tip of the Day',enabled=True,
desktop=job['desktop'],documents=[],children=[dict(hwnd=201,**{'class':'Button'},id=1,text='OK',enabled=True)])]
monkeypatch.setattr(sessions,'_process_windows',lambda pids:{12:deepcopy(windows)})
monkeypatch.setattr(win32gui,'GetWindow',lambda h,k:frame_handle if h==200 and k==win32con.GW_OWNER else 0)
def post(hwnd,message,*args):messages.append((hwnd,message));records.clear()
monkeypatch.setattr(win32gui,'PostMessage',post)
result=sessions._request_close(row)
assert result['release_status']==('RELEASED' if frame_handle==100 else 'WAITING')
assert messages==([(201,245)] if frame_handle==100 else [])
def test_registered_cleanup_cannot_act_from_another_windows_user_session(tmp_path,monkeypatch):
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
monkeypatch.setattr(sessions,'_force_ownership',lambda h,p:
dict(owner_sid='current',session_id=1,force_user_confirmed=False))
assert sessions._request_close(row)['release_status']=='WAITING'
assert not messages and records
assert not state['observer_requests']
@pytest.mark.parametrize('obstacle',['','progress','stop','unknown'])
def test_one_legacy_intent_keeps_diagnostic_budget_across_no_ready_and_close(tmp_path,monkeypatch,obstacle):
from threading import Event
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
stop=Event();original=sessions._legacy_diagnostic_windows
def windows(bound):
value=original(bound)
if state['declined']:
if obstacle=='stop' and state['ticks']>=4:stop.set()
if state['ticks']<4 or obstacle=='progress':
value[0]['children'].append(dict(hwnd=123,**{'class':'msctls_progress32'},text='',visible=True))
if obstacle=='unknown':
value.append(dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown action',children=[]))
return value
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows)
result=sessions._request_close(row,stop=stop)
assert state['observer_requests'] and state['observer_requests'][0][1]==[]
assert state['observer_requests'][0][2].get('observe_only',False) is False
if not obstacle:
assert result['release_status']=='RELEASED' and not records
assert messages==[(31,245),(100,16)] and 4<=state['ticks']<5
else:
assert result['release_status'] in ('WAITING','CANCELLED') and records
assert messages==[(31,245)]
assert state['ticks']<5 if obstacle=='stop' else 30<=state['ticks']<30.2
def test_known_no_then_changing_ready_snapshot_revalidates_within_same_intent(tmp_path,monkeypatch):
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
original=sessions._legacy_diagnostic_windows;reads=[]
def windows(bound):
value=original(bound)
if state['declined']:
reads.append(1)
if len(reads)==2:value[0]['children'].append(dict(hwnd=124,**{'class':'Afx:tool'},text='settling',parent=100))
return value
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows)
assert sessions._request_close(row)['release_status']=='RELEASED'
assert messages==[(31,245),(100,16)] and not records
def test_proved_native_cleanup_uses_its_budget_instead_of_metadata_inactivity(tmp_path,monkeypatch):
from threading import Event,Timer
from cbb_refresh_verify.operation_queue import BatchTaskContext
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
ready,done=Event(),Event();original=sessions._legacy_diagnostic_windows
def windows(bound):
if state['declined']:assert ready.wait(1)
return original(bound)
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows)
timer=Timer(.25,ready.set);timer.start()
context=BatchTaskContext(str(row['library']))
def cleanup():
try:return sessions._request_close(row)
finally:done.set()
try:
result=context.run(cleanup,timeout_seconds=.08)
assert result['release_status']=='RELEASED' and messages==[(31,245),(100,16)]
finally:
ready.set();timer.join(1);assert done.wait(2)
def test_registered_cleanup_preserves_frame_with_an_additional_mdi_document(tmp_path,monkeypatch):
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
original=sessions._legacy_diagnostic_windows
def windows(bound):
value=original(bound)
value[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101))
return value
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',windows)
assert sessions._request_close(row)['release_status']=='WAITING'
assert records and not messages
@pytest.mark.parametrize('hidden_sibling',[None,False,True])
def test_real_legacy_adapter_keeps_hidden_documents_before_any_native_action(tmp_path,monkeypatch,hidden_sibling):
import win32con,win32gui,win32process
snapshot,adapter=sessions._process_windows,sessions._legacy_diagnostic_windows
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
monkeypatch.setattr(sessions,'_process_windows',snapshot)
monkeypatch.setattr(sessions,'_legacy_diagnostic_windows',adapter)
monkeypatch.setattr(sessions,'_process_threads',lambda pids:{12:[1]})
monkeypatch.setattr(sessions,'_thread_desktop_name',lambda tid:job['desktop'])
monkeypatch.setattr(sessions,'_desktop_windows',lambda desktop:[100,200] if not state['declined'] else [100])
classes={100:'Afx:main',101:'MDIClient',102:'Afx:document',103:'Afx:document',
200:'#32770',30:'Static',31:'Button',32:'Button'}
texts={100:'Expedition PCB - Reusable Block - [IP101GR]',101:'',102:'IP101GR',103:'Other',
200:'Expedition PCB',30:'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?',31:'&No',32:'&Yes'}
parents={101:100,102:101,103:101,30:200,31:200,32:200}
monkeypatch.setattr(win32process,'GetWindowThreadProcessId',lambda h:(1,12))
monkeypatch.setattr(win32gui,'GetClassName',lambda h:classes[h])
monkeypatch.setattr(win32gui,'GetWindowText',lambda h:texts[h])
monkeypatch.setattr(win32gui,'GetParent',lambda h:parents.get(h,0))
monkeypatch.setattr(win32gui,'GetDlgCtrlID',lambda h:{30:6172,31:7,32:6}.get(h,0))
monkeypatch.setattr(win32gui,'GetWindowRect',lambda h:(0,0,300,200))
monkeypatch.setattr(win32gui,'IsWindowVisible',lambda h:not (h==103 and hidden_sibling))
monkeypatch.setattr(win32gui,'IsWindowEnabled',lambda h:h!=100 or state['declined'])
monkeypatch.setattr(win32gui,'GetWindow',lambda h,k:102 if h==101 and k==win32con.GW_CHILD else 100 if h==200 and k==win32con.GW_OWNER else 0)
monkeypatch.setattr(win32gui,'EnumChildWindows',lambda h,fn,arg:[fn(c,arg) for c in ([101,102]+([103] if hidden_sibling is not None else []) if h==100 else [30,31,32])])
result=sessions._request_close(row)
if hidden_sibling is None:
assert result['release_status']=='RELEASED',result
assert not records and messages==[(31,245),(100,16)]
else:
assert result['release_status']=='WAITING',result
assert records and not messages
@pytest.mark.parametrize('closed',[False,True])
@pytest.mark.parametrize('delayed_tip',[False,True])
def test_legacy_tip_continues_to_loaded_cleanup_only_without_prior_close(tmp_path,monkeypatch,closed,delayed_tip):
import win32con,win32gui
from copy import deepcopy
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch,closed=closed)
state['tip']=True
tip_windows=[dict(hwnd=100,**{'class':'Afx:main'},title='Expedition PCB',enabled=False,
desktop=job['desktop'],children=[],documents=[]),
dict(hwnd=200,**{'class':'#32770'},title='Tip of the Day',enabled=True,
desktop=job['desktop'],documents=[],children=[dict(hwnd=201,**{'class':'Button'},id=1,text='OK',enabled=True)])]
def windows(pids):
state['ticks']+=.02
if delayed_tip and state.get('tip_posted') and state['ticks']>=.3:
state['tip']=False
if closed:records.clear()
return {12:deepcopy(tip_windows) if state['tip'] else []}
monkeypatch.setattr(sessions,'_process_windows',windows)
monkeypatch.setattr(win32gui,'GetWindow',lambda h,k:100 if h==200 and k==win32con.GW_OWNER else 0)
original=win32gui.PostMessage
def post(hwnd,message,*args):
original(hwnd,message,*args)
if hwnd==201:
if delayed_tip:state.update(tip=True,tip_posted=True)
elif closed:records.clear()
monkeypatch.setattr(win32gui,'PostMessage',post)
if delayed_tip and closed:
original_wait=__import__('win32event').WaitForSingleObject
def wait(handle,ms):
value=original_wait(handle,ms)
if state.get('tip_posted') and state['ticks']>=.3:records.clear()
return value
monkeypatch.setattr(__import__('win32event'),'WaitForSingleObject',wait)
assert sessions._request_close(row)['release_status']=='RELEASED'
assert messages==([(201,245)] if closed else [(201,245),(31,245),(100,16)])
assert not records and state['ticks']<30