Welcome to mirror list, hosted at ThFree Co, Russian Federation.

chai-extras.js « support « screenshot-testing « lib « tests - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 52c1b4bbbfd296a38ff0bfb20c266ddc2448eeed (plain)
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*!
 * Matomo - free/libre analytics platform
 *
 * chai assertion extensions
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

var fs = require('fs'),
    fsExtra = require('fs-extra'),
    path = require('path'),
    chai = require('chai'),
    chaiFiles = require('chai-files'),
    AssertionError = chai.AssertionError;
const { spawnSync } = require('child_process');

/**
 * Returns a chai plugin that adds the `.matchImage` assertion.
 *
 * Usage:
 *
 * var baseFilePath = '...';
 * chai.use(require('chai-image-assert')(baseFilePath));
 *
 */
module.exports = function makeChaiImageAssert(comparisonCommand = 'compare') {
    return function chaiImageAssert(chai, utils) {
        chai.Assertion.addMethod('matchImage', matchImage);

        function matchImage(params) {
            if (typeof params === 'string') {
                params = { imageName: params };
            }

            let { imageName, compareAgainst, comparisonThreshold, prefix } = params;

            if (!prefix) {
                prefix = app.runner.suite.title; // note: runner is made global by run-tests.js
            }

            imageName = prefix + '_' + imageName;

            compareAgainst = compareAgainst || imageName;

            imageName = assumeFileIsImageIfNotSpecified(imageName);
            compareAgainst = assumeFileIsImageIfNotSpecified(compareAgainst);

            const expectedPath = getExpectedFilePath(compareAgainst),
                processedPath = getProcessedFilePath(imageName);

            const processedScreenshotsPath = path.dirname(processedPath);

            if (!fs.isDirectory(processedScreenshotsPath)) {
                fs.mkdirSync(processedScreenshotsPath);
            }

            const imageBuffer = this._obj;

            chai.assert.instanceOf(imageBuffer, Buffer);
            fs.writeFileSync(processedPath, imageBuffer);

            try {
                if (!fs.isFile(expectedPath)) {
                    app.appendMissingExpected(imageName);
                    this.assert(false, `expected file at '${expectedPath}' does not exist`);
                } else {
                    var matches = compareImages(expectedPath, processedPath, comparisonThreshold);

                    this.assert(
                        matches,
                        `expected screenshot to match ${expectedPath}`,
                        `expected screenshot to not match ${expectedPath}`
                    );

                    performAutomaticPageChecks();
                }
            } catch (e) {
                fail(e.message);
            }

            function fail(message) {
                var testInfo = {
                    name: imageName,
                    processed: fs.isFile(processedPath) ? processedPath : null,
                    expected: fs.isFile(expectedPath) ? expectedPath : null,
                    baseDirectory: app.runner.suite.baseDirectory
                };

                if (options['assume-artifacts']) {
                    const diffPath = getDiffPath(imageName);

                    // copy to diff dir for ui tests viewer (we don't generate diffs w/ compare since it slows the tests a bit)
                    if (!fs.existsSync(diffPath)) {
                        fs.linkSync(expectedPath, diffPath);
                    }
                }

                var expectedPathStr = testInfo.expected ? path.resolve(testInfo.expected) : (expectedPath + " (not found)"),
                    processedPathStr = testInfo.processed ? path.resolve(testInfo.processed) : (processedPath + " (not found)");

                var indent = "     ";
                var failureInfo = message + "\n";
                failureInfo += indent + "Generated screenshot: " + processedPathStr + "\n";
                failureInfo += indent + "Expected screenshot: " + expectedPathStr + "\n";

                var error = new AssertionError(message);
                error.message = failureInfo;

                throw error;
            }
        }

        function compareImages(expectedPath, processedPath, comparisonThreshold) {
            const command = comparisonCommand,
                args = [
                    '-metric',
                    'ae',
                    expectedPath,
                    processedPath,
                    'null:'
                ];

            const result = spawnSync(command, args);

            chai.assert(!isCommandNotFound(result),
                `the '${comparisonCommand}' command was not found, ('compare' is provided by imagemagick)`);

            const allOutput = result.stdout.toString() + result.stderr.toString();
            const pixelError = parseInt(allOutput);

            chai.assert(!isNaN(pixelError),
                `the '${comparisonCommand}' command output could not be parsed, should be` +
                ` an integer, got: ${allOutput.replace(/\s+$/g, '')}`);

            if (result.status !== 0) {
                return false;
            }

            if (pixelError === 0) {
                return true;
            }

            if (comparisonThreshold) {
                const { imageWidth, imageHeight } = getImageDimensions(expectedPath);
                const area = imageWidth * imageHeight;
                const percentDifference = pixelError / area;

                chai.assert(percentDifference <= comparisonThreshold, `images differ by ${(percentDifference * 100).toFixed(2)}%, `
                    + `which is greater than threshold ${(comparisonThreshold * 100).toFixed(2)}% (command output: ${allOutput.replace(/\s+$/g, '')})`);
                return true;
            }

            // allow a 10 pixel difference only
            chai.assert(pixelError <= 10, `images differ in ${pixelError} pixels (command output: ${allOutput.replace(/\s+$/g, '')})`);

            return true;
        }

        function getImageDimensions(imagePath) {
            // NOTE: this method assumes 'identify' exists if 'compare' exists

            const commandArgs = [
                imagePath,
            ];

            const result = spawnSync('identify', commandArgs);
            const allOutput = (result.stdout || '').toString() + (result.stderr || '').toString();

            chai.assert(result.status === 0, `magick command failed, output: ${allOutput}`);

            const dimensions = allOutput.split(' ')[2];
            const [ imageWidth, imageHeight ] = dimensions.split('x');

            const dimsObj = {
                imageWidth: parseInt(imageWidth),
                imageHeight: parseInt(imageHeight),
            };

            chai.assert(!isNaN(dimsObj.imageWidth) && !isNaN(dimsObj.imageHeight),
                `Could not parse dimensions in magick output. Output: ${allOutput}`);

            return dimsObj;
        }
    };
};

expect.file = function (filename) {
    prefix = app.runner.suite.title; // note: runner is made global by run-tests.js
    filename = prefix + '_' + filename;

    return chai.expect(chaiFiles.file(getExpectedFilePath(filename)));
};

function isCommandNotFound(result) {
    return result.status === 127
        || (result.error != null && result.error.code === 'ENOENT');
}

function getExpectedScreenshotPath() {
    if (typeof config.expectedScreenshotsDir === 'string') {
        config.expectedScreenshotsDir = [config.expectedScreenshotsDir];
    }
    for (var dir in config.expectedScreenshotsDir) {
        var expectedScreenshotDir = path.join(app.runner.suite.baseDirectory, config.expectedScreenshotsDir[dir]);
        if (fs.isDirectory(expectedScreenshotDir)) {
            break;
        }
    }

    return expectedScreenshotDir;
}

function getExpectedFilePath(fileName) {
    fileName = assumeFileIsImageIfNotSpecified(fileName);

    return path.join(getExpectedScreenshotPath(), fileName);
}

function getProcessedFilePath(fileName) {
    var pathToUITests = options['store-in-ui-tests-repo'] ? uiTestsDir : app.runner.suite.baseDirectory;
    var processedScreenshotDir = path.join(pathToUITests, config.processedScreenshotsDir);

    if (!fs.isDirectory(processedScreenshotDir)) {
        fsExtra.mkdirsSync(processedScreenshotDir);
    }
    fileName = assumeFileIsImageIfNotSpecified(fileName);

    return path.join(processedScreenshotDir, fileName);
}

function assumeFileIsImageIfNotSpecified(filename) {
    if(!endsWith(filename, '.png') && !endsWith(filename, '.txt') ) {
        return filename + '.png';
    }
    return filename;
}

function endsWith(string, needle)
{
    return string.substr(-1 * needle.length, needle.length) === needle;
}

// other automatically run assertions
function performAutomaticPageChecks() {
    //checkForDangerousLinks();
}

function checkForDangerousLinks() {
    var links = page.webpage.evaluate(() => {
        try {
            var result = [];

            var linkElements = document.getElementsByTagName('a');
            for (var i = 0; i !== linkElements.length; ++i) {
                var element = linkElements.item(i);

                var href = element.getAttribute('href');
                if (/^(javascript|vbscript|data):/.test(href) && !isWhitelistedJavaScript(href)) {
                    result.push(element.innerText + ' - [href = ' + href + ']');
                }
            }

            return JSON.stringify(result);
        } catch (e) {
            return e.message || e;
        }

        function isWhitelistedJavaScript(href) {
            var whitelistedCode = [
                '',
                'void(0)',
                'window.history.back()',
                'window.location.reload()',
            ];

            var m = /^javascript:(.*?);*$/.exec(href);
            if (!m) {
                return false;
            }

            var code = m[1] || '';
            return whitelistedCode.indexOf(code) !== -1;
        }
    });
    expect(links, "found dangerous links").to.equal('{}');
}

function getDiffPath(testInfoName) {
    var baseDir = path.join(PIWIK_INCLUDE_PATH, 'tests/UI');
    return path.resolve(path.join(baseDir, config.screenshotDiffDir, testInfoName));
}