883 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
390 lines
24 KiB
Python
390 lines
24 KiB
Python
#!/usr/bin/env python3
|
|
"""A disconnect modal must take precedence over the credential form underneath."""
|
|
from pathlib import Path
|
|
import re,sys
|
|
from contextlib import nullcontext
|
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
|
|
from client_session import classify,stable_login_retry
|
|
from client_ui import is_login_screen
|
|
from client_ui import pointer_step
|
|
assert pointer_step(0)==0
|
|
for delta in range(-1000,1001):
|
|
step=pointer_step(delta)
|
|
assert abs(step)<=12
|
|
assert not delta or step*delta>0
|
|
assert abs(step)<=abs(delta)
|
|
for initial in ((0,200),(200,0),(-31,78),(1919,-1079)):
|
|
x,y=initial
|
|
for _ in range(240):
|
|
if abs(x)+abs(y)<2:break
|
|
x-=pointer_step(x);y-=pointer_step(y)
|
|
else:raise AssertionError('Bounded relative pointer did not converge')
|
|
login='Email or phone Password Remember account Log in'
|
|
assert classify(login)=='login'
|
|
for adapted in ('Account Password','Account Name Password','Remember Account Password'):
|
|
assert classify(adapted)=='login'
|
|
assert classify('Disconnected '+adapted)=='disconnected'
|
|
assert is_login_screen(adapted)
|
|
for incomplete in ('Account','Password','Account Settings','Enter World Create Character'):
|
|
assert not is_login_screen(incomplete)
|
|
assert classify('Disconnected '+login)=='disconnected'
|
|
assert is_login_screen('Disconnected '+login) # Screenshot still counts as sensitive.
|
|
assert classify('Gatewaytest Enter World')=='loading-or-unknown'
|
|
assert classify('Gatewaytest Elwynn Forest Enter World')=='loading-or-unknown'
|
|
assert classify('Gatewaytest Northshire Valley Enter World')=='loading-or-unknown'
|
|
assert classify('Enter World Create Character')=='characters'
|
|
assert classify('Othername Elwynn Forest Enter World Create Character')=='characters'
|
|
assert classify('Othername Northshire Valley Enter World Create New Character')=='characters'
|
|
assert classify('Toggle Character List Elwynn Forest')=='loading-or-unknown'
|
|
assert classify('Toggle Character List Enter World')=='characters'
|
|
assert classify('Disconnected Toggle Character List Enter World')=='disconnected'
|
|
assert classify('Normal Select')=='ruleset'
|
|
assert classify('Choose Your Gameplay Ruleset Normal PvP Roleplay Hardcore')=='ruleset'
|
|
assert classify('Northshire Valley')=='world'
|
|
assert classify('Hall of Arms')=='world'
|
|
assert classify('Main Hall')=='world'
|
|
assert classify('Valley of Strength')=='world'
|
|
assert classify('The Drag')=='world' # Actual mounted Orgrimmar screenshot.
|
|
assert classify('The Drag Enter World Create Character')=='characters'
|
|
assert classify('Cenarion Hold')=='world' # Captured native flight arrival.
|
|
assert classify('Red Cloud Mesa')=='world' # Actual passive-loot fixture arrival.
|
|
assert classify('Red Cloud Mesa Enter World Create Character')=='characters'
|
|
assert classify(login+' Red Cloud Mesa')=='login'
|
|
assert classify('Disconnected Red Cloud Mesa')=='disconnected'
|
|
assert classify('Cenarion Hold Enter World Create Character')=='characters'
|
|
assert classify(login+' Cenarion Hold')=='login'
|
|
assert classify('Disconnected Cenarion Hold')=='disconnected'
|
|
assert classify('Valley of Strength Enter World Create Character')=='characters'
|
|
assert classify('Elwynn Forest')=='world'
|
|
assert classify('Goldshire')=='world' # Captured actual trainer scene.
|
|
assert classify('Booty Bay')=='world' # Actual imported Tauren world screenshot.
|
|
for cape in ('The Cape of Stranglethorn','The Cape of Strangl...'):
|
|
assert classify(cape)=='world' # Observed graveyard minimap, including truncation.
|
|
assert classify(login+' '+cape)=='login'
|
|
assert classify('Disconnected '+cape)=='disconnected'
|
|
assert classify(cape+' Enter World Create Character')=='characters'
|
|
assert classify('Booty Bay Enter World Create Character')=='characters'
|
|
assert classify(login+' Booty Bay')=='login'
|
|
assert classify('Disconnected Booty Bay')=='disconnected'
|
|
assert classify(login+' Goldshire')=='login'
|
|
assert classify('Disconnected Goldshire')=='disconnected'
|
|
assert classify('Goldshire Enter World Create Character')=='characters'
|
|
assert classify(login+' Elwynn Forest')=='login'
|
|
assert classify('Disconnected Elwynn Forest')=='disconnected'
|
|
assert classify(login+' Main Hall')=='login'
|
|
assert classify(login+' Hall of Arms')=='login'
|
|
assert classify('')=='loading-or-unknown'
|
|
assert not stable_login_retry('login',True,4.99)
|
|
assert stable_login_retry('login',True,5)
|
|
assert not stable_login_retry('loading-or-unknown',True,30)
|
|
assert not stable_login_retry('disconnected',True,30)
|
|
assert not stable_login_retry('login',False,30)
|
|
print('Disconnect modal blocks credential automation; its underlay remains screenshot-sensitive.')
|
|
|
|
# A focus loss must block new key presses while still releasing a held key.
|
|
# The real fatal-dialog Exit closed its window before the release event.
|
|
from types import SimpleNamespace
|
|
import client_ui as ui
|
|
class InputRecorder:
|
|
def __init__(self):self.events=[]
|
|
def write(self,*event):self.events.append(event)
|
|
def syn(self):pass
|
|
recorder=InputRecorder();previous=(ui.UI,ui.INPUT_WINDOW,ui.KEY_DELAY)
|
|
try:
|
|
ui.UI=recorder;ui.INPUT_WINDOW=1;ui.KEY_DELAY=0
|
|
unfocused=SimpleNamespace(get_input_focus=lambda:SimpleNamespace(focus=SimpleNamespace(id=2)))
|
|
try:ui.fake(unfocused,ui.X.KeyPress,40)
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Unfocused key press accepted')
|
|
assert not recorder.events
|
|
ui.fake(unfocused,ui.X.KeyRelease,40)
|
|
assert recorder.events==[(ui.ecodes.EV_KEY,32,0)]
|
|
finally:ui.UI,ui.INPUT_WINDOW,ui.KEY_DELAY=previous
|
|
print('Focus loss blocks presses but permits release of an already held key.')
|
|
|
|
# A focus change between Shift and its character must still release both keys.
|
|
keys={ord('A'):(38,1)}
|
|
connection=SimpleNamespace(keysym_to_keycode=lambda sym:50,sync=lambda:None)
|
|
events=[]
|
|
def lose_focus(d,event,code):
|
|
events.append((event,code))
|
|
if event==ui.X.KeyPress and code==38:raise RuntimeError('synthetic focus loss')
|
|
from unittest.mock import patch,Mock
|
|
with patch.object(ui,'KEYMAP',keys),patch.object(ui,'fake',side_effect=lose_focus):
|
|
try:ui.type_text(connection,'A')
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Focus loss did not stop typing')
|
|
assert events==[(ui.X.KeyPress,50),(ui.X.KeyPress,38),(ui.X.KeyRelease,38),(ui.X.KeyRelease,50)]
|
|
with patch.object(ui,'KEYMAP',keys),patch.object(ui,'fake') as emit:
|
|
try:ui.type_text(connection,'A\u2603')
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Unsupported text accepted')
|
|
emit.assert_not_called()
|
|
with patch.object(ui,'fake') as emit,patch.object(ui.time,'sleep',side_effect=InterruptedError):
|
|
try:ui.key(connection,'Return')
|
|
except InterruptedError:pass
|
|
else:raise AssertionError('Interrupted key hold ignored')
|
|
assert emit.call_args_list[-1].args[1:]==(ui.X.KeyRelease,50)
|
|
print('Interrupted input releases Shift/character keys; unmapped strings emit no partial input.')
|
|
|
|
# CLI callers also need the pre-WowB Wine startup allowance, but only for a live
|
|
# exact client path. Stale PID files must not bless unrelated processes.
|
|
import tempfile
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
base=Path(directory);runtime=base/'runtime';proc=base/'proc'
|
|
runtime.mkdir();(proc/'123').mkdir(parents=True)
|
|
(runtime/'client-launch.pid').write_text('123')
|
|
command=proc/'123/cmdline'
|
|
command.write_bytes(b'wine\0'+str(ui.CLIENT/'WowB.exe').encode()+b'\0-console\0')
|
|
assert ui.known_client_startup_pid(runtime,proc)==123
|
|
command.write_bytes(b'python3\0unrelated.py\0')
|
|
assert ui.known_client_startup_pid(runtime,proc) is None
|
|
command.unlink()
|
|
assert ui.known_client_startup_pid(runtime,proc) is None
|
|
(runtime/'client-launch.pid').write_text('invalid')
|
|
assert ui.known_client_startup_pid(runtime,proc) is None
|
|
print('CLI startup recognizes only live exact-path Wine launches, rejecting stale and reused PIDs.')
|
|
|
|
# Main/error windows share the WowB class. A fatal modal must never be selected
|
|
# for typing, nor hidden by an OCR classification of the login screen beneath.
|
|
main={'id':10,'pid':123,'classes':('wowb.exe',),'width':1920,'height':1080,'mapped':True,'transient':None}
|
|
dialog={**main,'id':11,'width':605,'height':102,'transient':10}
|
|
reporter={**main,'id':12,'pid':124,'classes':('blizzarderror.exe',),'width':523,'height':414}
|
|
assert ui.choose_main_window([main],123)==main
|
|
assert ui.choose_main_window([{**main,'id':9,'pid':999},main],123)==main
|
|
try:ui.choose_main_window([main,dialog,reporter],123)
|
|
except ui.ClientWindowBlocked as error:assert error.kind=='crashed'
|
|
else:raise AssertionError('Fatal modal accepted as game window')
|
|
try:ui.choose_main_window([main,dialog],123)
|
|
except ui.ClientWindowBlocked:pass
|
|
else:raise AssertionError('Modal underlay authorized keyboard input')
|
|
assert ui.focus_id(SimpleNamespace(get_input_focus=lambda:SimpleNamespace(focus=1))) is None
|
|
|
|
from client_session import Session
|
|
with patch.dict('os.environ',{'GW_CLIENT_INPUT':'invalid'}):
|
|
try:Session()
|
|
except ValueError:pass
|
|
else:raise AssertionError('Unknown input backend accepted')
|
|
# Standard X11 input remains explicitly selected and uses observed pointer/focus
|
|
# checks. A focus loss immediately before the press must never click elsewhere.
|
|
window=SimpleNamespace(id=10,get_geometry=lambda:SimpleNamespace(width=1920,height=1080))
|
|
root=SimpleNamespace(translate_coords=lambda *a:SimpleNamespace(x=0,y=0),query_pointer=lambda:SimpleNamespace(root_x=960,root_y=550),get_full_property=lambda *a:SimpleNamespace(value=[10]))
|
|
connection=SimpleNamespace(screen=lambda:SimpleNamespace(root=root),sync=lambda:None,intern_atom=lambda name:name)
|
|
with patch.object(ui,'UI',None),patch.object(ui,'focus_id',return_value=10),patch.object(ui.xtest,'fake_input')as emit,patch.object(ui.time,'sleep'):
|
|
ui.click_at(connection,window,960,550)
|
|
assert [(r.args[1],r.args[2])for r in emit.call_args_list]==[(ui.X.ButtonPress,1),(ui.X.ButtonRelease,1)]
|
|
with patch.object(ui,'UI',None),patch.object(ui,'focus_id',return_value=10),patch.object(root,'query_pointer',side_effect=[SimpleNamespace(root_x=0,root_y=0),SimpleNamespace(root_x=960,root_y=550)]),patch.object(ui.xtest,'fake_input')as emit,patch.object(ui.time,'sleep'):
|
|
ui.click_at(connection,window,960,550)
|
|
assert emit.call_args_list[0].args[1]==ui.X.MotionNotify and emit.call_args_list[0].kwargs==dict(x=960,y=550)
|
|
assert len(emit.call_args_list)==3 # Absolute move, then verified press/release.
|
|
with patch.object(ui,'UI',None),patch.object(ui,'focus_id',side_effect=[10,None]),patch.object(ui.xtest,'fake_input')as emit:
|
|
try:ui.click_at(connection,window,960,550)
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Pointer focus loss accepted')
|
|
emit.assert_not_called()
|
|
window=SimpleNamespace(id=10)
|
|
connection=SimpleNamespace(sync=lambda:None,screen=lambda:SimpleNamespace(root=root),intern_atom=lambda name:name)
|
|
with patch.object(ui,'target',return_value=window),patch.object(ui,'focus_id',side_effect=[None,10]),patch.object(ui,'activate') as activate:
|
|
ui.ensure_focus(connection,window);assert activate.call_count==1
|
|
with patch.object(ui,'target',side_effect=ui.ClientWindowBlocked('crashed')),patch.object(ui,'activate') as activate:
|
|
try:ui.ensure_focus(connection,window)
|
|
except ui.ClientWindowBlocked:pass
|
|
else:raise AssertionError('Focus recovery ignored fatal dialog')
|
|
activate.assert_not_called()
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
base=Path(directory);(base/'runtime').mkdir();closed=[]
|
|
display=SimpleNamespace(close=lambda:closed.append(True))
|
|
with patch.object(ui,'ROOT',base),patch.object(ui.display,'Display',return_value=display),patch.object(ui,'target',return_value=window),patch.object(ui,'ensure_focus',side_effect=RuntimeError('unavailable')):
|
|
session=Session(startup_pid=123)
|
|
try:session.__enter__()
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Unfocused session accepted')
|
|
assert session.lock.closed and closed==[True]
|
|
|
|
# Password provider is deliberately not a credential file: readback failure
|
|
# must stop before it is called, even when focus and form labels look correct.
|
|
for width,height,point in ((1920,1080,(960,550)),(2560,1440,(1280,733))):
|
|
window=SimpleNamespace(get_geometry=lambda:SimpleNamespace(width=width,height=height))
|
|
provider=Mock(side_effect=AssertionError('Password consumed before account verification'))
|
|
with patch.object(ui,'private_screen',return_value=login),patch.object(ui,'click_at')as click,patch.object(ui,'clear_edit_selection'),patch.object(ui,'type_text'),patch.object(ui,'key'),patch.object(ui,'verify_blurred_account',side_effect=RuntimeError('readback failed')):
|
|
try:ui._verified_login_values(None,window,'SYNTHETIC',provider)
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Failed readback accepted')
|
|
provider.assert_not_called();click.assert_called_once_with(None,window,*point)
|
|
window=SimpleNamespace(get_geometry=lambda:SimpleNamespace(width=1280,height=720))
|
|
with patch.object(ui,'private_screen')as read:
|
|
try:ui._verified_login_values(None,window,'SYNTHETIC',provider)
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Unknown display authorized credentials')
|
|
read.assert_not_called();provider.assert_not_called()
|
|
|
|
from PIL import Image,ImageDraw
|
|
pixels=Image.new('RGB',(1920,1080),'black');draw=ImageDraw.Draw(pixels)
|
|
assert ui.password_mask_shapes(pixels)==0
|
|
for offset in (0,12,24):draw.rectangle((810+offset,625,814+offset,629),fill='white')
|
|
draw.line((900,619,900,645),fill='white') # Blinking caret is not a mask glyph.
|
|
assert ui.password_mask_shapes(pixels)==3
|
|
print('PID-scoped window selection, modal/focus guards, failed-session cleanup and password-provider/mask protections passed.')
|
|
|
|
# Only a discarded focus-transition state read is retried, never other failures.
|
|
from client_session import Session
|
|
probe=Session();probe.d=object();probe.win=object();probe.focus=Mock()
|
|
with patch.object(ui,'private_screen',side_effect=[RuntimeError('Focus changed during capture; image discarded'),'Main Hall']):
|
|
assert probe.state()=='world' and probe.focus.call_count==2
|
|
probe.focus.reset_mock()
|
|
with patch.object(ui,'private_screen',side_effect=RuntimeError('unrelated failure')):
|
|
try:probe.state()
|
|
except RuntimeError as error:assert str(error)=='unrelated failure'
|
|
else:raise AssertionError('Unexpected state error swallowed')
|
|
assert probe.focus.call_count==1
|
|
|
|
# A truncated slash command must be canceled before a later cleanup command,
|
|
# never submitted by that command's opening Return. Do not replay failed input.
|
|
session=Session(startup_pid=123);session.d=object();session.win=object();events=[]
|
|
with patch.object(session,'focus'),patch.object(ui,'chat_edit_open',return_value=False),patch.object(ui,'wait_chat_edit')as ready,patch.object(ui,'clear_edit_selection')as clearEdit,patch.object(ui,'key',side_effect=lambda d,k:events.append(k)),patch.object(ui,'private_login_clipboard',return_value=nullcontext(lambda value:None)),patch.object(ui,'paste_login_clipboard',side_effect=[RuntimeError('focus lost while pasting'),None]) as pasted:
|
|
try:session.macro('/run incomplete')
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Interrupted macro unexpectedly submitted')
|
|
assert session.partial_macro and events==['Return']
|
|
session.macro('/s .save')
|
|
assert events==['Return','Escape','Return','Return'] and not session.partial_macro
|
|
assert [call.args[3] for call in pasted.call_args_list]==['/run incomplete','/s .save']
|
|
assert clearEdit.call_count==2
|
|
assert [c.args[2]for c in ready.call_args_list]==[True,True,False]
|
|
for unsafe in ('/run x~=nil','/run print("`")'):
|
|
with patch.object(session,'focus')as focus,patch.object(ui,'key')as key:
|
|
try:session.macro(unsafe)
|
|
except ValueError as e:assert 'console toggle' in str(e)
|
|
else:raise AssertionError('Console toggle typed into chat')
|
|
focus.assert_not_called();key.assert_not_called()
|
|
print('Interrupted macro is canceled before cleanup input; failed command is never replayed or submitted.')
|
|
|
|
# A single foliage/no-text frame must not fail live-world readiness or authorize
|
|
# input. Only exact world recognition ends the bounded read-only poll; known
|
|
# login/disconnect/character screens stop immediately without a reconnect.
|
|
probe=Session(startup_pid=123)
|
|
with patch.object(probe,'state',side_effect=['loading-or-unknown','world']),patch('client_session.time.sleep'):
|
|
probe.wait_world()
|
|
for state in ('login','disconnected','characters','ruleset'):
|
|
with patch.object(probe,'state',return_value=state) as read:
|
|
try:probe.wait_world()
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Known non-world screen authorized input')
|
|
assert read.call_count==1
|
|
with patch.object(probe,'state',return_value='loading-or-unknown'),patch('client_session.time.monotonic',side_effect=[0,99]):
|
|
try:probe.wait_world()
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Unbounded unknown readiness accepted')
|
|
for timeout in (0,16):
|
|
try:probe.wait_world(timeout)
|
|
except ValueError:pass
|
|
else:raise AssertionError('Invalid readiness bound accepted')
|
|
print('Read-only world readiness tolerates one unknown frame, rejects known other screens and times out without input.')
|
|
with patch.object(probe,'state',side_effect=['loading-or-unknown','login'])as read,patch('client_session.time.sleep'):
|
|
probe.wait_login()
|
|
assert all(call.kwargs=={'world_first':False}for call in read.call_args_list)
|
|
for other in ('characters','world','ruleset','disconnected'):
|
|
with patch.object(probe,'state',return_value=other):
|
|
try:probe.wait_login()
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Login readiness accepted a different screen')
|
|
with patch.object(probe,'state',return_value='loading-or-unknown'),patch('client_session.time.monotonic',side_effect=[0,4]),patch('client_session.time.sleep'):
|
|
try:probe.wait_login()
|
|
except RuntimeError:pass
|
|
else:raise AssertionError('Unbounded login readiness accepted')
|
|
for timeout in (0,6):
|
|
try:probe.wait_login(timeout)
|
|
except ValueError:pass
|
|
else:raise AssertionError('Invalid login readiness bound accepted')
|
|
print('Read-only login readiness tolerates transient unknown frames; preserves other sessions/modals and never submits credentials.')
|
|
|
|
# No OCR or arbitrary pixel text is used for edit readiness. Both observed
|
|
# outline rows must be present; a different geometry cannot authorize typing.
|
|
from PIL import Image
|
|
assert ui.compact_world_label(Image.new('RGB',(1920,1080),'black')).size==(588,126)
|
|
assert ui.compact_world_label(Image.new('RGB',(1280,720),'black'))is None
|
|
assert classify('Booty Ba')=='loading-or-unknown' # Never add a fuzzy OCR alias.
|
|
assert classify('Boory Bay')=='loading-or-unknown'
|
|
assert ui.raw_world_label(Image.new('RGB',(1280,720),'black'))is None
|
|
# Real public minimap crop from the post-reload failure, no player/account data.
|
|
import io,os,subprocess
|
|
for fixture_name in('booty-bay-post-reload-label.png','booty-bay-bright-backdrop-label.png','booty-bay-upper-flare-label.png'):
|
|
fixture=Path(__file__).resolve().parent/'fixtures'/fixture_name
|
|
pixels=Image.new('RGB',(1920,1080),'black');pixels.paste(Image.open(fixture),(1710,0))
|
|
label=ui.raw_world_label(pixels);encoded=io.BytesIO();label.save(encoded,format='PNG')
|
|
observed=subprocess.run(['tesseract','stdin','stdout','--psm','13'],input=encoded.getvalue(),capture_output=True,check=True,env=dict(os.environ,OMP_THREAD_LIMIT='1')).stdout.decode()
|
|
assert classify(observed)=='world',repr(observed)
|
|
assert classify(login+' '+observed)=='login'
|
|
assert classify('Disconnected '+observed)=='disconnected'
|
|
assert classify('Enter World Create Character '+observed)=='characters'
|
|
# Real bank-interior label: use an additional segmentation mode, never a
|
|
# replacement for the exact zone text or login/character-screen precedence.
|
|
pixels=Image.new('RGB',(1920,1080),'black')
|
|
pixels.paste(Image.open(Path(__file__).resolve().parent/'fixtures/booty-bay-wood-interior-label.png'),(1710,0))
|
|
encoded=io.BytesIO();ui.compact_world_label(pixels).save(encoded,format='PNG')
|
|
observed=subprocess.run(['tesseract','stdin','stdout','--psm','8'],input=encoded.getvalue(),capture_output=True,check=True,env=dict(os.environ,OMP_THREAD_LIMIT='1')).stdout.decode()
|
|
assert classify(observed)=='world',repr(observed)
|
|
assert classify(login+' '+observed)=='login'
|
|
assert classify('Disconnected '+observed)=='disconnected'
|
|
assert classify('Enter World Create Character '+observed)=='characters'
|
|
closed=Image.new('RGB',(1920,1080),'black')
|
|
assert not ui.chat_edit_pixels_open(closed)
|
|
for y in (945,961):
|
|
for x in range(40,460):closed.putpixel((x,y),(200,200,200))
|
|
assert ui.chat_edit_pixels_open(closed)
|
|
for x in range(40,460):closed.putpixel((x,961),(200,200,0))
|
|
assert not ui.chat_edit_pixels_open(closed)
|
|
print('Chat edit requires both observed border rows; no text OCR, command replay or relaxed focus checks.')
|
|
|
|
pixels=Image.new('RGB',(2560,1440),'black')
|
|
pixels.paste(Image.open(Path(__file__).resolve().parent/'fixtures/cenarion-hold-compact-1440p-label.png'),(2310,5))
|
|
encoded=io.BytesIO();ui.native_compact_world_label(pixels).save(encoded,format='PNG')
|
|
observed=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,check=True,env=dict(os.environ,OMP_THREAD_LIMIT='1')).stdout.decode()
|
|
assert re.sub(r'[^a-z]','',observed.lower())=='cenarionhold',repr(observed)
|
|
assert classify(observed)=='world'
|
|
assert classify(login+' '+observed)=='login'
|
|
assert classify('Disconnected '+observed)=='disconnected'
|
|
assert classify('Enter World Create Character '+observed)=='characters'
|
|
|
|
# The same exact label in shade must retain its final glyph. Modal and
|
|
# credential precedence remain mandatory even when this read-only view works.
|
|
pixels=Image.new('RGB',(2560,1440),'black')
|
|
pixels.paste(Image.open(Path(__file__).resolve().parent/'fixtures/cenarion-hold-shaded-1440p-label.png'),(2310,5))
|
|
encoded=io.BytesIO();ui.native_compact_world_label(pixels,grayscale=True).save(encoded,format='PNG')
|
|
observed=subprocess.run(['tesseract','stdin','stdout','--psm','7'],input=encoded.getvalue(),capture_output=True,check=True,env=dict(os.environ,OMP_THREAD_LIMIT='1')).stdout.decode()
|
|
assert re.sub(r'[^a-z]','',observed.lower())=='cenarionhold',repr(observed)
|
|
assert classify(observed)=='world'
|
|
assert classify(login+' '+observed)=='login'
|
|
assert classify('Disconnected '+observed)=='disconnected'
|
|
assert classify('Enter World Create Character '+observed)=='characters'
|
|
|
|
# Binary outlined-font readback is another OCR view, never an expected-name
|
|
# whitelist or a character substitution. Credential-stop tests above remain.
|
|
with patch.object(ui,'field_ocr',return_value=['OTHER']),patch.object(ui.subprocess,'run',side_effect=[SimpleNamespace(stdout=b'WRONG'),SimpleNamespace(stdout=b'SYNTHETIC')])as run:
|
|
values=ui.account_field_ocr(Image.new('RGB',(1920,1080),'black'))
|
|
assert values==['OTHER','WRONG','SYNTHETIC']
|
|
assert 'tessedit_char_whitelist' not in ' '.join(run.call_args_list[-1].args[0])
|
|
print('Outlined account readback view preserves exact comparisons and password guards.')
|
|
|
|
# The fast login observation still reads the modal region before returning;
|
|
# it never OCRs account values or the roster after recognizing the form.
|
|
with tempfile.TemporaryDirectory()as directory:
|
|
image=Path(directory)/'screen.png';Image.new('RGB',(1920,1080),'black').save(image)
|
|
for modal in (b'',b'Disconnected'):
|
|
responses=[SimpleNamespace(stdout=''),SimpleNamespace(returncode=0,stdout=b'Account Password'),SimpleNamespace(returncode=0,stdout=modal)]
|
|
with patch.object(ui,'capture_frame'),patch.object(ui.subprocess,'run',side_effect=responses)as run:
|
|
observed=ui.capture_text(None,None,image,world_first=False)
|
|
assert classify(observed)==('disconnected'if modal else'login')
|
|
assert run.call_count==3
|
|
print('Fast login capture reads public labels and modal before returning; skips unrelated field/world/roster OCR.')
|
|
|
|
# An active official Octo session needs a fresh notice and explicit handoff.
|
|
# A background test must stop before requesting activation or sending input.
|
|
from unittest.mock import patch
|
|
with patch.object(ui,'official_octo_focused',return_value=True), patch.object(ui,'target') as target_probe, patch.object(ui.subprocess,'run') as activation:
|
|
try:ui.activate(object(),object())
|
|
except RuntimeError as exc:assert 'ten-second notice' in str(exc)
|
|
else:raise AssertionError('Official Octo focus was taken without an explicit handoff')
|
|
target_probe.assert_not_called();activation.assert_not_called()
|
|
print('Official Octo focus blocks automatic takeover before activation or input.')
|