-
Notifications
You must be signed in to change notification settings - Fork 203
/
Copy pathdiff-snapshot.js
263 lines (232 loc) · 8.49 KB
/
diff-snapshot.js
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/*
* Copyright (c) 2017 American Express Travel Related Services Company, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
const childProcess = require('child_process');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const pixelmatch = require('pixelmatch');
const { PNG } = require('pngjs');
const rimraf = require('rimraf');
const { createHash } = require('crypto');
const glur = require('glur');
const ImageComposer = require('./image-composer');
/**
* Helper function to create reusable image resizer
*/
const createImageResizer = (width, height) => (source) => {
const resized = new PNG({ width, height, fill: true });
PNG.bitblt(source, resized, 0, 0, source.width, source.height, 0, 0);
return resized;
};
/**
* Fills diff area with black transparent color for meaningful diff
*/
/* eslint-disable no-plusplus, no-param-reassign, no-bitwise */
const fillSizeDifference = (width, height) => (image) => {
const inArea = (x, y) => y > height || x > width;
for (let y = 0; y < image.height; y++) {
for (let x = 0; x < image.width; x++) {
if (inArea(x, y)) {
const idx = ((image.width * y) + x) << 2;
image.data[idx] = 0;
image.data[idx + 1] = 0;
image.data[idx + 2] = 0;
image.data[idx + 3] = 64;
}
}
}
return image;
};
/* eslint-enabled */
/**
* Aligns images sizes to biggest common value
* and fills new pixels with transparent pixels
*/
const alignImagesToSameSize = (firstImage, secondImage) => {
// Keep original sizes to fill extended area later
const firstImageWidth = firstImage.width;
const firstImageHeight = firstImage.height;
const secondImageWidth = secondImage.width;
const secondImageHeight = secondImage.height;
// Calculate biggest common values
const resizeToSameSize = createImageResizer(
Math.max(firstImageWidth, secondImageWidth),
Math.max(firstImageHeight, secondImageHeight)
);
// Resize both images
const resizedFirst = resizeToSameSize(firstImage);
const resizedSecond = resizeToSameSize(secondImage);
// Fill resized area with black transparent pixels
return [
fillSizeDifference(firstImageWidth, firstImageHeight)(resizedFirst),
fillSizeDifference(secondImageWidth, secondImageHeight)(resizedSecond),
];
};
const isFailure = ({ pass, updateSnapshot }) => !pass && !updateSnapshot;
const shouldUpdate = ({ pass, updateSnapshot, updatePassedSnapshot }) => (
(!pass && updateSnapshot) || (pass && updatePassedSnapshot)
);
function diffImageToSnapshot(options) {
/* eslint complexity: ["error", 12] */
const {
receivedImageBuffer,
snapshotIdentifier,
snapshotsDir,
diffDir,
diffDirection,
updateSnapshot = false,
updatePassedSnapshot = false,
customDiffConfig = {},
failureThreshold,
failureThresholdType,
blur,
} = options;
let result = {};
const baselineSnapshotPath = path.join(snapshotsDir, `${snapshotIdentifier}-snap.png`);
if (!fs.existsSync(baselineSnapshotPath)) {
mkdirp.sync(snapshotsDir);
fs.writeFileSync(baselineSnapshotPath, receivedImageBuffer);
result = { added: true };
} else {
const diffOutputPath = path.join(diffDir, `${snapshotIdentifier}-diff.png`);
rimraf.sync(diffOutputPath);
const defaultDiffConfig = {
threshold: 0.01,
};
const diffConfig = Object.assign({}, defaultDiffConfig, customDiffConfig);
const rawReceivedImage = PNG.sync.read(receivedImageBuffer);
const rawBaselineImage = PNG.sync.read(fs.readFileSync(baselineSnapshotPath));
const hasSizeMismatch = (
rawReceivedImage.height !== rawBaselineImage.height ||
rawReceivedImage.width !== rawBaselineImage.width
);
const imageDimensions = {
receivedHeight: rawReceivedImage.height,
receivedWidth: rawReceivedImage.width,
baselineHeight: rawBaselineImage.height,
baselineWidth: rawBaselineImage.width,
};
// Align images in size if different
const [receivedImage, baselineImage] = hasSizeMismatch
? alignImagesToSameSize(rawReceivedImage, rawBaselineImage)
: [rawReceivedImage, rawBaselineImage];
const imageWidth = receivedImage.width;
const imageHeight = receivedImage.height;
if (typeof blur === 'number' && blur > 0) {
glur(receivedImage.data, imageWidth, imageHeight, blur);
glur(baselineImage.data, imageWidth, imageHeight, blur);
}
const diffImage = new PNG({ width: imageWidth, height: imageHeight });
let pass = false;
let diffSize = false;
let diffRatio = 0;
let diffPixelCount = 0;
const receivedImageDigest = createHash('sha1').update(receivedImage.data).digest('base64');
const baselineImageDigest = createHash('sha1').update(baselineImage.data).digest('base64');
pass = receivedImageDigest === baselineImageDigest;
if (!pass) {
diffPixelCount = pixelmatch(
receivedImage.data,
baselineImage.data,
diffImage.data,
imageWidth,
imageHeight,
diffConfig
);
const totalPixels = imageWidth * imageHeight;
diffRatio = diffPixelCount / totalPixels;
// Always fail test on image size mismatch
if (hasSizeMismatch) {
pass = false;
diffSize = true;
} else if (failureThresholdType === 'pixel') {
pass = diffPixelCount <= failureThreshold;
} else if (failureThresholdType === 'percent') {
pass = diffRatio <= failureThreshold;
} else {
throw new Error(`Unknown failureThresholdType: ${failureThresholdType}. Valid options are "pixel" or "percent".`);
}
}
if (isFailure({ pass, updateSnapshot })) {
mkdirp.sync(diffDir);
const composer = new ImageComposer({
direction: diffDirection,
});
composer.addImage(baselineImage, imageWidth, imageHeight);
composer.addImage(diffImage, imageWidth, imageHeight);
composer.addImage(receivedImage, imageWidth, imageHeight);
const composerParams = composer.getParams();
const compositeResultImage = new PNG({
width: composerParams.compositeWidth,
height: composerParams.compositeHeight,
});
// copy baseline, diff, and received images into composite result image
composerParams.images.forEach((image, index) => {
PNG.bitblt(
image.imageData, compositeResultImage, 0, 0, image.imageWidth, image.imageHeight,
composerParams.offsetX * index, composerParams.offsetY * index
);
});
// Set filter type to Paeth to avoid expensive auto scanline filter detection
// For more information see https://www.w3.org/TR/PNG-Filters.html
const pngBuffer = PNG.sync.write(compositeResultImage, { filterType: 4 });
fs.writeFileSync(diffOutputPath, pngBuffer);
result = {
pass: false,
diffSize,
imageDimensions,
diffOutputPath,
diffRatio,
diffPixelCount,
imgSrcString: `data:image/png;base64,${pngBuffer.toString('base64')}`,
};
} else if (shouldUpdate({ pass, updateSnapshot, updatePassedSnapshot })) {
mkdirp.sync(snapshotsDir);
fs.writeFileSync(baselineSnapshotPath, receivedImageBuffer);
result = { updated: true };
} else {
result = {
pass,
diffRatio,
diffPixelCount,
diffOutputPath,
};
}
}
return result;
}
function runDiffImageToSnapshot(options) {
options.receivedImageBuffer = options.receivedImageBuffer.toString('base64');
const serializedInput = JSON.stringify(options);
let result = {};
const writeDiffProcess = childProcess.spawnSync(
process.execPath, [`${__dirname}/diff-process.js`],
{
input: Buffer.from(serializedInput),
stdio: ['pipe', 'inherit', 'inherit', 'pipe'],
maxBuffer: 10 * 1024 * 1024, // 10 MB
}
);
if (writeDiffProcess.status === 0) {
const output = writeDiffProcess.output[3].toString();
result = JSON.parse(output);
} else {
throw new Error('Error running image diff.');
}
return result;
}
module.exports = {
diffImageToSnapshot,
runDiffImageToSnapshot,
};