2021-07-28 05:26:12 +02:00
|
|
|
/**
|
|
|
|
|
* Copyright Microsoft Corporation. All rights reserved.
|
|
|
|
|
*
|
|
|
|
|
* 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.
|
|
|
|
|
*/
|
|
|
|
|
|
2022-04-06 23:57:14 +02:00
|
|
|
import type { Locator, Page } from 'playwright-core';
|
2022-02-28 21:25:59 +01:00
|
|
|
import type { Page as PageEx } from 'playwright-core/lib/client/page';
|
|
|
|
|
import type { Locator as LocatorEx } from 'playwright-core/lib/client/locator';
|
2023-01-27 21:44:15 +01:00
|
|
|
import { currentTestInfo, currentExpectTimeout } from '../common/globals';
|
2023-01-13 22:50:38 +01:00
|
|
|
import type { ImageComparatorOptions, Comparator } from 'playwright-core/lib/utils';
|
|
|
|
|
import { getComparator } from 'playwright-core/lib/utils';
|
2022-02-28 21:25:59 +01:00
|
|
|
import type { PageScreenshotOptions } from 'playwright-core/types/types';
|
2022-03-15 02:01:13 +01:00
|
|
|
import {
|
2023-07-14 15:33:48 +02:00
|
|
|
addSuffixToFilePath, serializeError, sanitizeForFilePath,
|
2023-01-27 21:44:15 +01:00
|
|
|
trimLongString, callLogText,
|
2023-02-21 23:15:11 +01:00
|
|
|
expectTypes } from '../util';
|
2022-04-19 02:50:25 +02:00
|
|
|
import { colors } from 'playwright-core/lib/utilsBundle';
|
2022-02-18 20:21:58 +01:00
|
|
|
import fs from 'fs';
|
|
|
|
|
import path from 'path';
|
2022-04-19 05:20:49 +02:00
|
|
|
import { mime } from 'playwright-core/lib/utilsBundle';
|
2023-02-10 04:22:17 +01:00
|
|
|
import type { TestInfoImpl } from '../worker/testInfo';
|
2023-06-20 00:18:59 +02:00
|
|
|
import type { ExpectMatcherContext, SyncExpectationResult } from './expect';
|
2021-07-28 05:26:12 +02:00
|
|
|
|
2021-10-01 18:15:44 +02:00
|
|
|
type NameOrSegments = string | string[];
|
2022-03-31 23:11:34 +02:00
|
|
|
const snapshotNamesSymbol = Symbol('snapshotNames');
|
|
|
|
|
|
|
|
|
|
type SnapshotNames = {
|
|
|
|
|
anonymousSnapshotIndex: number;
|
|
|
|
|
namedSnapshotIndex: { [key: string]: number };
|
|
|
|
|
};
|
2022-02-18 20:21:58 +01:00
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
class SnapshotHelper<T extends ImageComparatorOptions> {
|
|
|
|
|
readonly testInfo: TestInfoImpl;
|
2022-03-31 23:11:34 +02:00
|
|
|
readonly snapshotName: string;
|
2022-02-23 22:17:37 +01:00
|
|
|
readonly expectedPath: string;
|
2022-03-11 17:46:13 +01:00
|
|
|
readonly previousPath: string;
|
2022-02-23 22:17:37 +01:00
|
|
|
readonly snapshotPath: string;
|
|
|
|
|
readonly actualPath: string;
|
|
|
|
|
readonly diffPath: string;
|
|
|
|
|
readonly mimeType: string;
|
2022-02-28 21:25:59 +01:00
|
|
|
readonly kind: 'Screenshot'|'Snapshot';
|
2022-04-27 17:14:37 +02:00
|
|
|
readonly updateSnapshots: 'all' | 'none' | 'missing';
|
2022-02-28 21:25:59 +01:00
|
|
|
readonly comparatorOptions: ImageComparatorOptions;
|
2022-03-22 00:42:21 +01:00
|
|
|
readonly comparator: Comparator;
|
2022-02-28 21:25:59 +01:00
|
|
|
readonly allOptions: T;
|
2022-02-23 22:17:37 +01:00
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
|
testInfo: TestInfoImpl,
|
2022-03-11 01:50:26 +01:00
|
|
|
snapshotPathResolver: (...pathSegments: string[]) => string,
|
2022-02-23 22:17:37 +01:00
|
|
|
anonymousSnapshotExtension: string,
|
2022-03-05 02:30:43 +01:00
|
|
|
configOptions: ImageComparatorOptions,
|
2022-02-23 22:17:37 +01:00
|
|
|
nameOrOptions: NameOrSegments | { name?: NameOrSegments } & T,
|
|
|
|
|
optOptions: T,
|
|
|
|
|
) {
|
|
|
|
|
let options: T;
|
|
|
|
|
let name: NameOrSegments | undefined;
|
|
|
|
|
if (Array.isArray(nameOrOptions) || typeof nameOrOptions === 'string') {
|
|
|
|
|
name = nameOrOptions;
|
|
|
|
|
options = optOptions;
|
|
|
|
|
} else {
|
|
|
|
|
name = nameOrOptions.name;
|
|
|
|
|
options = { ...nameOrOptions };
|
|
|
|
|
delete (options as any).name;
|
|
|
|
|
}
|
2022-03-31 23:11:34 +02:00
|
|
|
|
|
|
|
|
let snapshotNames = (testInfo as any)[snapshotNamesSymbol] as SnapshotNames;
|
|
|
|
|
if (!(testInfo as any)[snapshotNamesSymbol]) {
|
|
|
|
|
snapshotNames = {
|
|
|
|
|
anonymousSnapshotIndex: 0,
|
|
|
|
|
namedSnapshotIndex: {},
|
|
|
|
|
};
|
|
|
|
|
(testInfo as any)[snapshotNamesSymbol] = snapshotNames;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Consider the use case below. We should save actual to different paths.
|
|
|
|
|
//
|
|
|
|
|
// expect.toMatchSnapshot('a.png')
|
|
|
|
|
// // noop
|
|
|
|
|
// expect.toMatchSnapshot('a.png')
|
|
|
|
|
|
|
|
|
|
let actualModifier = '';
|
2022-02-23 22:17:37 +01:00
|
|
|
if (!name) {
|
|
|
|
|
const fullTitleWithoutSpec = [
|
|
|
|
|
...testInfo.titlePath.slice(1),
|
2022-03-31 23:11:34 +02:00
|
|
|
++snapshotNames.anonymousSnapshotIndex,
|
2022-02-23 22:17:37 +01:00
|
|
|
].join(' ');
|
|
|
|
|
name = sanitizeForFilePath(trimLongString(fullTitleWithoutSpec)) + '.' + anonymousSnapshotExtension;
|
2022-03-31 23:11:34 +02:00
|
|
|
this.snapshotName = name;
|
|
|
|
|
} else {
|
|
|
|
|
const joinedName = Array.isArray(name) ? name.join(path.sep) : name;
|
|
|
|
|
snapshotNames.namedSnapshotIndex[joinedName] = (snapshotNames.namedSnapshotIndex[joinedName] || 0) + 1;
|
|
|
|
|
const index = snapshotNames.namedSnapshotIndex[joinedName];
|
|
|
|
|
if (index > 1) {
|
|
|
|
|
actualModifier = `-${index - 1}`;
|
|
|
|
|
this.snapshotName = `${joinedName}-${index - 1}`;
|
|
|
|
|
} else {
|
|
|
|
|
this.snapshotName = joinedName;
|
|
|
|
|
}
|
2022-02-23 22:17:37 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
options = {
|
2022-03-05 02:30:43 +01:00
|
|
|
...configOptions,
|
2022-02-23 22:17:37 +01:00
|
|
|
...options,
|
|
|
|
|
};
|
|
|
|
|
|
2022-03-04 08:17:31 +01:00
|
|
|
if (options.maxDiffPixels !== undefined && options.maxDiffPixels < 0)
|
|
|
|
|
throw new Error('`maxDiffPixels` option value must be non-negative integer');
|
2022-02-23 22:17:37 +01:00
|
|
|
|
2022-03-04 08:17:31 +01:00
|
|
|
if (options.maxDiffPixelRatio !== undefined && (options.maxDiffPixelRatio < 0 || options.maxDiffPixelRatio > 1))
|
|
|
|
|
throw new Error('`maxDiffPixelRatio` option value must be between 0 and 1');
|
2022-02-23 22:17:37 +01:00
|
|
|
|
|
|
|
|
// sanitizes path if string
|
2022-03-31 23:11:34 +02:00
|
|
|
const inputPathSegments = Array.isArray(name) ? name : [addSuffixToFilePath(name, '', undefined, true)];
|
|
|
|
|
const outputPathSegments = Array.isArray(name) ? name : [addSuffixToFilePath(name, actualModifier, undefined, true)];
|
|
|
|
|
this.snapshotPath = snapshotPathResolver(...inputPathSegments);
|
2023-07-10 18:45:24 +02:00
|
|
|
const inputFile = testInfo._getOutputPath(...inputPathSegments);
|
|
|
|
|
const outputFile = testInfo._getOutputPath(...outputPathSegments);
|
2022-03-31 23:11:34 +02:00
|
|
|
this.expectedPath = addSuffixToFilePath(inputFile, '-expected');
|
2022-03-11 17:46:13 +01:00
|
|
|
this.previousPath = addSuffixToFilePath(outputFile, '-previous');
|
|
|
|
|
this.actualPath = addSuffixToFilePath(outputFile, '-actual');
|
|
|
|
|
this.diffPath = addSuffixToFilePath(outputFile, '-diff');
|
|
|
|
|
|
|
|
|
|
this.updateSnapshots = testInfo.config.updateSnapshots;
|
|
|
|
|
if (this.updateSnapshots === 'missing' && testInfo.retry < testInfo.project.retries)
|
|
|
|
|
this.updateSnapshots = 'none';
|
|
|
|
|
this.mimeType = mime.getType(path.basename(this.snapshotPath)) ?? 'application/octet-string';
|
2022-03-22 00:42:21 +01:00
|
|
|
this.comparator = getComparator(this.mimeType);
|
2022-02-23 22:17:37 +01:00
|
|
|
|
|
|
|
|
this.testInfo = testInfo;
|
2022-02-28 21:25:59 +01:00
|
|
|
this.allOptions = options;
|
|
|
|
|
this.comparatorOptions = {
|
2022-03-04 08:17:31 +01:00
|
|
|
maxDiffPixels: options.maxDiffPixels,
|
|
|
|
|
maxDiffPixelRatio: options.maxDiffPixelRatio,
|
2022-02-28 21:25:59 +01:00
|
|
|
threshold: options.threshold,
|
2023-02-13 20:11:44 +01:00
|
|
|
_comparator: options._comparator,
|
2022-02-28 21:25:59 +01:00
|
|
|
};
|
|
|
|
|
this.kind = this.mimeType.startsWith('image/') ? 'Screenshot' : 'Snapshot';
|
2022-02-18 20:21:58 +01:00
|
|
|
}
|
2022-02-23 22:17:37 +01:00
|
|
|
|
|
|
|
|
handleMissingNegated() {
|
|
|
|
|
const isWriteMissingMode = this.updateSnapshots === 'all' || this.updateSnapshots === 'missing';
|
2022-11-29 21:51:15 +01:00
|
|
|
const message = `A snapshot doesn't exist at ${this.snapshotPath}${isWriteMissingMode ? ', matchers using ".not" won\'t write them automatically.' : '.'}`;
|
2022-04-06 02:47:35 +02:00
|
|
|
return {
|
2022-02-23 22:17:37 +01:00
|
|
|
// NOTE: 'isNot' matcher implies inversed value.
|
|
|
|
|
pass: true,
|
|
|
|
|
message: () => message,
|
2022-04-06 02:47:35 +02:00
|
|
|
};
|
2022-02-16 23:22:01 +01:00
|
|
|
}
|
2021-07-28 05:26:12 +02:00
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
handleDifferentNegated() {
|
|
|
|
|
// NOTE: 'isNot' matcher implies inversed value.
|
2022-04-06 02:47:35 +02:00
|
|
|
return { pass: false, message: () => '' };
|
2022-02-23 22:17:37 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
handleMatchingNegated() {
|
|
|
|
|
const message = [
|
2022-02-28 21:25:59 +01:00
|
|
|
colors.red(`${this.kind} comparison failed:`),
|
2022-02-23 22:17:37 +01:00
|
|
|
'',
|
|
|
|
|
indent('Expected result should be different from the actual one.', ' '),
|
|
|
|
|
].join('\n');
|
|
|
|
|
// NOTE: 'isNot' matcher implies inversed value.
|
2022-04-06 02:47:35 +02:00
|
|
|
return { pass: true, message: () => message };
|
2022-02-23 22:17:37 +01:00
|
|
|
}
|
2022-02-18 00:44:03 +01:00
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
handleMissing(actual: Buffer | string) {
|
|
|
|
|
const isWriteMissingMode = this.updateSnapshots === 'all' || this.updateSnapshots === 'missing';
|
|
|
|
|
if (isWriteMissingMode) {
|
|
|
|
|
writeFileSync(this.snapshotPath, actual);
|
|
|
|
|
writeFileSync(this.actualPath, actual);
|
2023-06-05 23:57:06 +02:00
|
|
|
this.testInfo.attachments.push({ name: addSuffixToFilePath(this.snapshotName, '-actual'), contentType: this.mimeType, path: this.actualPath });
|
2022-02-23 22:17:37 +01:00
|
|
|
}
|
2022-11-29 21:51:15 +01:00
|
|
|
const message = `A snapshot doesn't exist at ${this.snapshotPath}${isWriteMissingMode ? ', writing actual.' : '.'}`;
|
2022-02-23 22:17:37 +01:00
|
|
|
if (this.updateSnapshots === 'all') {
|
|
|
|
|
/* eslint-disable no-console */
|
|
|
|
|
console.log(message);
|
2022-04-06 02:47:35 +02:00
|
|
|
return { pass: true, message: () => message };
|
2022-02-23 22:17:37 +01:00
|
|
|
}
|
|
|
|
|
if (this.updateSnapshots === 'missing') {
|
|
|
|
|
this.testInfo._failWithError(serializeError(new Error(message)), false /* isHardError */);
|
2022-04-06 02:47:35 +02:00
|
|
|
return { pass: true, message: () => '' };
|
2022-02-23 22:17:37 +01:00
|
|
|
}
|
2022-04-06 02:47:35 +02:00
|
|
|
return { pass: false, message: () => message };
|
2022-02-23 22:17:37 +01:00
|
|
|
}
|
2022-02-18 00:44:03 +01:00
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
handleDifferent(
|
|
|
|
|
actual: Buffer | string | undefined,
|
|
|
|
|
expected: Buffer | string | undefined,
|
2022-03-11 17:46:13 +01:00
|
|
|
previous: Buffer | string | undefined,
|
2022-02-23 22:17:37 +01:00
|
|
|
diff: Buffer | string | undefined,
|
|
|
|
|
diffError: string | undefined,
|
|
|
|
|
log: string[] | undefined,
|
2022-02-28 21:25:59 +01:00
|
|
|
title = `${this.kind} comparison failed:`) {
|
2022-02-23 22:17:37 +01:00
|
|
|
const output = [
|
|
|
|
|
colors.red(title),
|
|
|
|
|
'',
|
|
|
|
|
];
|
2022-03-12 07:40:28 +01:00
|
|
|
if (diffError)
|
|
|
|
|
output.push(indent(diffError, ' '));
|
2022-03-04 20:01:05 +01:00
|
|
|
if (log?.length)
|
2022-02-23 22:17:37 +01:00
|
|
|
output.push(callLogText(log));
|
2022-03-12 07:40:28 +01:00
|
|
|
else
|
|
|
|
|
output.push('');
|
2021-07-28 05:26:12 +02:00
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
if (expected !== undefined) {
|
|
|
|
|
writeFileSync(this.expectedPath, expected);
|
2022-03-31 23:11:34 +02:00
|
|
|
this.testInfo.attachments.push({ name: addSuffixToFilePath(this.snapshotName, '-expected'), contentType: this.mimeType, path: this.expectedPath });
|
2022-02-23 22:17:37 +01:00
|
|
|
output.push(`Expected: ${colors.yellow(this.expectedPath)}`);
|
|
|
|
|
}
|
2022-03-11 17:46:13 +01:00
|
|
|
if (previous !== undefined) {
|
|
|
|
|
writeFileSync(this.previousPath, previous);
|
2022-03-31 23:11:34 +02:00
|
|
|
this.testInfo.attachments.push({ name: addSuffixToFilePath(this.snapshotName, '-previous'), contentType: this.mimeType, path: this.previousPath });
|
2022-03-11 17:46:13 +01:00
|
|
|
output.push(`Previous: ${colors.yellow(this.previousPath)}`);
|
|
|
|
|
}
|
2022-02-23 22:17:37 +01:00
|
|
|
if (actual !== undefined) {
|
|
|
|
|
writeFileSync(this.actualPath, actual);
|
2022-03-31 23:11:34 +02:00
|
|
|
this.testInfo.attachments.push({ name: addSuffixToFilePath(this.snapshotName, '-actual'), contentType: this.mimeType, path: this.actualPath });
|
2022-02-23 22:17:37 +01:00
|
|
|
output.push(`Received: ${colors.yellow(this.actualPath)}`);
|
|
|
|
|
}
|
|
|
|
|
if (diff !== undefined) {
|
|
|
|
|
writeFileSync(this.diffPath, diff);
|
2022-03-31 23:11:34 +02:00
|
|
|
this.testInfo.attachments.push({ name: addSuffixToFilePath(this.snapshotName, '-diff'), contentType: this.mimeType, path: this.diffPath });
|
2022-02-23 22:17:37 +01:00
|
|
|
output.push(` Diff: ${colors.yellow(this.diffPath)}`);
|
|
|
|
|
}
|
2022-04-06 02:47:35 +02:00
|
|
|
return { pass: false, message: () => output.join('\n'), };
|
2022-02-23 22:17:37 +01:00
|
|
|
}
|
2022-02-18 20:21:58 +01:00
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
handleMatching() {
|
2022-04-06 02:47:35 +02:00
|
|
|
return { pass: true, message: () => '' };
|
2022-02-23 22:17:37 +01:00
|
|
|
}
|
2022-02-18 20:21:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function toMatchSnapshot(
|
2023-06-20 00:18:59 +02:00
|
|
|
this: ExpectMatcherContext,
|
2022-02-18 20:21:58 +01:00
|
|
|
received: Buffer | string,
|
2022-03-11 03:41:16 +01:00
|
|
|
nameOrOptions: NameOrSegments | { name?: NameOrSegments } & ImageComparatorOptions = {},
|
|
|
|
|
optOptions: ImageComparatorOptions = {}
|
2022-04-06 02:47:35 +02:00
|
|
|
): SyncExpectationResult {
|
2022-02-18 20:21:58 +01:00
|
|
|
const testInfo = currentTestInfo();
|
|
|
|
|
if (!testInfo)
|
|
|
|
|
throw new Error(`toMatchSnapshot() must be called during the test`);
|
2022-03-22 16:36:09 +01:00
|
|
|
if (received instanceof Promise)
|
|
|
|
|
throw new Error('An unresolved Promise was passed to toMatchSnapshot(), make sure to resolve it by adding await to it.');
|
2022-09-01 14:34:36 +02:00
|
|
|
|
2023-04-07 18:54:01 +02:00
|
|
|
if (testInfo._configInternal.ignoreSnapshots)
|
2022-09-01 14:34:36 +02:00
|
|
|
return { pass: !this.isNot, message: () => '' };
|
|
|
|
|
|
2022-03-05 02:30:43 +01:00
|
|
|
const helper = new SnapshotHelper(
|
2022-03-11 01:50:26 +01:00
|
|
|
testInfo, testInfo.snapshotPath.bind(testInfo), determineFileExtension(received),
|
2023-04-07 18:54:01 +02:00
|
|
|
testInfo._projectInternal.expect?.toMatchSnapshot || {},
|
2022-03-05 02:30:43 +01:00
|
|
|
nameOrOptions, optOptions);
|
2022-02-16 23:22:01 +01:00
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
if (this.isNot) {
|
|
|
|
|
if (!fs.existsSync(helper.snapshotPath))
|
|
|
|
|
return helper.handleMissingNegated();
|
2022-03-22 00:42:21 +01:00
|
|
|
const isDifferent = !!helper.comparator(received, fs.readFileSync(helper.snapshotPath), helper.comparatorOptions);
|
2022-02-23 22:17:37 +01:00
|
|
|
return isDifferent ? helper.handleDifferentNegated() : helper.handleMatchingNegated();
|
2022-02-18 20:21:58 +01:00
|
|
|
}
|
|
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
if (!fs.existsSync(helper.snapshotPath))
|
|
|
|
|
return helper.handleMissing(received);
|
2022-02-18 20:21:58 +01:00
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
const expected = fs.readFileSync(helper.snapshotPath);
|
2022-03-22 00:42:21 +01:00
|
|
|
const result = helper.comparator(received, expected, helper.comparatorOptions);
|
2022-02-23 22:17:37 +01:00
|
|
|
if (!result)
|
|
|
|
|
return helper.handleMatching();
|
2022-02-18 20:21:58 +01:00
|
|
|
|
2022-02-23 22:17:37 +01:00
|
|
|
if (helper.updateSnapshots === 'all') {
|
|
|
|
|
writeFileSync(helper.snapshotPath, received);
|
2022-02-18 20:21:58 +01:00
|
|
|
/* eslint-disable no-console */
|
2022-02-23 22:17:37 +01:00
|
|
|
console.log(helper.snapshotPath + ' does not match, writing actual.');
|
2022-04-06 02:47:35 +02:00
|
|
|
return { pass: true, message: () => helper.snapshotPath + ' running with --update-snapshots, writing actual.' };
|
2022-02-18 20:21:58 +01:00
|
|
|
}
|
|
|
|
|
|
2022-03-11 17:46:13 +01:00
|
|
|
return helper.handleDifferent(received, expected, undefined, result.diff, result.errorMessage, undefined);
|
2022-02-18 20:21:58 +01:00
|
|
|
}
|
|
|
|
|
|
2022-02-28 21:25:59 +01:00
|
|
|
type HaveScreenshotOptions = ImageComparatorOptions & Omit<PageScreenshotOptions, 'type' | 'quality' | 'path'>;
|
|
|
|
|
|
2023-04-21 05:34:07 +02:00
|
|
|
export function toHaveScreenshotStepTitle(
|
|
|
|
|
nameOrOptions: NameOrSegments | { name?: NameOrSegments } & HaveScreenshotOptions = {},
|
|
|
|
|
optOptions: HaveScreenshotOptions = {}
|
|
|
|
|
): string {
|
|
|
|
|
let name: NameOrSegments | undefined;
|
|
|
|
|
if (typeof nameOrOptions === 'object' && !Array.isArray(nameOrOptions))
|
|
|
|
|
name = nameOrOptions.name;
|
|
|
|
|
else
|
|
|
|
|
name = nameOrOptions;
|
|
|
|
|
return Array.isArray(name) ? name.join(path.sep) : name || '';
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-28 21:25:59 +01:00
|
|
|
export async function toHaveScreenshot(
|
2023-06-20 00:18:59 +02:00
|
|
|
this: ExpectMatcherContext,
|
2022-02-28 21:25:59 +01:00
|
|
|
pageOrLocator: Page | Locator,
|
|
|
|
|
nameOrOptions: NameOrSegments | { name?: NameOrSegments } & HaveScreenshotOptions = {},
|
|
|
|
|
optOptions: HaveScreenshotOptions = {}
|
|
|
|
|
): Promise<SyncExpectationResult> {
|
|
|
|
|
const testInfo = currentTestInfo();
|
|
|
|
|
if (!testInfo)
|
|
|
|
|
throw new Error(`toHaveScreenshot() must be called during the test`);
|
2022-09-01 14:34:36 +02:00
|
|
|
|
2023-04-07 18:54:01 +02:00
|
|
|
if (testInfo._configInternal.ignoreSnapshots)
|
2022-09-01 14:34:36 +02:00
|
|
|
return { pass: !this.isNot, message: () => '' };
|
|
|
|
|
|
2023-04-07 18:54:01 +02:00
|
|
|
const config = (testInfo._projectInternal.expect as any)?.toHaveScreenshot;
|
2022-11-10 00:29:07 +01:00
|
|
|
const snapshotPathResolver = testInfo.snapshotPath.bind(testInfo);
|
2022-03-05 02:30:43 +01:00
|
|
|
const helper = new SnapshotHelper(
|
2022-05-09 16:34:53 +02:00
|
|
|
testInfo, snapshotPathResolver, 'png',
|
2022-03-11 17:45:36 +01:00
|
|
|
{
|
2023-02-13 20:11:44 +01:00
|
|
|
_comparator: config?._comparator,
|
2022-03-11 17:45:36 +01:00
|
|
|
maxDiffPixels: config?.maxDiffPixels,
|
|
|
|
|
maxDiffPixelRatio: config?.maxDiffPixelRatio,
|
|
|
|
|
threshold: config?.threshold,
|
|
|
|
|
},
|
2022-03-05 02:30:43 +01:00
|
|
|
nameOrOptions, optOptions);
|
2022-03-12 07:40:28 +01:00
|
|
|
if (!helper.snapshotPath.toLowerCase().endsWith('.png'))
|
|
|
|
|
throw new Error(`Screenshot name "${path.basename(helper.snapshotPath)}" must have '.png' extension`);
|
|
|
|
|
expectTypes(pageOrLocator, ['Page', 'Locator'], 'toHaveScreenshot');
|
2022-09-14 00:49:04 +02:00
|
|
|
|
2022-02-28 21:25:59 +01:00
|
|
|
const [page, locator] = pageOrLocator.constructor.name === 'Page' ? [(pageOrLocator as PageEx), undefined] : [(pageOrLocator as Locator).page() as PageEx, pageOrLocator as LocatorEx];
|
|
|
|
|
const screenshotOptions = {
|
2022-03-11 17:45:36 +01:00
|
|
|
animations: config?.animations ?? 'disabled',
|
2022-04-01 21:28:40 +02:00
|
|
|
scale: config?.scale ?? 'css',
|
|
|
|
|
caret: config?.caret ?? 'hide',
|
2022-02-28 21:25:59 +01:00
|
|
|
...helper.allOptions,
|
|
|
|
|
mask: (helper.allOptions.mask || []) as LocatorEx[],
|
2023-06-07 02:15:55 +02:00
|
|
|
maskColor: helper.allOptions.maskColor,
|
2022-02-28 21:25:59 +01:00
|
|
|
name: undefined,
|
|
|
|
|
threshold: undefined,
|
2022-03-04 08:17:31 +01:00
|
|
|
maxDiffPixels: undefined,
|
|
|
|
|
maxDiffPixelRatio: undefined,
|
2022-02-28 21:25:59 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const hasSnapshot = fs.existsSync(helper.snapshotPath);
|
|
|
|
|
if (this.isNot) {
|
|
|
|
|
if (!hasSnapshot)
|
|
|
|
|
return helper.handleMissingNegated();
|
|
|
|
|
|
|
|
|
|
// Having `errorMessage` means we timed out while waiting
|
|
|
|
|
// for screenshots not to match, so screenshots
|
|
|
|
|
// are actually the same in the end.
|
2023-02-21 23:15:11 +01:00
|
|
|
const isDifferent = !(await page._expectScreenshot({
|
2022-02-28 21:25:59 +01:00
|
|
|
expected: await fs.promises.readFile(helper.snapshotPath),
|
|
|
|
|
isNot: true,
|
|
|
|
|
locator,
|
2023-02-13 20:11:44 +01:00
|
|
|
comparatorOptions: {
|
|
|
|
|
...helper.comparatorOptions,
|
|
|
|
|
comparator: helper.comparatorOptions._comparator,
|
|
|
|
|
},
|
2022-02-28 21:25:59 +01:00
|
|
|
screenshotOptions,
|
|
|
|
|
timeout: currentExpectTimeout(helper.allOptions),
|
|
|
|
|
})).errorMessage;
|
|
|
|
|
return isDifferent ? helper.handleDifferentNegated() : helper.handleMatchingNegated();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Fast path: there's no screenshot and we don't intend to update it.
|
|
|
|
|
if (helper.updateSnapshots === 'none' && !hasSnapshot)
|
2022-11-29 21:51:15 +01:00
|
|
|
return { pass: false, message: () => `A snapshot doesn't exist at ${helper.snapshotPath}.` };
|
2022-02-28 21:25:59 +01:00
|
|
|
|
2022-06-22 03:01:25 +02:00
|
|
|
if (!hasSnapshot) {
|
2022-02-28 21:25:59 +01:00
|
|
|
// Regenerate a new screenshot by waiting until two screenshots are the same.
|
|
|
|
|
const timeout = currentExpectTimeout(helper.allOptions);
|
2023-02-21 23:15:11 +01:00
|
|
|
const { actual, previous, diff, errorMessage, log } = await page._expectScreenshot({
|
2022-02-28 21:25:59 +01:00
|
|
|
expected: undefined,
|
|
|
|
|
isNot: false,
|
|
|
|
|
locator,
|
2023-02-13 20:11:44 +01:00
|
|
|
comparatorOptions: { ...helper.comparatorOptions, comparator: helper.comparatorOptions._comparator },
|
2022-02-28 21:25:59 +01:00
|
|
|
screenshotOptions,
|
|
|
|
|
timeout,
|
|
|
|
|
});
|
|
|
|
|
// We tried re-generating new snapshot but failed.
|
|
|
|
|
// This can be due to e.g. spinning animation, so we want to show it as a diff.
|
2022-04-19 16:43:18 +02:00
|
|
|
if (errorMessage)
|
|
|
|
|
return helper.handleDifferent(actual, undefined, previous, diff, undefined, log, errorMessage);
|
2022-02-28 21:25:59 +01:00
|
|
|
|
2022-06-22 03:01:25 +02:00
|
|
|
// We successfully generated new screenshot.
|
|
|
|
|
return helper.handleMissing(actual!);
|
2022-02-28 21:25:59 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// General case:
|
|
|
|
|
// - snapshot exists
|
|
|
|
|
// - regular matcher (i.e. not a `.not`)
|
2022-06-22 03:01:25 +02:00
|
|
|
// - perhaps an 'all' flag to update non-matching screenshots
|
2022-02-28 21:25:59 +01:00
|
|
|
const expected = await fs.promises.readFile(helper.snapshotPath);
|
2023-02-21 23:15:11 +01:00
|
|
|
const { actual, diff, errorMessage, log } = await page._expectScreenshot({
|
2022-02-28 21:25:59 +01:00
|
|
|
expected,
|
|
|
|
|
isNot: false,
|
|
|
|
|
locator,
|
2023-02-13 20:11:44 +01:00
|
|
|
comparatorOptions: { ...helper.comparatorOptions, comparator: helper.comparatorOptions._comparator },
|
2022-02-28 21:25:59 +01:00
|
|
|
screenshotOptions,
|
|
|
|
|
timeout: currentExpectTimeout(helper.allOptions),
|
|
|
|
|
});
|
|
|
|
|
|
2022-06-22 03:01:25 +02:00
|
|
|
if (!errorMessage)
|
|
|
|
|
return helper.handleMatching();
|
|
|
|
|
|
|
|
|
|
if (helper.updateSnapshots === 'all') {
|
|
|
|
|
writeFileSync(helper.snapshotPath, actual!);
|
|
|
|
|
writeFileSync(helper.actualPath, actual!);
|
|
|
|
|
/* eslint-disable no-console */
|
|
|
|
|
console.log(helper.snapshotPath + ' is re-generated, writing actual.');
|
|
|
|
|
return {
|
|
|
|
|
pass: true,
|
|
|
|
|
message: () => helper.snapshotPath + ' running with --update-snapshots, writing actual.'
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return helper.handleDifferent(actual, expected, undefined, diff, errorMessage, log);
|
2022-02-28 21:25:59 +01:00
|
|
|
}
|
|
|
|
|
|
2022-02-18 20:21:58 +01:00
|
|
|
function writeFileSync(aPath: string, content: Buffer | string) {
|
|
|
|
|
fs.mkdirSync(path.dirname(aPath), { recursive: true });
|
|
|
|
|
fs.writeFileSync(aPath, content);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function indent(lines: string, tab: string) {
|
|
|
|
|
return lines.replace(/^(?=.+$)/gm, tab);
|
|
|
|
|
}
|
2022-02-16 23:22:01 +01:00
|
|
|
|
|
|
|
|
function determineFileExtension(file: string | Buffer): string {
|
|
|
|
|
if (typeof file === 'string')
|
2022-02-18 20:21:58 +01:00
|
|
|
return 'txt';
|
2022-02-16 23:22:01 +01:00
|
|
|
if (compareMagicBytes(file, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
|
2022-02-18 20:21:58 +01:00
|
|
|
return 'png';
|
2022-02-16 23:22:01 +01:00
|
|
|
if (compareMagicBytes(file, [0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01]))
|
2022-02-18 20:21:58 +01:00
|
|
|
return 'jpg';
|
|
|
|
|
return 'dat';
|
2022-02-16 23:22:01 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function compareMagicBytes(file: Buffer, magicBytes: number[]): boolean {
|
|
|
|
|
return Buffer.compare(Buffer.from(magicBytes), file.slice(0, magicBytes.length)) === 0;
|
|
|
|
|
}
|