syntax-video-infer / tests /test_frontend.cjs
MesserMMP's picture
Update the research workspace
57ea0fa verified
Raw History Blame Contribute Delete
17.8 kB
'use strict';
// Lightweight DOM-contract tests: no browser, model weights, or DICOM decoding.
const test=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const path=require('node:path');
const vm=require('node:vm');
const root=path.join(__dirname,'..');
const html=fs.readFileSync(path.join(root,'static/index.html'),'utf8');
const source=fs.readFileSync(path.join(root,'static/app.js'),'utf8');
const cache=JSON.parse(fs.readFileSync(path.join(root,'service/example_results/philips-zero.json'),'utf8'));
class Element {
constructor(tag,document){this.tagName=tag.toUpperCase();this.ownerDocument=document;this.children=[];this.parentElement=null;this.attributes={};this.dataset={};this.listeners={};this.className='';this._text='';this.hidden=false;this.disabled=false;this.open=false;this.currentTime=0;this.duration=NaN;this.readyState=0;this.paused=true;this.seeking=false;this.error=null;this.style={setProperty:(key,value)=>{this.style[key]=value;}};const element=this;this.classList={contains:name=>element.className.split(/\s+/).includes(name),add(...names){element.className=[...new Set([...element.className.split(/\s+/).filter(Boolean),...names])].join(' ');},remove(...names){element.className=element.className.split(/\s+/).filter(name=>!names.includes(name)).join(' ');},toggle(name,force){const enabled=force??!this.contains(name);enabled?this.add(name):this.remove(name);return enabled;}};}
get firstElementChild(){return this.children[0]||null;}
get isConnected(){let node=this;while(node.parentElement)node=node.parentElement;return node===this.ownerDocument.documentElement;}
get textContent(){return this._text+this.children.map(node=>node.textContent).join('');}
set textContent(value){this._text=String(value);this.children.forEach(node=>node.parentElement=null);this.children=[];}
get innerHTML(){return this.textContent;}
set innerHTML(value){this.textContent=String(value).replace(/<br\s*\/?\s*>/gi,'\n').replace(/<[^>]+>/g,'');}
setAttribute(name,value){this.attributes[name]=String(value);if(name==='id')this.id=String(value);if(name==='class')this.className=String(value);if(name==='lang')this.lang=String(value);if(name==='hidden')this.hidden=true;if(name==='disabled')this.disabled=true;if(name==='muted')this.muted=true;if(name.startsWith('data-'))this.dataset[name.slice(5).replace(/-([a-z])/g,(_,c)=>c.toUpperCase())]=String(value);}
getAttribute(name){return name==='class'?this.className:this.attributes[name]??null;}
removeAttribute(name){delete this.attributes[name];}
append(...nodes){for(let node of nodes){if(typeof node==='string'){const text=new Element('#text',this.ownerDocument);text.textContent=node;node=text;}node.remove();node.parentElement=this;this.children.push(node);}}
prepend(node){node.remove();node.parentElement=this;this.children.unshift(node);}
after(node){const parent=this.parentElement;if(!parent)throw Error('Detached node');node.remove();node.parentElement=parent;parent.children.splice(parent.children.indexOf(this)+1,0,node);}
remove(){if(this.parentElement)this.parentElement.children=this.parentElement.children.filter(node=>node!==this);this.parentElement=null;}
replaceChildren(...nodes){this.children.forEach(node=>node.parentElement=null);this.children=[];this._text='';this.append(...nodes);}
addEventListener(type,callback,options){(this.listeners[type]??=[]).push({callback,once:options?.once});}
async dispatch(type,event={}){for(const listener of [...(this.listeners[type]||[])]){await listener.callback({target:this,preventDefault(){},...event});if(listener.once)this.listeners[type]=this.listeners[type].filter(item=>item!==listener);}}
click(){if(!this.disabled)return this.dispatch('click');}
focus(){this.ownerDocument.activeElement=this;}
scrollIntoView(){}
getBoundingClientRect(){return{top:100,bottom:300,height:200,width:390};}
querySelector(selector){return this.querySelectorAll(selector)[0]||null;}
querySelectorAll(selector){return descendants(this).filter(node=>matches(node,selector));}
load(){this.readyState=0;this.duration=NaN;this.currentTime=0;this.paused=true;}
pause(){this.paused=true;}
play(){this.paused=false;return Promise.resolve();}
showModal(){this.open=true;}
close(){this.open=false;return this.dispatch('close');}
}
function descendants(root){return root.children.flatMap(node=>[node,...descendants(node)]);}
function simpleMatch(node,selector){if(selector.startsWith('#'))return node.id===selector.slice(1);if(selector.startsWith('.'))return node.classList.contains(selector.slice(1));const attr=selector.match(/^\[([^=\]]+)(?:=["']?([^"'\]]+)["']?)?\]$/);if(attr)return node.getAttribute(attr[1])!==null&&(attr[2]===undefined||node.getAttribute(attr[1])===attr[2]);return node.tagName===selector.toUpperCase();}
function matches(node,selector){const parts=selector.trim().split(/\s+/);if(!simpleMatch(node,parts.pop()))return false;for(const part of parts.reverse()){let parent=node.parentElement;while(parent&&!simpleMatch(parent,part))parent=parent.parentElement;if(!parent)return false;node=parent;}return true;}
function makeDocument(markup){const document={createElement:tag=>new Element(tag,document),createElementNS:(_,tag)=>new Element(tag,document),createTextNode:text=>{const node=new Element('#text',document);node.textContent=text;return node;}};const stack=[];const voids=new Set(['meta','link','img','input','br','hr','source']);for(const token of markup.match(/<[^>]+>|[^<]+/g)||[]){if(token.startsWith('<!'))continue;if(token.startsWith('</')){stack.pop();continue;}if(token.startsWith('<')){const tag=token.match(/^<([\w-]+)/)?.[1];if(!tag)continue;const node=document.createElement(tag);const attrs=token.slice(tag.length+1).replace(/\/?\s*>$/,'');for(const match of attrs.matchAll(/([^\s=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s]+)))?/g))node.setAttribute(match[1],match[2]??match[3]??match[4]??'');if(stack.length)stack.at(-1).append(node);if(tag==='html')document.documentElement=node;if(tag==='body')document.body=node;if(!voids.has(tag)&&!token.endsWith('/>'))stack.push(node);}else if(stack.length)stack.at(-1)._text+=token;}
document.getElementById=id=>[document.documentElement,...descendants(document.documentElement)].find(node=>node.id===id)||null;document.querySelectorAll=selector=>[document.documentElement,...descendants(document.documentElement)].filter(node=>matches(node,selector));document.querySelector=selector=>document.querySelectorAll(selector)[0]||null;return document;}
function storage(initial={}){const values=new Map(Object.entries(initial));return{getItem:key=>values.get(key)??null,setItem:(key,value)=>values.set(key,String(value)),removeItem:key=>values.delete(key),values};}
function environment({markup=html,url='https://example.test/',session=storage(),blockedStorage=false,mobile=false,routes={}}={}){
const document=makeDocument(markup),navigations=[],requests=[],windowEvents={},animationFrames=[];const unavailable={getItem(){throw Error('blocked');},setItem(){throw Error('blocked');}};
const context={document,URL,URLSearchParams,Date,Promise,Map,Set,console,sessionStorage:blockedStorage?unavailable:session,localStorage:storage(),location:{href:url,replace:value=>navigations.push(value)},performance:{now:()=>0},navigator:{clipboard:{writeText:async()=>{}}},setTimeout:()=>1,clearTimeout:()=>{},requestAnimationFrame:callback=>{animationFrames.push(callback);return animationFrames.length;},addEventListener(type,callback){(windowEvents[type]??=[]).push(callback);},matchMedia:query=>({matches:query.includes('760px')&&mobile,addEventListener(){}}),FormData:class{constructor(){this.files=[];}append(...data){this.files.push(data);}},Blob,fetch:async(url,options={})=>{requests.push({url,...options});const key=`${options.method||'GET'} ${url}`;let response=routes[key];if(typeof response==='function')response=await response(options);if(response===undefined&&url==='/api/status')response={service:'ready',device:'cpu',model:{status:'cached',revision:'pinned',repository:'test/model'},limits:{max_files:64,max_request_mb:512}};if(response===undefined&&url==='/api/examples')response={examples:[]};if(response instanceof Error)throw response;if(response===undefined)throw Error('Unexpected request '+key);const status=response.__status??200;return{ok:status>=200&&status<300,status,json:async()=>structuredClone(response.__body??response)};}};
context.window=context;vm.createContext(context);return{context,document,navigations,requests,session,windowEvents,animationFrames};}
const hook="globalThis.__app={init,refreshStatus,uploadFiles,acceptStudies,startJob,render,applyLanguage,studyAction,workspaceSnapshot,setLanguage(value){lang=value;applyLanguage();},state(){return{studies,selectedStudyId,busy,activeJob,resultByStudy,resultJobByStudy};}};";
function runApp(env){const marker='init().catch(()=>showInterfaceRecovery(false));';assert(source.includes(marker));vm.runInContext(source.replace(marker,hook),env.context);return env.context.__app;}
const settle=async()=>{for(let i=0;i<5;i++)await new Promise(resolve=>setImmediate(resolve));};
function projection(id,artery='unassigned',frames=64){return{id,name:id+'.dcm',frames,rows:512,columns:512,artery,preview_url:'/preview/'+id,video_url:'/video/'+id};}
function study(id='study-a',complete=false,projections=[projection('a'),projection('b'),projection('short','exclude',8)]){return{id,study_uid:'test-study-uid',classification_complete:complete,projections};}
function resultFor(study,precomputed=false){return{...structuredClone(cache.result),input_assignments:study.projections.map(p=>({id:p.id,artery:p.artery})),...(precomputed?{source:{type:'precomputed_example'}}:{})};}
test('DOM revision and every required runtime ID agree with the shipped HTML',()=>{const env=environment();assert(runApp(env));const refs=[...source.matchAll(/\$\('([^']+)'\)/g)].map(match=>match[1]);assert(refs.every(id=>env.document.getElementById(id)));assert.equal(env.document.querySelectorAll('[data-artery]').length,0);assert.equal(env.document.getElementById('run-card').querySelectorAll('button').length,1);assert.equal(env.document.getElementById('pipeline-steps').querySelectorAll('button').length,0);});
test('stale HTML refreshes once before any app listener or API call; handles survive',()=>{const session=storage({'cardiosyntax-workspace':JSON.stringify({study_ids:['saved-study'],result_jobs:[['saved-study','saved-result']]})});const stale=html.replace('data-ui-version="classifier-workflow-4"','data-ui-version="legacy"').replace('id="run-button-label"','id="old-label"');const original=session.getItem('cardiosyntax-workspace');const first=environment({markup:stale,session});assert.equal(runApp(first),undefined);assert.equal(first.navigations.length,1);assert.equal(first.requests.length,0);assert.equal(session.getItem('cardiosyntax-workspace'),original);const second=environment({markup:stale,session,url:first.navigations[0]});assert.equal(runApp(second),undefined);assert.equal(second.navigations.length,0);assert.match(second.document.body.textContent,/Refresh the workspace/);assert.equal(session.getItem('cardiosyntax-workspace'),original);});
test('missing element with current marker is guarded; blocked storage cannot create reload loop',()=>{const missing=html.replace('id="classification-label"','id="missing-label"');const first=environment({markup:missing,blockedStorage:true});assert.equal(runApp(first),undefined);assert.equal(first.navigations.length,1);const second=environment({markup:missing,blockedStorage:true,url:first.navigations[0]});assert.equal(runApp(second),undefined);assert.equal(second.navigations.length,0);assert(second.document.body.querySelector('button'));});
test('actual upload → classifier → inference uses one action node and an empty run payload',async()=>{const pending=study(),classified=study('study-a',true,[projection('a','left'),projection('b','right'),projection('short','exclude',8)]),result=resultFor(classified);const env=environment({routes:{'POST /api/studies':{studies:[pending],rejected:[],warnings:[]},'POST /api/studies/study-a/classify':{id:'classifier-job',kind:'classify',status:'queued'},'GET /api/jobs/classifier-job':{id:'classifier-job',kind:'classify',status:'completed',progress:1,result:{study:classified}},'POST /api/studies/study-a/run':options=>{assert.equal(options.body,'{}');return{id:'inference-job',kind:'inference',status:'queued'};},'GET /api/jobs/inference-job':{id:'inference-job',kind:'inference',status:'completed',progress:1,result}}});const app=runApp(env);await app.init();await settle();const button=env.document.getElementById('run-button');assert.equal(env.document.querySelectorAll('.cine-controls').length,2);await app.uploadFiles([{name:'siemens.dcm'}]);assert.equal(env.document.getElementById('run-button-label').textContent,'Identify arteries');assert.equal(env.document.getElementById('classification-label').textContent,'Pending');await app.startJob();await settle();assert.equal(env.document.getElementById('run-button-label').textContent,'Calculate SYNTAX');assert.equal(env.document.getElementById('classification-label').textContent,'LCA');assert.equal(env.document.getElementById('run-button'),button);await app.startJob();await settle();assert.equal(env.document.getElementById('run-button-label').textContent,'Recalculate SYNTAX');assert.equal(env.document.getElementById('run-button'),button);assert.equal(env.document.getElementById('score-number').textContent,result.calibrated.toFixed(2));assert.equal(env.document.getElementById('fold-table-body').children.length,5);assert(!env.document.body.textContent.includes('Cannot set properties'));});
test('verified cached example renders full result and six experts without classifying or inferring',async()=>{const example={...study('cached',true,[projection('l','left'),projection('r','right')]),reference_score:0,expert_scores:[0,0,0,0,0,0],reference_url:'https://huggingface.co/datasets/test/data/blob/pinned/annotations.json'};const result=resultFor(example,true),env=environment({mobile:true});const app=runApp(env);await app.init();await settle();app.acceptStudies({studies:[example],cached_job:{id:'saved-gpu',study_id:'cached',kind:'inference',status:'completed',result}});assert.equal(env.document.getElementById('run-button-label').textContent,'Recalculate SYNTAX');assert.equal(env.document.getElementById('expert-scores').children.length,6);assert.equal(env.document.getElementById('reference-score-value').textContent,'0.00');assert.equal(env.document.getElementById('result-origin').hidden,false);assert.equal(env.document.getElementById('workspace-grid').firstElementChild.id,'run-card');assert.equal(env.requests.filter(request=>request.method==='POST').length,0);app.setLanguage('ru');assert.equal(env.document.getElementById('run-button-label').textContent,'Пересчитать SYNTAX');});
test('short/all-excluded uploads and partial results stay renderable and read-only',async()=>{const env=environment();const app=runApp(env);await app.init();await settle();app.acceptStudies({studies:[study('short',false,[projection('short','exclude',8)])]});assert.equal(env.document.getElementById('run-button').disabled,true);assert.equal(env.document.getElementById('classification-label').textContent,'Excluded');const partial=study('partial',true,[projection('only-left','left')]);app.acceptStudies({studies:[partial],cached_job:{id:'partial-result',study_id:'partial',kind:'inference',status:'completed',result:{complete:false,raw:null,calibrated:null,per_fold:[],left:{per_fold:[-.1,0,.1,.2,.3]},right:{per_fold:[]},input_assignments:[{id:'only-left',artery:'left'}]}}});assert.equal(env.document.getElementById('score-number').textContent,'—');assert.equal(env.document.getElementById('fold-table-body').children.length,5);assert.equal(env.document.getElementById('result-state').textContent,'Partial');const excluded=study('excluded',true,[{...projection('uncertain','exclude'),reason:'Low-confidence artery classification; automatically excluded.'}]);app.acceptStudies({studies:[excluded]});assert.equal(env.document.getElementById('run-button').disabled,true);assert.match(env.document.getElementById('classification-reason').textContent,/Low classifier confidence/);assert(!source.includes('saved.drafts'));assert(!source.includes('projections.sort'));});
test('pending status and queued video/scroll events stay harmless after recovery replaces the DOM',async()=>{
const ready={service:'ready',device:'cpu',model:{status:'cached'}};let resolveStatus,statusCalls=0;
const env=environment({routes:{'GET /api/status':()=>++statusCalls===1?ready:new Promise(resolve=>{resolveStatus=resolve;})}});
const app=runApp(env);await app.init();await settle();
const example=study('recovering',true,[projection('left','left'),projection('right','right')]);
app.acceptStudies({studies:[example],cached_job:{id:'saved-recovery-result',study_id:example.id,kind:'inference',status:'completed',result:resultFor(example,true)}});
const video=env.document.getElementById('viewer-image'),dialog=env.document.getElementById('preview-dialog');
const handles=env.session.getItem('cardiosyntax-workspace');
const pending=app.refreshStatus();
env.windowEvents.scroll.forEach(callback=>callback());
assert.equal(env.animationFrames.length,1);
env.context.showInterfaceRecovery(false);
resolveStatus(ready);
await assert.doesNotReject(pending);
await assert.doesNotReject(video.dispatch('error'));
await assert.doesNotReject(dialog.dispatch('close'));
assert.doesNotThrow(()=>env.animationFrames.forEach(callback=>callback()));
assert.match(env.document.body.textContent,/Refresh the workspace/);
assert.equal(env.session.getItem('cardiosyntax-workspace'),handles);
assert.equal(env.navigations.length,0);
});