Files
lmxopcua/docs/ui-consistency/evidence/ot13-config-modals/browser.py
T

95 lines
9.0 KiB
Python

"""Five source-linked configuration wrappers, strictly owned loopback synthetic state."""
import base64,csv,hashlib,io,json,re,sys
from pathlib import Path
from urllib.parse import urlsplit,parse_qs
from playwright.sync_api import sync_playwright,expect
sys.path.insert(0,'/Users/dohertj2/Desktop/ignitionoee/docs/ui-validation/router-canary')
from browser_zoom import zoom_browser,set_browser_zoom
out=Path(__file__).parent;origin='http://127.0.0.1:58916';results={'origin':origin,'scenes':[]}
with sync_playwright() as p:
for mode,width,zoom in [('desktop',1440,1),('phone',390,1),('real200',1440,2)]:
for kind in ['device','driver','tag','export','scope']:
with zoom_browser(p,width=width,height=900) as(ctx,worker):
page=ctx.new_page();page.set_default_timeout(10000);errors=[];external=[]
page.on('pageerror',lambda e:errors.append(str(e)))
def route(request):
if urlsplit(request.request.url).hostname not in ['127.0.0.1','localhost']:external.append(urlsplit(request.request.url).hostname);request.abort()
else:request.continue_()
page.route('**/*',route)
provenance=page.request.get(origin+'/fixture/provenance').json();assert provenance['provider']=='Microsoft.EntityFrameworkCore.InMemory'
page.goto(origin+'/?kind='+kind);expect(page.locator('#ready')).to_have_text('ready');factor=set_browser_zoom(worker,page,zoom)
session=page.locator('#session').inner_text();checks=[]
def state():return page.request.get(origin+'/fixture/state/'+session).json()
def check(name,value):checks.append({'name':name,'passed':bool(value)});assert value,name
def command(path):
response=page.request.post(origin+'/fixture/'+path+'/'+session+('/B' if path=='target' else '/success'));assert response.ok
def release(outcome='success'):
response=page.request.post(origin+'/fixture/release/'+session+'/'+outcome);assert response.ok
def replace():
response=page.request.post(origin+'/fixture/target/'+session+'/B');assert response.ok
def name_input():return page.get_by_label({'device':'Device name','driver':'Driver name','tag':'Name'}[kind],exact=True)
page.locator('#open').click();modal=page.locator('[role=dialog]');expect(modal).to_be_visible();safe=modal.locator('[data-initial-focus]');expect(safe).to_be_focused()
check('Named dialog and visible safe initial focus',modal.evaluate("n=>!!document.getElementById(n.getAttribute('aria-labelledby'))?.textContent.trim()") and safe.evaluate('n=>{const r=n.getBoundingClientRect();return r.top>=0&&r.bottom<=innerHeight}'))
page.locator('#outside').evaluate('n=>n.focus()');check('Outside focus denied',modal.evaluate('n=>n.contains(document.activeElement)'))
for _ in range(12):page.keyboard.press('Tab');assert modal.evaluate('n=>n.contains(document.activeElement)')
check('Twelve Tab steps remain scoped',True)
for field in modal.locator('input:not([type=hidden]),select,textarea').all():
if not field.is_visible() or field.is_disabled():continue
id=field.get_attribute('id');label=modal.locator('label[for="'+str(id)+'"]')
if id and label.count()==1:
check('Visible field has matching label '+id,True)
if field.get_attribute('type') not in ['checkbox','radio']:label.click();expect(field).to_be_focused()
else:
labelled=field.evaluate("n=>(n.getAttribute('aria-labelledby')||'').split(/\\s+/).filter(Boolean).map(id=>document.getElementById(id)?.textContent.trim()||'')")
snapshot=field.aria_snapshot();check('Composite table field has actual accessible row/column name',len(labelled)>=2 and all(text and re.sub(r'\s+',' ',text) in re.sub(r'\s+',' ',snapshot) for text in labelled))
field.focus();expect(field).to_be_focused()
check('Descriptions resolve '+str(id),field.evaluate("n=>(n.getAttribute('aria-describedby')||'').split(/\\s+/).filter(Boolean).every(id=>!!document.getElementById(id))"))
check('Text/select/textarea label clicks focus actual controls',True)
geometry=modal.locator('.modal-content').evaluate('n=>{const r=n.getBoundingClientRect();return {left:r.left,right:r.right,innerWidth,scrollWidth:document.documentElement.scrollWidth,dpr:devicePixelRatio}}')
check('Modal and page fit horizontally',geometry['left']>=0 and geometry['right']<=geometry['innerWidth']+1 and geometry['scrollWidth']<=geometry['innerWidth'])
modal.screenshot(path=str(out/(mode+'-'+kind+'.png')))
if kind=='export':
preview=modal.locator('textarea').input_value();check('Bounded CSV preview',1<len(preview.splitlines())<=50)
link=modal.get_by_role('link',name='Download CSV',exact=True);href=link.get_attribute('href');check('Download URL uses same target',parse_qs(urlsplit(href).query)['deviceId']==['CSV-A'])
with page.expect_download() as awaiting:link.click()
download=awaiting.value;content=Path(download.path()).read_bytes();rows=list(csv.reader(io.StringIO(content.decode())))
check('Full synthetic CSV download preserves127 rows',len(rows)==128)
replace();expect(modal.locator('textarea')).not_to_have_value(preview);check('Retarget preview/download remain paired',parse_qs(urlsplit(link.get_attribute('href')).query)['deviceId']==['CSV-B'] and len(modal.locator('textarea').input_value().splitlines())==4)
safe.click();expect(modal).to_have_count(0);expect(page.locator('#open')).to_be_focused()
check('Export closes without any mutation',state()['operations']==[])
csvproof={'rows':len(rows)-1,'sha256':hashlib.sha256(content).hexdigest(),'fileName':download.suggested_filename}
else:
page.keyboard.press('Escape');expect(modal).to_have_count(0);expect(page.locator('#open')).to_be_focused();check('Idle Escape returns to trigger',True)
page.locator('#open').click();expect(modal).to_be_visible()
if kind=='scope':
check('Scope selection required',modal.locator('.modal-footer .btn-primary').is_disabled())
modal.get_by_role('button',name='Expand Synthetic scope A',exact=True).click();expect(modal.locator('button[aria-pressed]').filter(has_text='Synthetic scope child-scope-A')).to_be_visible();check('Lazy children load inside current scope',True)
modal.locator('button[aria-pressed]').filter(has_text='Synthetic scope A').click()
else:
if kind=='tag':
name_input().fill('/bad');modal.locator('.modal-footer .btn-primary').click();expect(modal.locator('[id$="name-error"]')).not_to_have_text('');check('Invalid RawPath sends no operation',state()['operations']==[])
name_input().fill('fixture-updated');name_input().press('Tab')
modal.locator('.modal-footer .btn-primary').click();expect(modal).to_have_attribute('aria-busy','true')
check('Busy body controls disabled',modal.locator('fieldset').first.evaluate('n=>n.disabled'))
page.keyboard.press('Escape');check('Busy Escape/header/cancel cannot dismiss',modal.count()==1 and modal.locator('.btn-close').is_disabled() and modal.locator('.modal-footer .btn-outline-secondary').is_disabled())
first=state();check('Exactly one captured synthetic action',len(first['operations'])==1 and first['operations'][0]['target']=='A')
if kind!='scope':check('Unknown JSON and optimistic version retained',json.loads(first['operations'][0]['json'])['marker']=='A' and list(base64.b64decode(first['operations'][0]['version']))==[1,2])
release();expect(modal).to_have_count(0);expect(page.locator('#open')).to_be_focused();check('Successful action closes and restores focus',True)
page.locator('#open').click();expect(modal).to_be_visible();before=state()
if kind=='scope':modal.locator('button[aria-pressed]').filter(has_text='Synthetic scope A').click()
else:name_input().fill('fixture-replacement');name_input().press('Tab')
modal.locator('.modal-footer .btn-primary').click();expect(modal).to_have_attribute('aria-busy','true');replace()
if kind=='scope':expect(modal.locator('button[aria-pressed]').filter(has_text='Synthetic scope B')).to_be_visible()
else:expect(name_input()).to_have_value('beta')
release('failure');expect(modal).to_have_attribute('aria-busy','false')
current=state();check('Retired result does not invoke replacement UI callbacks',current['saved']==before['saved'] and current['closed']==before['closed'] and len(current['operations'])==2)
check('Retired failure does not overwrite current presentation','Synthetic old target failure' not in modal.inner_text())
if kind!='scope':check('Replacement draft remains beta',name_input().input_value()=='beta')
modal.locator('.modal-footer .btn-outline-secondary').click();expect(modal).to_have_count(0);expect(page.locator('#open')).to_be_focused();check('Replacement idle cancel returns focus',True)
csvproof=None
check('No operational/probe calls or external network',state()['forbidden']==0 and external==[])
check('No page errors',errors==[])
results['scenes'].append({'mode':mode,'kind':kind,'zoom':factor,'geometry':geometry,'checks':checks,'errors':errors,'externalHosts':external,'finalState':state(),'csv':csvproof})
(out/'browser-results.json').write_text(json.dumps(results,indent=2)+'\n')
print(json.dumps({'scenes':len(results['scenes']),'checks':sum(len(s['checks']) for s in results['scenes'])}))