// DOM + actual Python HTTP handler checks using temporary data and no network. // Run with a locally available jsdom: NODE_PATH=/path/to/node_modules node test_ui.cjs const {JSDOM} = require('jsdom'); const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const assert = require('node:assert/strict'); const {spawnSync} = require('node:child_process'); const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ddj-rejection-test-')); const folder = path.join(root, 'fixture'); fs.mkdirSync(folder); for (const id of ['A', 'B', 'C', 'D']) { for (const suffix of ['source', ...(id === 'C' ? [] : ['edited']), ...(id === 'D' ? [] : ['result', 'result_v104'])]) { fs.writeFileSync(path.join(folder, `${id}_${suffix}.png`), 'fixture image'); } } const bridge = `import json,sys from pathlib import Path from app import Dataset from test_app import request_without_socket root=Path(sys.argv[1]) assert root.name.startswith('ddj-rejection-test-') request=json.load(sys.stdin) print(json.dumps(request_without_socket(Dataset(root),request['path'],request.get('body')),ensure_ascii=False))`; function api(url, body) { const run = spawnSync(process.env.PYTHON || 'python3', ['-c', bridge, root], { cwd:__dirname, input:JSON.stringify({path:url,body}), encoding:'utf8' }); assert.equal(run.status, 0, run.stderr); return JSON.parse(run.stdout); } const pages = []; const {buildSync} = require('esbuild'); const bundle = buildSync({entryPoints:[path.join(__dirname,'src/main.jsx')],bundle:true,write:false,format:'iife',loader:{'.css':'empty'},define:{'process.env.NODE_ENV':'"test"'}}).outputFiles[0].text; function page() { const dom = new JSDOM(fs.readFileSync(path.join(__dirname,'static/index.html'),'utf8'), { url:'http://127.0.0.1', runScripts:'outside-only', pretendToBeVisual:true }); pages.push(dom); const win = dom.window; win.fetch = async (url, options) => { const response = api(url, options?.body === undefined ? undefined : JSON.parse(options.body)); return {ok:response.status < 400, json:async () => response.data}; }; const style = win.document.createElement('style'); style.textContent = fs.readFileSync(path.join(__dirname,'src/style.css'),'utf8'); win.document.head.append(style); win.HTMLDialogElement.prototype.showModal = function () { this.open = true; }; win.HTMLDialogElement.prototype.close = function () { this.open = false; }; win.eval(bundle); return {win, $:id => win.document.getElementById(id), click:selector => win.document.querySelector(selector).click()}; } const settle = async () => { for (let i=0;i<4;i++) await new Promise(resolve => setTimeout(resolve, 40)); }; const label = (id, suffix) => path.join(folder, `${id}_${suffix}.txt`); async function main() { const p = page(); const stale = page(); await settle(); assert.equal(p.$('itemId').textContent, 'A', p.$('toast')?.textContent); assert(!p.$('enlargeSource').hidden && !p.$('enlargeEdited').hidden); assert(p.$('sourceImage').src.includes('A_source.png')); assert(p.$('editedImage').src.includes('A_edited.png')); assert.equal(p.win.getComputedStyle(p.win.document.querySelector('.reference-images')).display,'grid'); p.click('#enlargeEdited'); await settle(); assert(p.$('imageDialog').open); assert(p.$('dialogImage').src.includes('A_edited.png')); p.click('#closeDialog'); await settle(); p.click('#rejectResults'); await settle(); assert.equal(fs.readFileSync(label('A','all_rejected'),'utf8'),'result_unsatisfied\n'); assert(!fs.existsSync(label('A','best'))); assert.equal(p.$('itemId').textContent, 'B'); assert.equal(p.$('rejectedCount').textContent, '1'); stale.click('.choose-button'); await settle(); assert(stale.$('toast').classList.contains('error')); assert.equal(fs.readFileSync(label('A','all_rejected'),'utf8'),'result_unsatisfied\n'); p.click('#rejectEdited'); await settle(); assert.equal(fs.readFileSync(label('B','all_rejected'),'utf8'),'edited_unsatisfied\n'); assert.equal(p.$('itemId').textContent, 'C'); assert(p.$('rejectEdited').disabled); assert(!p.$('missingEdited').hidden); p.click('#skip'); await settle(); assert(!p.$('empty').hidden); assert(!fs.existsSync(label('C','best')) && !fs.existsSync(label('C','all_rejected'))); const reloaded = page(); await settle(); assert.equal(reloaded.$('itemId').textContent, 'C'); p.click('[data-filter="rejected"]'); await settle(); assert.equal(p.$('itemId').textContent, 'A', p.$('toast')?.textContent); assert.equal(p.$('savedName').textContent, '结果都不满意'); assert(p.$('rejectResults').disabled); p.click('#rejectEdited'); await settle(); assert.equal(fs.readFileSync(label('A','all_rejected'),'utf8'),'edited_unsatisfied\n'); p.click('#previous'); await settle(); assert.equal(p.$('itemId').textContent, 'A', p.$('toast')?.textContent); p.click('.result-card:last-child .choose-button'); await settle(); assert(!fs.existsSync(label('A','all_rejected'))); assert.equal(fs.readFileSync(label('A','best'),'utf8'),'A_result_v104.png\n'); assert.equal(p.$('itemId').textContent, 'B'); p.click('#clearBest'); await settle(); assert(!fs.existsSync(label('B','all_rejected'))); assert(p.$('savedBox').hidden); p.click('[data-filter="no_results"]'); await settle(); assert.equal(p.$('itemId').textContent, 'D'); assert(p.$('rejectResults').disabled); assert(!p.$('rejectEdited').disabled); p.click('#rejectEdited'); await settle(); assert.equal(fs.readFileSync(label('D','all_rejected'),'utf8'),'edited_unsatisfied\n'); const final = api('/api/state').data; assert.deepEqual(final.stats,{total:4,done:2,rejected:1,pending:2,no_results:1}); p.click('[data-filter="pending"]'); await settle(); assert.equal(p.$('itemId').textContent, 'B'); p.click('.perfect-button'); await settle(); assert.equal(fs.readFileSync(label('B','perfect'),'utf8'),'B_result.png\n'); assert.equal(fs.readFileSync(label('B','best'),'utf8'),'B_result.png\n'); assert(!fs.existsSync(path.join(folder,'B_perfect.png'))); assert(p.$('empty')); // C was explicitly skipped earlier in this session. p.click('#previous'); await settle(); assert(p.$('itemInfo').textContent.includes('完美')); p.click('#clearBest'); await settle(); assert(!fs.existsSync(label('B','perfect'))); // Exercise all completed subfilters against all four annotation types. for (const [id, kind, reason] of [['B','perfect'],['C','reject','result_unsatisfied']]) { const item = api('/api/state').data.items.find(x => x.id === id); assert.equal(api('/api/'+kind,{key:item.key,revision:item.revision,result:id+'_result.png',reason}).status,200); } const filtered = page(); await settle(); filtered.click('[data-filter="done"]'); await settle(); async function subtype(type, expected) { filtered.$('annotationType').value = type; filtered.$('annotationType').dispatchEvent(new filtered.win.Event('change',{bubbles:true})); await settle(); assert.deepEqual([...filtered.$('jump').options].map(x => x.textContent.replace(/^[✓★] /,'')), expected); } await subtype('perfect',['B']); await subtype('best',['A','B']); await subtype('ordinary',['A']); await subtype('result_unsatisfied',['C']); await subtype('edited_unsatisfied',['D']); await subtype('all',['A','B','C','D']); const other = path.join(root, 'other'); fs.mkdirSync(other); for (const suffix of ['source','result']) fs.writeFileSync(path.join(other,`E_${suffix}.png`),'fixture image'); filtered.click('#refresh'); await settle(); assert.equal(filtered.$('progressText').textContent, '4 / 5'); async function selectFolder(value, expected) { filtered.$('folder').value = value; filtered.$('folder').dispatchEvent(new filtered.win.Event('change',{bubbles:true})); await settle(); assert.equal(filtered.$('progressText').textContent, expected); } await selectFolder('fixture','4 / 4'); assert.equal(filtered.win.document.querySelector('.progress-track i').style.width,'100%'); await selectFolder('other','0 / 1'); assert.equal(filtered.win.document.querySelector('.progress-track i').style.width,'0%'); await selectFolder('','4 / 5'); // Prefix directories stay grouped under their model in filters and progress. for (const id of ['ABC123', 'XYZ987']) { const shard = path.join(root, 'sharded-model', id.slice(0, 3)); fs.mkdirSync(shard, {recursive:true}); for (const suffix of ['source', 'result']) fs.writeFileSync(path.join(shard, `${id}_${suffix}.png`), 'fixture'); if (id === 'ABC123') fs.writeFileSync(path.join(shard, `${id}_best.txt`), `${id}_result.png\n`); } filtered.click('#refresh'); await settle(); assert.deepEqual([...filtered.$('folder').options].map(x => x.value), ['', 'fixture', 'other', 'sharded-model']); await selectFolder('sharded-model', '1 / 2'); assert.equal(filtered.$('totalCount').textContent, '2'); assert.equal(filtered.$('pendingCount').textContent, '1'); assert.equal(filtered.$('itemId').textContent, 'ABC123'); filtered.click('[data-filter="pending"]'); await settle(); assert.equal(filtered.$('itemId').textContent, 'XYZ987'); filtered.click('.choose-button'); await settle(); assert.equal(filtered.$('progressText').textContent, '2 / 2'); assert.equal(fs.readFileSync(path.join(root, 'sharded-model/XYZ/XYZ987_best.txt'), 'utf8'), 'XYZ987_result.png\n'); console.log('PASS: simultaneous source/edited, enlarged edited, both rejection reasons, auto advance, reload persistence, skip, filters, missing edited/result, reselect, clear, stale-tab protection.'); } main().catch(error => { console.error(error); process.exitCode=1; }).finally(() => { pages.forEach(dom => dom.window.close()); fs.rmSync(root,{recursive:true,force:true}); });