File size: 6,374 Bytes
1e92f2d |
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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
import fs from 'fs-extra';
import fg from 'fast-glob';
import path from 'path';
import { PNG } from 'pngjs';
// locked to v2.2.0
import {
getReportHtmlAfterPopulatingData,
getReportJsonWithTotalStats,
} from 'cypress-image-diff-html-report/dist/common/utils';
import type { IBadCase } from './build';
const ROOT = path.resolve(__dirname, '../../');
const REPORT_DIR = path.join(ROOT, 'visualRegressionReport');
const components = fg
.sync('components/*/index.ts[x]', { cwd: ROOT })
.reduce((acc, file) => {
const basePath = path.dirname(file);
if (
[
fs.existsSync(path.join(basePath, 'index.en-US.md')),
fs.existsSync(path.join(basePath, 'demo')),
fs.existsSync(path.join(basePath, '__tests__')),
].every(Boolean)
) {
acc.push(path.basename(basePath));
}
return acc;
}, [] as string[])
.sort((a, b) => b.length - a.length);
const processedComponents = new Set<string>();
const extractFilenameComponents = (filename: string) => {
const parts = filename.split('.');
const isCssVar = filename.endsWith('.css-var.png');
const [firstHalf, theme] = parts as any[];
let componentName = '';
let demoName = '';
for (const component of components) {
if (firstHalf?.length && firstHalf.startsWith(component)) {
componentName = component;
demoName = firstHalf.slice(component.length + 1);
processedComponents.add(component);
break;
}
}
return {
componentName,
demoName,
theme,
isCssVar,
};
};
// https://placehold.co/
const imagesPlaceHold = {
genMissing: (w = 680, h = 280) =>
`https://placehold.co/${w}x${h}/transparent/red?text=MISS&font=lora`,
getRemoved: (w = 680, h = 280) =>
`https://placehold.co/${w}x${h}/transparent/red?text=REMOVED&font=lora`,
getAdded: (w = 680, h = 280) =>
`https://placehold.co/${w}x${h}/transparent/green?text=ADDED&font=lora`,
};
const getImageSize = (imagePath: string) => {
const png = PNG.sync.read(fs.readFileSync(imagePath));
return {
width: Math.floor(png.width),
height: Math.floor(png.height),
};
};
/**
* 转化为特定格式 (cypress-image-diff-html-report 格式) 的报告
* @example-json https://github.com/kien-ht/cypress-image-diff-html-report/blob/v2.2.0/playground/example.json
* @type https://github.com/kien-ht/cypress-image-diff-html-report/blob/v2.2.0/src/common/types.ts
*/
const convertReport = (options: Required<Options>) => {
const { badCases, publicPath } = options;
const total = badCases.length;
const suites: any[] = [];
const processedBadCases = badCases.map((badCase) => ({
raw: badCase,
...extractFilenameComponents(badCase.filename),
}));
Array.from(processedComponents)
.sort((a, b) => b.length - a.length)
.forEach((component) => {
const componentBadCases = processedBadCases.filter(
(badCase) => badCase.componentName === component,
);
const specPath = path.join('components', component, '__tests__/image.test.ts');
const tests = componentBadCases.map((badCase) => {
let baselinePath;
let comparisonPath;
let diffPath;
const { filename, type } = badCase.raw;
if (type === 'changed') {
baselinePath = `${publicPath}/images/base/${filename}`;
comparisonPath = `${publicPath}/images/current/${filename}`;
diffPath = `${publicPath}/images/diff/${filename}`;
} else if (type === 'removed') {
const pathSuffix = `images/base/${filename}`;
const { width, height } = getImageSize(path.join(REPORT_DIR, pathSuffix));
baselinePath = `${publicPath}/${pathSuffix}`;
comparisonPath = imagesPlaceHold.genMissing(width, height); // Missing
diffPath = imagesPlaceHold.getRemoved(width, height); // Removed
} else if (type === 'added') {
const pathSuffix = `images/current/${filename}`;
const { width, height } = getImageSize(path.join(REPORT_DIR, pathSuffix));
baselinePath = imagesPlaceHold.genMissing(width, height); // Missing
comparisonPath = `${publicPath}/${pathSuffix}`;
diffPath = imagesPlaceHold.getAdded(width, height); // Added
}
const name = [
`components/${badCase.componentName}/demo/${badCase.demoName}.tsx`,
`[${badCase.theme}]`,
badCase.isCssVar && '(CSS Var)',
]
.filter(Boolean)
.join(' ');
// https://github.com/kien-ht/cypress-image-diff-html-report/blob/v2.2.0/playground/example.json#L61-L70
return {
status: 'fail',
name,
percentage: badCase.raw.weight,
failureThreshold: 0.1, // 由 scripts/visual-regression/build.ts 决定
specPath,
specFilename: path.basename(specPath),
baselinePath,
diffPath,
comparisonPath,
};
});
// https://github.com/kien-ht/cypress-image-diff-html-report/blob/v2.2.0/playground/example.json#L57-L73
const suite = {
name: component,
path: specPath,
tests,
};
suites.push(suite);
});
return {
total,
totalPassed: 0,
totalFailed: total,
suites: suites.sort((a, b) => a.name.localeCompare(b.name)),
// \\\\\\ 不那么重要的字段 \\\\\\
startedAt: new Date().toISOString(),
endedAt: new Date().toISOString(),
duration: Math.floor(Math.random() * 1000),
browserName: 'chrome',
browserVersion: 'unknown',
cypressVersion: '10.8.0', // 写死
};
};
interface Options {
badCases: IBadCase[];
publicPath?: string;
}
const defaultOptions: Required<Options> = {
badCases: [],
publicPath: '.',
};
export const generate = async (opt: Options) => {
const options = { ...defaultOptions, ...opt };
const reportJson = convertReport(options);
// copied from https://github.com/kien-ht/cypress-image-diff-html-report/blob/v2.2.0/src/core.ts#L17-L27
const jsonWithTotalStats = getReportJsonWithTotalStats(reportJson as any);
const html = await getReportHtmlAfterPopulatingData(jsonWithTotalStats);
const target = path.join(REPORT_DIR, 'index.html');
try {
await fs.ensureFile(target);
await fs.writeFile(target, html);
} catch (err) {
fs.removeSync(target);
throw new Error((err as Error).message);
}
};
|