151 lines
9.2 KiB
Python
151 lines
9.2 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
|
|
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
|
state.update(tip=False,closing=closed)
|
|
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)
|
|
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):
|
|
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
|