174 lines
9.3 KiB
JavaScript
174 lines
9.3 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { execFile } from 'node:child_process';
|
|
import { createServer } from 'node:http';
|
|
import { readFile, writeFile } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import test from 'node:test';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { promisify } from 'node:util';
|
|
import { judgeVisual, rubric } from '../src/vlm-judge.mjs';
|
|
import { fixture, jpeg, png, tallJpeg, writeJson } from './fixture.mjs';
|
|
|
|
const run = fileURLToPath(new URL('../run.mjs', import.meta.url));
|
|
const catalogFile = new URL('../cases/20-templates-manifest.json', import.meta.url);
|
|
const exec = promisify(execFile);
|
|
const templateId = 'GJ-DESK-DNZ0385';
|
|
const readJson = async file => JSON.parse(await readFile(file, 'utf8'));
|
|
const makeDimensions = (score = 4) => Object.fromEntries(Object.keys(rubric.dimensions).map(key => [
|
|
key, { score, evidence: '成品一和实拍一之间的轮廓及样式一致', assetIds: ['result-1', key === 'legacyText' ? 'template-1' : 'product-1'] },
|
|
]));
|
|
const visualFiles = [
|
|
{ id: 'product-1', role: 'product', path: '实拍.jpg' },
|
|
{ id: 'template-1', role: 'template', path: '模板.png' },
|
|
{ id: 'result-1', role: 'result', path: '原木长桌-成品/详情页切片/01 原木/详情页-01.jpg' },
|
|
];
|
|
|
|
test('catalog contains all and only the 20 published business template IDs and focused checks', async () => {
|
|
const catalog = await readJson(catalogFile);
|
|
const ids = catalog.templates.map(template => template.id);
|
|
assert.deepEqual(ids, [
|
|
'GJ-DESK-DNZ0385', 'OYL-BOOKCASE-001', 'OYL-SHOECABINET-001', 'SFY-CHAIR-001',
|
|
'SFY-COATRACK-001', 'SFY-DESK-001', 'SFY-MATTRESS-001', 'SFY-MATTRESS-002',
|
|
'SFY-NIGHTSTAND-001', 'SFY-SHOECABINET-001', 'SFY-SHOECABINET-002', 'SFY-SIDEBOARD-001',
|
|
'SFY-SOFA-001', 'YJD-DESK-001', 'YJD-LAZY-SOFA-001', 'YJD-NIGHTSTAND-001',
|
|
'YJD-OFFICE-DESK-001', 'YJD-SHOECABINET-001', 'YJD-VANITY-001', 'ZH-BOOKCASE-001',
|
|
]);
|
|
const focus = id => catalog.templates.find(template => template.id === id).focus.join(' ');
|
|
assert.match(focus('GJ-DESK-DNZ0385'), /S17-I01 白底与层 3772/);
|
|
assert.match(focus('OYL-BOOKCASE-001'), /183\/184 的九个内嵌字段/);
|
|
assert.match(focus('SFY-COATRACK-001'), /S14\/S15 白底覆盖/);
|
|
assert.deepEqual(catalog.defaults.dimensions, Object.keys(rubric.dimensions));
|
|
const listed = await exec(process.execPath, [run, '--list']);
|
|
assert.equal(listed.stdout.trim().split(/\r?\n/u).length, 20);
|
|
});
|
|
|
|
test('CLI writes both reports even when there are no real recordings', async t => {
|
|
const { workspace } = await fixture(t);
|
|
const plan = path.join(workspace, '评测.json');
|
|
const out = path.join(workspace, '报告');
|
|
await writeJson(plan, { runs: [] });
|
|
await assert.rejects(exec(process.execPath, [run, '--plan', plan, '--out', out, '--dry-run']), { code: 2 });
|
|
const report = await readJson(path.join(out, 'report.json'));
|
|
assert.deepEqual(report.summary.counts, { passed: 0, failed: 0, unmeasured: 20 });
|
|
assert.match(await readFile(path.join(out, 'report.md'), 'utf8'), /待验证 20/);
|
|
});
|
|
|
|
test('CLI exercises real HTTP transport against a local judge and replays the result with no requests', async t => {
|
|
const { workspace, deliveryDir, manifest, save, contract, evidence } = await fixture(t);
|
|
await writeFile(path.join(workspace, '实拍.jpg'), jpeg);
|
|
await writeFile(path.join(workspace, '模板.png'), png);
|
|
const planPath = path.join(workspace, '评测.json');
|
|
const livePath = path.join(workspace, '在线报告');
|
|
const replayPath = path.join(workspace, '离线报告');
|
|
const inputs = [];
|
|
const server = createServer(async (req, res) => {
|
|
req.setEncoding('utf8');
|
|
let body = '';
|
|
for await (const part of req) body += part;
|
|
inputs.push({ url: req.url, auth: req.headers.authorization, body: JSON.parse(body) });
|
|
res.setHeader('Content-Type', 'application/json');
|
|
res.end(JSON.stringify({
|
|
model: 'fixture-vision-fixed',
|
|
choices: [{ message: { content: JSON.stringify({ dimensions: makeDimensions() }) } }],
|
|
usage: { prompt_tokens: 800, completion_tokens: 200 },
|
|
}));
|
|
});
|
|
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
t.after(() => new Promise(resolve => server.close(resolve)));
|
|
const env = { ...process.env, XIAOYI_EVAL_VLM_ENDPOINT: 'http://127.0.0.1:' + server.address().port + '/v1/chat/completions',
|
|
XIAOYI_EVAL_VLM_MODEL: 'fixture-vision-fixed', XIAOYI_EVAL_VLM_API_KEY: 'fixture-key' };
|
|
const visual = { assets: visualFiles, productFacts: { material: '原木' } };
|
|
const plan = {
|
|
judge: { pricing: { currency: 'CNY', inputPerMillion: 2, outputPerMillion: 8 } },
|
|
runs: [{
|
|
templateId, deliveryDir, contract, evidence, visual,
|
|
production: { modelId: 'fixture-production', protocol: 'fixture-wire', firstPass: true, cost: { currency: 'CNY', amount: 1.23 } },
|
|
}],
|
|
};
|
|
await writeJson(planPath, plan);
|
|
const args = [run, '--plan', planPath, '--template', templateId];
|
|
await exec(process.execPath, [...args, '--out', livePath, '--live'], { env });
|
|
assert.equal(inputs.length, 1);
|
|
assert.equal(inputs[0].url, '/v1/chat/completions');
|
|
assert.equal(inputs[0].auth, 'Bearer fixture-key');
|
|
assert.equal(inputs[0].body.model, 'fixture-vision-fixed');
|
|
const content = inputs[0].body.messages[0].content;
|
|
assert.match(content[0].text, /S17-I01/);
|
|
assert.deepEqual(content.filter(item => item.type === 'image_url').map(item => item.image_url.url.split(';')[0]),
|
|
['data:image/jpeg', 'data:image/png', 'data:image/jpeg']);
|
|
const live = await readJson(path.join(livePath, 'report.json'));
|
|
assert.deepEqual(live.summary.counts, { passed: 1, failed: 0, unmeasured: 0 });
|
|
assert.deepEqual(live.summary.firstPass, { measured: 1, passed: 1 });
|
|
assert.equal(live.summary.productionCost.CNY, 1.23);
|
|
assert.equal(live.summary.judgeCost.CNY, 0.0032);
|
|
|
|
visual.replay = path.join(livePath, 'replays', templateId + '.json');
|
|
await writeJson(planPath, plan);
|
|
await exec(process.execPath, [...args, '--out', replayPath], { env });
|
|
assert.equal(inputs.length, 1);
|
|
const replay = await readJson(path.join(replayPath, 'report.json'));
|
|
assert.deepEqual(replay.results[0].visual, live.results[0].visual);
|
|
assert.deepEqual(replay.summary.judgeCost, {});
|
|
|
|
const changed = path.join(workspace, '实拍.jpg');
|
|
await writeFile(changed, tallJpeg);
|
|
await assert.rejects(exec(process.execPath, [...args, '--out', replayPath, '--dry-run'], { env }), { code: 2 });
|
|
const stale = await readJson(path.join(replayPath, 'report.json'));
|
|
assert.match(stale.results[0].visual.reason, /不一致/);
|
|
assert.equal(inputs.length, 1);
|
|
|
|
manifest.allOutputsCompleted = false;
|
|
await save();
|
|
await assert.rejects(exec(process.execPath, [...args, '--out', replayPath, '--dry-run'], { env }), { code: 1 });
|
|
});
|
|
|
|
test('visual judge rejects invalid structured scores and unknown evidence IDs', async t => {
|
|
const { workspace } = await fixture(t);
|
|
await writeFile(path.join(workspace, '实拍.jpg'), jpeg);
|
|
await writeFile(path.join(workspace, '模板.png'), png);
|
|
const catalog = await readJson(catalogFile);
|
|
const dimensions = makeDimensions();
|
|
const input = {
|
|
baseDir: workspace, mode: 'live', template: catalog.templates[0], visual: { assets: visualFiles },
|
|
judge: { endpoint: 'https://example.invalid/v1/chat/completions', modelId: 'fixture' },
|
|
fetchImpl: async () => Response.json({ choices: [{ message: { content: JSON.stringify({ dimensions }) } }] }),
|
|
};
|
|
dimensions.lighting.score = 3;
|
|
assert.equal((await judgeVisual(input)).status, 'failed');
|
|
dimensions.lighting.score = 6;
|
|
await assert.rejects(judgeVisual(input), /视觉评分或证据无效 lighting/);
|
|
dimensions.lighting = { score: 4, evidence: '参考图', assetIds: ['missing-id'] };
|
|
await assert.rejects(judgeVisual(input), /视觉评分或证据无效 lighting/);
|
|
});
|
|
|
|
test('CLI maps passed, failed and unmeasured single-template dry-run outcomes to exit codes 0, 1 and 2', async t => {
|
|
const { workspace, deliveryDir, manifest, save, contract, evidence } = await fixture(t);
|
|
await writeFile(path.join(workspace, '实拍.jpg'), jpeg);
|
|
await writeFile(path.join(workspace, '模板.png'), png);
|
|
const replay = path.join(workspace, 'replay.json');
|
|
const recorded = await judgeVisual({
|
|
baseDir: workspace,
|
|
mode: 'live',
|
|
template: (await readJson(catalogFile)).templates[0],
|
|
visual: { assets: visualFiles, productFacts: { material: '原木' } },
|
|
judge: { endpoint: 'https://example.invalid/v1/chat/completions', modelId: 'fixture' },
|
|
fetchImpl: async () => Response.json({ choices: [{ message: { content: JSON.stringify({ dimensions: makeDimensions() }) } }] }),
|
|
});
|
|
await writeJson(replay, recorded);
|
|
const planPath = path.join(workspace, 'exit-codes.json');
|
|
const out = path.join(workspace, 'exit-out');
|
|
const visual = { assets: visualFiles, productFacts: { material: '原木' }, replay };
|
|
await writeJson(planPath, { runs: [{ templateId, deliveryDir, contract, evidence, visual }] });
|
|
const args = [run, '--plan', planPath, '--template', templateId, '--out', out, '--dry-run'];
|
|
|
|
await exec(process.execPath, args);
|
|
|
|
delete evidence.candidateIds;
|
|
await writeJson(planPath, { runs: [{ templateId, deliveryDir, contract, evidence, visual }] });
|
|
await assert.rejects(exec(process.execPath, args), { code: 2 });
|
|
|
|
manifest.allOutputsCompleted = false;
|
|
await save();
|
|
await assert.rejects(exec(process.execPath, args), { code: 1 });
|
|
});
|