File size: 6,886 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | const {chromium} = require('playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const {pathToFileURL} = require('node:url');
function affineFit(values, positions, increasing) {
const xMean = values.reduce((a, b) => a + b, 0) / values.length;
const yMean = positions.reduce((a, b) => a + b, 0) / positions.length;
const variance = values.reduce((sum, x) => sum + (x - xMean) ** 2, 0);
if (!variance) return positions.every(y => Math.abs(y - yMean) <= 1);
const slope = values.reduce((sum, x, i) => sum + (x - xMean) * (positions[i] - yMean), 0) / variance;
return (increasing ? slope > 0 : slope < 0) && values.every((x, i) =>
Math.abs(positions[i] - (yMean + slope * (x - xMean))) <= 1);
}
(async () => {
const browser = await chromium.launch({headless: true, args: ['--no-sandbox']});
try {
const page = await browser.newPage({viewport: {width: 1100, height: 760}});
await page.route(/^https?:/, route => route.abort());
await page.goto(pathToFileURL(path.join(process.cwd(), 'report.html')).href);
const allVisible = await page.locator('#gdp-life-scatter, #gdp-life-scatter [data-country], #continent-population-bars, #continent-population-bars rect').evaluateAll(elements => elements.every(element => {
for (let node = element; node; node = node.parentElement) {
const style = getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false;
}
return true;
}));
assert(allVisible, 'chart or marks are hidden by their ancestors');
const points = await page.locator('#gdp-life-scatter [data-country]').evaluateAll(elements => elements.map(element => {
const box = element.getBoundingClientRect(), style = getComputedStyle(element);
return {country: element.dataset.country, continent: element.dataset.continent,
gdp: Number(element.dataset.gdp), life: Number(element.dataset.life),
x: box.x + box.width / 2, y: box.y + box.height / 2, color: style.fill,
visible: box.width > 0 && box.height > 0 && style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity) > 0};
}));
assert(points.length && points.every(point => point.visible), 'every country needs a visible scatter mark');
const colors = new Map();
for (const point of points) {
assert(point.color !== 'none' && point.color !== 'rgba(0, 0, 0, 0)', 'scatter mark has no visible color');
if (!colors.has(point.continent)) colors.set(point.continent, point.color);
assert.equal(colors.get(point.continent), point.color, 'continent colors are inconsistent');
}
assert.equal(new Set(colors.values()).size, colors.size, 'continents must have distinct colors');
for (const id of ['gdp-axis-label', 'life-axis-label']) {
const label = page.locator('#' + id);
assert(await label.isVisible() && (await label.textContent()).trim(), 'scatter axes need visible labels');
}
const ticks = await page.locator('#gdp-life-scatter text:visible, #gdp-life-scatter foreignObject:visible')
.evaluateAll(labels => labels.filter(label => {
const style = getComputedStyle(label);
return label.getBoundingClientRect().width > 0 && Number(style.opacity) > 0
&& /^[-+−]?[$€£]?\s*\d[\d,.\s]*(?:[eE][+-]?\d+|[kKmMbB万亿])?$/.test(label.textContent.trim());
}).length);
assert(ticks >= 2, 'scatter chart must display numeric tick labels');
for (const [continent, color] of colors) {
const legend = page.locator('#continent-legend [data-continent]').filter({hasText: continent});
assert(await legend.count() === 1 && await legend.isVisible(), 'each continent needs a visible color legend');
assert(await legend.evaluate(element => {
const style = getComputedStyle(element); return [style.color, style.fill];
}).then(values => values.includes(color)), 'legend color must agree with plotted continent');
}
const gdp = points.map(point => point.gdp), x = points.map(point => point.x);
const linear = affineFit(gdp, x, true);
const logarithmic = affineFit(gdp.map(Math.log), x, true);
assert(linear || logarithmic, 'scatter horizontal position does not encode GDP');
if (!linear) assert(/log|对数/i.test(await page.locator('body').innerText()), 'logarithmic axis must be labeled');
assert(affineFit(points.map(point => point.life), points.map(point => point.y), false), 'scatter vertical position does not encode life expectancy');
for (const selector of ['#continent-population', '#continent-population-bars', '#fastest-growth'])
assert(await page.locator(selector).isVisible(), `${selector} is hidden`);
const fastest = page.locator('#fastest-growth');
const visibleNumbers = text => Array.from(text.matchAll(/([+-]?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*(billion|million|千|万|亿)?/gi),
match => Number(match[1].replaceAll(',', '')) *
({billion: 1e9, million: 1e6, 千: 1e3, 万: 1e4, 亿: 1e8}[match[2]?.toLowerCase()] ?? 1));
const growthText = await fastest.innerText();
assert(growthText.includes(await fastest.getAttribute('data-country')), 'fastest-growth country exists only in metadata');
const growth = Number(await fastest.getAttribute('data-absolute-growth'));
assert(visibleNumbers(growthText).some(value => Math.abs(value - growth) <= Math.max(0.51, Math.abs(growth) * 1e-6)),
'the fastest-growing country must show its increase in people');
const populationRows = page.locator('#continent-population tr[data-continent]');
for (const row of await populationRows.all()) {
const {continent, mean, visibleCells} = await row.evaluate(element => ({
continent: element.dataset.continent,
mean: Number(element.dataset.meanPop),
visibleCells: Array.from(element.cells).filter(cell => {
const style = getComputedStyle(cell);
return cell.getClientRects().length && style.visibility !== 'hidden' && Number(style.opacity) > 0;
}).map(cell => cell.innerText),
}));
assert(await row.isVisible() && visibleCells.some(text => text.includes(continent)), 'continent must be visible on its population row');
const displayed = visibleCells.flatMap(visibleNumbers);
assert(displayed.some(value => Math.abs(value - mean) <= Math.max(0.51, Math.abs(mean) * 1e-6)),
`population table must display ${continent}'s mean on that row`);
}
fs.mkdirSync('/logs/verifier/visual-audit', {recursive: true});
await page.screenshot({path: `/logs/verifier/visual-audit/${process.env.GAPMINDER_SCREENSHOT || 'gapminder-report'}.png`, fullPage: true});
} finally {
await browser.close();
}
})().catch(error => {console.error(error); process.exit(1)});
|