@ohos-ports/playwright 1.52.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +168 -0
  4. package/ThirdPartyNotices.txt +4011 -0
  5. package/cli.js +19 -0
  6. package/index.d.ts +17 -0
  7. package/index.js +17 -0
  8. package/index.mjs +18 -0
  9. package/jsx-runtime.js +42 -0
  10. package/jsx-runtime.mjs +21 -0
  11. package/lib/common/config.js +272 -0
  12. package/lib/common/configLoader.js +373 -0
  13. package/lib/common/esmLoaderHost.js +100 -0
  14. package/lib/common/expectBundle.js +49 -0
  15. package/lib/common/expectBundleImpl.js +389 -0
  16. package/lib/common/fixtures.js +302 -0
  17. package/lib/common/globals.js +58 -0
  18. package/lib/common/ipc.js +60 -0
  19. package/lib/common/poolBuilder.js +85 -0
  20. package/lib/common/process.js +109 -0
  21. package/lib/common/suiteUtils.js +149 -0
  22. package/lib/common/test.js +313 -0
  23. package/lib/common/testLoader.js +100 -0
  24. package/lib/common/testType.js +306 -0
  25. package/lib/errorContext.js +149 -0
  26. package/lib/fsWatcher.js +67 -0
  27. package/lib/index.js +692 -0
  28. package/lib/internalsForTest.js +42 -0
  29. package/lib/isomorphic/events.js +77 -0
  30. package/lib/isomorphic/folders.js +30 -0
  31. package/lib/isomorphic/stringInternPool.js +69 -0
  32. package/lib/isomorphic/teleReceiver.js +484 -0
  33. package/lib/isomorphic/teleSuiteUpdater.js +137 -0
  34. package/lib/isomorphic/testServerConnection.js +211 -0
  35. package/lib/isomorphic/testServerInterface.js +16 -0
  36. package/lib/isomorphic/testTree.js +307 -0
  37. package/lib/isomorphic/types.d.js +16 -0
  38. package/lib/isomorphic/util.js +28 -0
  39. package/lib/loader/loaderMain.js +59 -0
  40. package/lib/matchers/expect.js +322 -0
  41. package/lib/matchers/matcherHint.js +59 -0
  42. package/lib/matchers/matchers.js +362 -0
  43. package/lib/matchers/toBeTruthy.js +71 -0
  44. package/lib/matchers/toEqual.js +94 -0
  45. package/lib/matchers/toHaveURL.js +117 -0
  46. package/lib/matchers/toMatchAriaSnapshot.js +180 -0
  47. package/lib/matchers/toMatchSnapshot.js +365 -0
  48. package/lib/matchers/toMatchText.js +105 -0
  49. package/lib/plugins/gitCommitInfoPlugin.js +198 -0
  50. package/lib/plugins/index.js +28 -0
  51. package/lib/plugins/webServerPlugin.js +207 -0
  52. package/lib/program.js +407 -0
  53. package/lib/reporters/base.js +540 -0
  54. package/lib/reporters/blob.js +135 -0
  55. package/lib/reporters/dot.js +82 -0
  56. package/lib/reporters/empty.js +32 -0
  57. package/lib/reporters/github.js +127 -0
  58. package/lib/reporters/html.js +579 -0
  59. package/lib/reporters/internalReporter.js +129 -0
  60. package/lib/reporters/json.js +254 -0
  61. package/lib/reporters/junit.js +230 -0
  62. package/lib/reporters/line.js +113 -0
  63. package/lib/reporters/list.js +228 -0
  64. package/lib/reporters/merge.js +511 -0
  65. package/lib/reporters/multiplexer.js +104 -0
  66. package/lib/reporters/reporterV2.js +102 -0
  67. package/lib/reporters/teleEmitter.js +269 -0
  68. package/lib/reporters/versions/blobV1.js +16 -0
  69. package/lib/runner/dispatcher.js +484 -0
  70. package/lib/runner/failureTracker.js +62 -0
  71. package/lib/runner/lastRun.js +74 -0
  72. package/lib/runner/loadUtils.js +299 -0
  73. package/lib/runner/loaderHost.js +89 -0
  74. package/lib/runner/processHost.js +165 -0
  75. package/lib/runner/projectUtils.js +235 -0
  76. package/lib/runner/rebase.js +189 -0
  77. package/lib/runner/reporters.js +162 -0
  78. package/lib/runner/runner.js +110 -0
  79. package/lib/runner/sigIntWatcher.js +96 -0
  80. package/lib/runner/taskRunner.js +127 -0
  81. package/lib/runner/tasks.js +400 -0
  82. package/lib/runner/testGroups.js +117 -0
  83. package/lib/runner/testServer.js +477 -0
  84. package/lib/runner/uiModeReporter.js +30 -0
  85. package/lib/runner/vcs.js +72 -0
  86. package/lib/runner/watchMode.js +394 -0
  87. package/lib/runner/workerHost.js +93 -0
  88. package/lib/third_party/tsconfig-loader.js +103 -0
  89. package/lib/transform/babelBundle.js +43 -0
  90. package/lib/transform/babelBundleImpl.js +477 -0
  91. package/lib/transform/compilationCache.js +255 -0
  92. package/lib/transform/esmLoader.js +104 -0
  93. package/lib/transform/esmUtils.js +53 -0
  94. package/lib/transform/portTransport.js +66 -0
  95. package/lib/transform/transform.js +291 -0
  96. package/lib/util.js +407 -0
  97. package/lib/utilsBundle.js +46 -0
  98. package/lib/utilsBundleImpl.js +102 -0
  99. package/lib/worker/fixtureRunner.js +253 -0
  100. package/lib/worker/testInfo.js +422 -0
  101. package/lib/worker/testTracing.js +351 -0
  102. package/lib/worker/timeoutManager.js +174 -0
  103. package/lib/worker/util.js +31 -0
  104. package/lib/worker/workerMain.js +511 -0
  105. package/package.json +64 -0
  106. package/test.d.ts +18 -0
  107. package/test.js +24 -0
  108. package/test.mjs +33 -0
  109. package/types/test.d.ts +10061 -0
  110. package/types/testReporter.d.ts +799 -0
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var toMatchAriaSnapshot_exports = {};
30
+ __export(toMatchAriaSnapshot_exports, {
31
+ toMatchAriaSnapshot: () => toMatchAriaSnapshot
32
+ });
33
+ module.exports = __toCommonJS(toMatchAriaSnapshot_exports);
34
+ var import_fs = __toESM(require("fs"));
35
+ var import_path = __toESM(require("path"));
36
+ var import_utils = require("@ohos-ports/playwright-core/lib/utils");
37
+ var import_matcherHint = require("./matcherHint");
38
+ var import_expectBundle = require("../common/expectBundle");
39
+ var import_util = require("../util");
40
+ var import_expect = require("./expect");
41
+ var import_globals = require("../common/globals");
42
+ async function toMatchAriaSnapshot(receiver, expectedParam, options = {}) {
43
+ const matcherName = "toMatchAriaSnapshot";
44
+ const testInfo = (0, import_globals.currentTestInfo)();
45
+ if (!testInfo)
46
+ throw new Error(`toMatchAriaSnapshot() must be called during the test`);
47
+ if (testInfo._projectInternal.ignoreSnapshots)
48
+ return { pass: !this.isNot, message: () => "", name: "toMatchAriaSnapshot", expected: "" };
49
+ const updateSnapshots = testInfo.config.updateSnapshots;
50
+ const pathTemplate = testInfo._projectInternal.expect?.toMatchAriaSnapshot?.pathTemplate;
51
+ const defaultTemplate = "{snapshotDir}/{testFileDir}/{testFileName}-snapshots/{arg}{ext}";
52
+ const matcherOptions = {
53
+ isNot: this.isNot,
54
+ promise: this.promise
55
+ };
56
+ let expected;
57
+ let timeout;
58
+ let expectedPath;
59
+ if ((0, import_utils.isString)(expectedParam)) {
60
+ expected = expectedParam;
61
+ timeout = options.timeout ?? this.timeout;
62
+ } else {
63
+ if (expectedParam?.name) {
64
+ const ext = expectedParam.name.endsWith(".aria.yml") ? ".aria.yml" : void 0;
65
+ expectedPath = testInfo._resolveSnapshotPath(pathTemplate, defaultTemplate, [(0, import_util.sanitizeFilePathBeforeExtension)(expectedParam.name, ext)]);
66
+ } else {
67
+ let snapshotNames = testInfo[snapshotNamesSymbol];
68
+ if (!snapshotNames) {
69
+ snapshotNames = { anonymousSnapshotIndex: 0 };
70
+ testInfo[snapshotNamesSymbol] = snapshotNames;
71
+ }
72
+ const fullTitleWithoutSpec = [...testInfo.titlePath.slice(1), ++snapshotNames.anonymousSnapshotIndex].join(" ");
73
+ expectedPath = testInfo._resolveSnapshotPath(pathTemplate, defaultTemplate, [(0, import_utils.sanitizeForFilePath)((0, import_util.trimLongString)(fullTitleWithoutSpec))], ".aria.yml");
74
+ if (!await (0, import_util.fileExistsAsync)(expectedPath)) {
75
+ const legacyPath = testInfo._resolveSnapshotPath(pathTemplate, defaultTemplate, [(0, import_utils.sanitizeForFilePath)((0, import_util.trimLongString)(fullTitleWithoutSpec))], ".yml");
76
+ if (await (0, import_util.fileExistsAsync)(legacyPath))
77
+ expectedPath = legacyPath;
78
+ }
79
+ }
80
+ expected = await import_fs.default.promises.readFile(expectedPath, "utf8").catch(() => "");
81
+ timeout = expectedParam?.timeout ?? this.timeout;
82
+ }
83
+ const generateMissingBaseline = updateSnapshots === "missing" && !expected;
84
+ if (generateMissingBaseline) {
85
+ if (this.isNot) {
86
+ const message2 = `Matchers using ".not" can't generate new baselines`;
87
+ return { pass: this.isNot, message: () => message2, name: "toMatchAriaSnapshot" };
88
+ } else {
89
+ expected = `- none "Generating new baseline"`;
90
+ }
91
+ }
92
+ expected = unshift(expected);
93
+ const { matches: pass, received, log, timedOut } = await receiver._expect("to.match.aria", { expectedValue: expected, isNot: this.isNot, timeout });
94
+ const typedReceived = received;
95
+ const messagePrefix = (0, import_matcherHint.matcherHint)(this, receiver, matcherName, "locator", void 0, matcherOptions, timedOut ? timeout : void 0);
96
+ const notFound = typedReceived === import_matcherHint.kNoElementsFoundError;
97
+ if (notFound) {
98
+ return {
99
+ pass: this.isNot,
100
+ message: () => messagePrefix + `Expected: ${this.utils.printExpected(expected)}
101
+ Received: ${(0, import_expectBundle.EXPECTED_COLOR)("<element not found>")}` + (0, import_util.callLogText)(log),
102
+ name: "toMatchAriaSnapshot",
103
+ expected
104
+ };
105
+ }
106
+ const receivedText = typedReceived.raw;
107
+ const message = () => {
108
+ if (pass) {
109
+ if (notFound)
110
+ return messagePrefix + `Expected: not ${this.utils.printExpected(expected)}
111
+ Received: ${receivedText}` + (0, import_util.callLogText)(log);
112
+ const printedReceived = (0, import_expect.printReceivedStringContainExpectedSubstring)(receivedText, receivedText.indexOf(expected), expected.length);
113
+ return messagePrefix + `Expected: not ${this.utils.printExpected(expected)}
114
+ Received: ${printedReceived}` + (0, import_util.callLogText)(log);
115
+ } else {
116
+ const labelExpected = `Expected`;
117
+ if (notFound)
118
+ return messagePrefix + `${labelExpected}: ${this.utils.printExpected(expected)}
119
+ Received: ${receivedText}` + (0, import_util.callLogText)(log);
120
+ return messagePrefix + this.utils.printDiffOrStringify(expected, receivedText, labelExpected, "Received", false) + (0, import_util.callLogText)(log);
121
+ }
122
+ };
123
+ if (!this.isNot) {
124
+ if (updateSnapshots === "all" || updateSnapshots === "changed" && pass === this.isNot || generateMissingBaseline) {
125
+ if (expectedPath) {
126
+ await import_fs.default.promises.mkdir(import_path.default.dirname(expectedPath), { recursive: true });
127
+ await import_fs.default.promises.writeFile(expectedPath, typedReceived.regex, "utf8");
128
+ const relativePath = import_path.default.relative(process.cwd(), expectedPath);
129
+ if (updateSnapshots === "missing") {
130
+ const message2 = `A snapshot doesn't exist at ${relativePath}, writing actual.`;
131
+ testInfo._hasNonRetriableError = true;
132
+ testInfo._failWithError(new Error(message2));
133
+ } else {
134
+ const message2 = `A snapshot is generated at ${relativePath}.`;
135
+ console.log(message2);
136
+ }
137
+ return { pass: true, message: () => "", name: "toMatchAriaSnapshot" };
138
+ } else {
139
+ const suggestedRebaseline = `\`
140
+ ${(0, import_utils.escapeTemplateString)(indent(typedReceived.regex, "{indent} "))}
141
+ {indent}\``;
142
+ if (updateSnapshots === "missing") {
143
+ const message2 = "A snapshot is not provided, generating new baseline.";
144
+ testInfo._hasNonRetriableError = true;
145
+ testInfo._failWithError(new Error(message2));
146
+ }
147
+ return { pass: false, message: () => "", name: "toMatchAriaSnapshot", suggestedRebaseline };
148
+ }
149
+ }
150
+ }
151
+ return {
152
+ name: matcherName,
153
+ expected,
154
+ message,
155
+ pass,
156
+ actual: received,
157
+ log,
158
+ timeout: timedOut ? timeout : void 0
159
+ };
160
+ }
161
+ function unshift(snapshot) {
162
+ const lines = snapshot.split("\n");
163
+ let whitespacePrefixLength = 100;
164
+ for (const line of lines) {
165
+ if (!line.trim())
166
+ continue;
167
+ const match = line.match(/^(\s*)/);
168
+ if (match && match[1].length < whitespacePrefixLength)
169
+ whitespacePrefixLength = match[1].length;
170
+ }
171
+ return lines.filter((t) => t.trim()).map((line) => line.substring(whitespacePrefixLength)).join("\n");
172
+ }
173
+ function indent(snapshot, indent2) {
174
+ return snapshot.split("\n").map((line) => indent2 + line).join("\n");
175
+ }
176
+ const snapshotNamesSymbol = Symbol("snapshotNames");
177
+ // Annotate the CommonJS export names for ESM import in node:
178
+ 0 && (module.exports = {
179
+ toMatchAriaSnapshot
180
+ });
@@ -0,0 +1,365 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var toMatchSnapshot_exports = {};
30
+ __export(toMatchSnapshot_exports, {
31
+ toHaveScreenshot: () => toHaveScreenshot,
32
+ toHaveScreenshotStepTitle: () => toHaveScreenshotStepTitle,
33
+ toMatchSnapshot: () => toMatchSnapshot
34
+ });
35
+ module.exports = __toCommonJS(toMatchSnapshot_exports);
36
+ var import_fs = __toESM(require("fs"));
37
+ var import_path = __toESM(require("path"));
38
+ var import_utils = require("@ohos-ports/playwright-core/lib/utils");
39
+ var import_utils2 = require("@ohos-ports/playwright-core/lib/utils");
40
+ var import_utilsBundle = require("@ohos-ports/playwright-core/lib/utilsBundle");
41
+ var import_util = require("../util");
42
+ var import_matcherHint = require("./matcherHint");
43
+ var import_globals = require("../common/globals");
44
+ const snapshotNamesSymbol = Symbol("snapshotNames");
45
+ const NonConfigProperties = [
46
+ "clip",
47
+ "fullPage",
48
+ "mask",
49
+ "maskColor",
50
+ "omitBackground",
51
+ "timeout"
52
+ ];
53
+ class SnapshotHelper {
54
+ constructor(testInfo, matcherName, locator, anonymousSnapshotExtension, configOptions, nameOrOptions, optOptions) {
55
+ let name;
56
+ if (Array.isArray(nameOrOptions) || typeof nameOrOptions === "string") {
57
+ name = nameOrOptions;
58
+ this.options = { ...optOptions };
59
+ } else {
60
+ const { name: nameFromOptions, ...options } = nameOrOptions;
61
+ this.options = options;
62
+ name = nameFromOptions;
63
+ }
64
+ let snapshotNames = testInfo[snapshotNamesSymbol];
65
+ if (!testInfo[snapshotNamesSymbol]) {
66
+ snapshotNames = {
67
+ anonymousSnapshotIndex: 0,
68
+ namedSnapshotIndex: {}
69
+ };
70
+ testInfo[snapshotNamesSymbol] = snapshotNames;
71
+ }
72
+ let expectedPathSegments;
73
+ let outputBasePath;
74
+ if (!name) {
75
+ const fullTitleWithoutSpec = [
76
+ ...testInfo.titlePath.slice(1),
77
+ ++snapshotNames.anonymousSnapshotIndex
78
+ ].join(" ");
79
+ expectedPathSegments = [(0, import_utils.sanitizeForFilePath)((0, import_util.trimLongString)(fullTitleWithoutSpec)) + "." + anonymousSnapshotExtension];
80
+ const sanitizedName = (0, import_utils.sanitizeForFilePath)((0, import_util.trimLongString)(fullTitleWithoutSpec, import_util.windowsFilesystemFriendlyLength)) + "." + anonymousSnapshotExtension;
81
+ outputBasePath = testInfo._getOutputPath(sanitizedName);
82
+ this.attachmentBaseName = sanitizedName;
83
+ } else {
84
+ expectedPathSegments = Array.isArray(name) ? name : [(0, import_util.sanitizeFilePathBeforeExtension)(name)];
85
+ const joinedName = Array.isArray(name) ? name.join(import_path.default.sep) : (0, import_util.sanitizeFilePathBeforeExtension)((0, import_util.trimLongString)(name, import_util.windowsFilesystemFriendlyLength));
86
+ snapshotNames.namedSnapshotIndex[joinedName] = (snapshotNames.namedSnapshotIndex[joinedName] || 0) + 1;
87
+ const index = snapshotNames.namedSnapshotIndex[joinedName];
88
+ const sanitizedName = index > 1 ? (0, import_util.addSuffixToFilePath)(joinedName, `-${index - 1}`) : joinedName;
89
+ outputBasePath = testInfo._getOutputPath(sanitizedName);
90
+ this.attachmentBaseName = sanitizedName;
91
+ }
92
+ const defaultTemplate = "{snapshotDir}/{testFileDir}/{testFileName}-snapshots/{arg}{-projectName}{-snapshotSuffix}{ext}";
93
+ this.expectedPath = testInfo._resolveSnapshotPath(configOptions.pathTemplate, defaultTemplate, expectedPathSegments);
94
+ this.legacyExpectedPath = (0, import_util.addSuffixToFilePath)(outputBasePath, "-expected");
95
+ this.previousPath = (0, import_util.addSuffixToFilePath)(outputBasePath, "-previous");
96
+ this.actualPath = (0, import_util.addSuffixToFilePath)(outputBasePath, "-actual");
97
+ this.diffPath = (0, import_util.addSuffixToFilePath)(outputBasePath, "-diff");
98
+ const filteredConfigOptions = { ...configOptions };
99
+ for (const prop of NonConfigProperties)
100
+ delete filteredConfigOptions[prop];
101
+ this.options = {
102
+ ...filteredConfigOptions,
103
+ ...this.options
104
+ };
105
+ if (this.options._comparator) {
106
+ this.options.comparator = this.options._comparator;
107
+ delete this.options._comparator;
108
+ }
109
+ if (this.options.maxDiffPixels !== void 0 && this.options.maxDiffPixels < 0)
110
+ throw new Error("`maxDiffPixels` option value must be non-negative integer");
111
+ if (this.options.maxDiffPixelRatio !== void 0 && (this.options.maxDiffPixelRatio < 0 || this.options.maxDiffPixelRatio > 1))
112
+ throw new Error("`maxDiffPixelRatio` option value must be between 0 and 1");
113
+ this.matcherName = matcherName;
114
+ this.locator = locator;
115
+ this.updateSnapshots = testInfo.config.updateSnapshots;
116
+ this.mimeType = import_utilsBundle.mime.getType(import_path.default.basename(this.expectedPath)) ?? "application/octet-string";
117
+ this.comparator = (0, import_utils.getComparator)(this.mimeType);
118
+ this.testInfo = testInfo;
119
+ this.kind = this.mimeType.startsWith("image/") ? "Screenshot" : "Snapshot";
120
+ }
121
+ createMatcherResult(message, pass, log) {
122
+ const unfiltered = {
123
+ name: this.matcherName,
124
+ expected: this.expectedPath,
125
+ actual: this.actualPath,
126
+ diff: this.diffPath,
127
+ pass,
128
+ message: () => message,
129
+ log
130
+ };
131
+ return Object.fromEntries(Object.entries(unfiltered).filter(([_, v]) => v !== void 0));
132
+ }
133
+ handleMissingNegated() {
134
+ const isWriteMissingMode = this.updateSnapshots !== "none";
135
+ const message = `A snapshot doesn't exist at ${this.expectedPath}${isWriteMissingMode ? `, matchers using ".not" won't write them automatically.` : "."}`;
136
+ return this.createMatcherResult(message, true);
137
+ }
138
+ handleDifferentNegated() {
139
+ return this.createMatcherResult("", false);
140
+ }
141
+ handleMatchingNegated() {
142
+ const message = [
143
+ import_utils2.colors.red(`${this.kind} comparison failed:`),
144
+ "",
145
+ indent("Expected result should be different from the actual one.", " ")
146
+ ].join("\n");
147
+ return this.createMatcherResult(message, true);
148
+ }
149
+ handleMissing(actual, step) {
150
+ const isWriteMissingMode = this.updateSnapshots !== "none";
151
+ if (isWriteMissingMode)
152
+ writeFileSync(this.expectedPath, actual);
153
+ step?._attachToStep({ name: (0, import_util.addSuffixToFilePath)(this.attachmentBaseName, "-expected"), contentType: this.mimeType, path: this.expectedPath });
154
+ writeFileSync(this.actualPath, actual);
155
+ step?._attachToStep({ name: (0, import_util.addSuffixToFilePath)(this.attachmentBaseName, "-actual"), contentType: this.mimeType, path: this.actualPath });
156
+ const message = `A snapshot doesn't exist at ${this.expectedPath}${isWriteMissingMode ? ", writing actual." : "."}`;
157
+ if (this.updateSnapshots === "all" || this.updateSnapshots === "changed") {
158
+ console.log(message);
159
+ return this.createMatcherResult(message, true);
160
+ }
161
+ if (this.updateSnapshots === "missing") {
162
+ this.testInfo._hasNonRetriableError = true;
163
+ this.testInfo._failWithError(new Error(message));
164
+ return this.createMatcherResult("", true);
165
+ }
166
+ return this.createMatcherResult(message, false);
167
+ }
168
+ handleDifferent(actual, expected, previous, diff, header, diffError, log, step) {
169
+ const output = [`${header}${indent(diffError, " ")}`];
170
+ if (expected !== void 0) {
171
+ writeFileSync(this.legacyExpectedPath, expected);
172
+ step?._attachToStep({ name: (0, import_util.addSuffixToFilePath)(this.attachmentBaseName, "-expected"), contentType: this.mimeType, path: this.expectedPath });
173
+ output.push(`
174
+ Expected: ${import_utils2.colors.yellow(this.expectedPath)}`);
175
+ }
176
+ if (previous !== void 0) {
177
+ writeFileSync(this.previousPath, previous);
178
+ step?._attachToStep({ name: (0, import_util.addSuffixToFilePath)(this.attachmentBaseName, "-previous"), contentType: this.mimeType, path: this.previousPath });
179
+ output.push(`Previous: ${import_utils2.colors.yellow(this.previousPath)}`);
180
+ }
181
+ if (actual !== void 0) {
182
+ writeFileSync(this.actualPath, actual);
183
+ step?._attachToStep({ name: (0, import_util.addSuffixToFilePath)(this.attachmentBaseName, "-actual"), contentType: this.mimeType, path: this.actualPath });
184
+ output.push(`Received: ${import_utils2.colors.yellow(this.actualPath)}`);
185
+ }
186
+ if (diff !== void 0) {
187
+ writeFileSync(this.diffPath, diff);
188
+ step?._attachToStep({ name: (0, import_util.addSuffixToFilePath)(this.attachmentBaseName, "-diff"), contentType: this.mimeType, path: this.diffPath });
189
+ output.push(` Diff: ${import_utils2.colors.yellow(this.diffPath)}`);
190
+ }
191
+ if (log?.length)
192
+ output.push((0, import_util.callLogText)(log));
193
+ else
194
+ output.push("");
195
+ return this.createMatcherResult(output.join("\n"), false, log);
196
+ }
197
+ handleMatching() {
198
+ return this.createMatcherResult("", true);
199
+ }
200
+ }
201
+ function toMatchSnapshot(received, nameOrOptions = {}, optOptions = {}) {
202
+ const testInfo = (0, import_globals.currentTestInfo)();
203
+ if (!testInfo)
204
+ throw new Error(`toMatchSnapshot() must be called during the test`);
205
+ if (received instanceof Promise)
206
+ throw new Error("An unresolved Promise was passed to toMatchSnapshot(), make sure to resolve it by adding await to it.");
207
+ if (testInfo._projectInternal.ignoreSnapshots)
208
+ return { pass: !this.isNot, message: () => "", name: "toMatchSnapshot", expected: nameOrOptions };
209
+ const configOptions = testInfo._projectInternal.expect?.toMatchSnapshot || {};
210
+ const helper = new SnapshotHelper(
211
+ testInfo,
212
+ "toMatchSnapshot",
213
+ void 0,
214
+ determineFileExtension(received),
215
+ configOptions,
216
+ nameOrOptions,
217
+ optOptions
218
+ );
219
+ if (this.isNot) {
220
+ if (!import_fs.default.existsSync(helper.expectedPath))
221
+ return helper.handleMissingNegated();
222
+ const isDifferent = !!helper.comparator(received, import_fs.default.readFileSync(helper.expectedPath), helper.options);
223
+ return isDifferent ? helper.handleDifferentNegated() : helper.handleMatchingNegated();
224
+ }
225
+ if (!import_fs.default.existsSync(helper.expectedPath))
226
+ return helper.handleMissing(received, this._stepInfo);
227
+ const expected = import_fs.default.readFileSync(helper.expectedPath);
228
+ if (helper.updateSnapshots === "all") {
229
+ if (!(0, import_utils.compareBuffersOrStrings)(received, expected))
230
+ return helper.handleMatching();
231
+ writeFileSync(helper.expectedPath, received);
232
+ console.log(helper.expectedPath + " is not the same, writing actual.");
233
+ return helper.createMatcherResult(helper.expectedPath + " running with --update-snapshots, writing actual.", true);
234
+ }
235
+ if (helper.updateSnapshots === "changed") {
236
+ const result2 = helper.comparator(received, expected, helper.options);
237
+ if (!result2)
238
+ return helper.handleMatching();
239
+ writeFileSync(helper.expectedPath, received);
240
+ console.log(helper.expectedPath + " does not match, writing actual.");
241
+ return helper.createMatcherResult(helper.expectedPath + " running with --update-snapshots, writing actual.", true);
242
+ }
243
+ const result = helper.comparator(received, expected, helper.options);
244
+ if (!result)
245
+ return helper.handleMatching();
246
+ const receiver = (0, import_utils.isString)(received) ? "string" : "Buffer";
247
+ const header = (0, import_matcherHint.matcherHint)(this, void 0, "toMatchSnapshot", receiver, void 0, void 0);
248
+ return helper.handleDifferent(received, expected, void 0, result.diff, header, result.errorMessage, void 0, this._stepInfo);
249
+ }
250
+ function toHaveScreenshotStepTitle(nameOrOptions = {}, optOptions = {}) {
251
+ let name;
252
+ if (typeof nameOrOptions === "object" && !Array.isArray(nameOrOptions))
253
+ name = nameOrOptions.name;
254
+ else
255
+ name = nameOrOptions;
256
+ return Array.isArray(name) ? name.join(import_path.default.sep) : name || "";
257
+ }
258
+ async function toHaveScreenshot(pageOrLocator, nameOrOptions = {}, optOptions = {}) {
259
+ const testInfo = (0, import_globals.currentTestInfo)();
260
+ if (!testInfo)
261
+ throw new Error(`toHaveScreenshot() must be called during the test`);
262
+ if (testInfo._projectInternal.ignoreSnapshots)
263
+ return { pass: !this.isNot, message: () => "", name: "toHaveScreenshot", expected: nameOrOptions };
264
+ (0, import_util.expectTypes)(pageOrLocator, ["Page", "Locator"], "toHaveScreenshot");
265
+ const [page, locator] = pageOrLocator.constructor.name === "Page" ? [pageOrLocator, void 0] : [pageOrLocator.page(), pageOrLocator];
266
+ const configOptions = testInfo._projectInternal.expect?.toHaveScreenshot || {};
267
+ const helper = new SnapshotHelper(testInfo, "toHaveScreenshot", locator, "png", configOptions, nameOrOptions, optOptions);
268
+ if (!helper.expectedPath.toLowerCase().endsWith(".png"))
269
+ throw new Error(`Screenshot name "${import_path.default.basename(helper.expectedPath)}" must have '.png' extension`);
270
+ (0, import_util.expectTypes)(pageOrLocator, ["Page", "Locator"], "toHaveScreenshot");
271
+ const style = await loadScreenshotStyles(helper.options.stylePath);
272
+ const timeout = helper.options.timeout ?? this.timeout;
273
+ const expectScreenshotOptions = {
274
+ locator,
275
+ animations: helper.options.animations ?? "disabled",
276
+ caret: helper.options.caret ?? "hide",
277
+ clip: helper.options.clip,
278
+ fullPage: helper.options.fullPage,
279
+ mask: helper.options.mask,
280
+ maskColor: helper.options.maskColor,
281
+ omitBackground: helper.options.omitBackground,
282
+ scale: helper.options.scale ?? "css",
283
+ style,
284
+ isNot: !!this.isNot,
285
+ timeout,
286
+ comparator: helper.options.comparator,
287
+ maxDiffPixels: helper.options.maxDiffPixels,
288
+ maxDiffPixelRatio: helper.options.maxDiffPixelRatio,
289
+ threshold: helper.options.threshold
290
+ };
291
+ const hasSnapshot = import_fs.default.existsSync(helper.expectedPath);
292
+ if (this.isNot) {
293
+ if (!hasSnapshot)
294
+ return helper.handleMissingNegated();
295
+ expectScreenshotOptions.expected = await import_fs.default.promises.readFile(helper.expectedPath);
296
+ const isDifferent = !(await page._expectScreenshot(expectScreenshotOptions)).errorMessage;
297
+ return isDifferent ? helper.handleDifferentNegated() : helper.handleMatchingNegated();
298
+ }
299
+ if (helper.updateSnapshots === "none" && !hasSnapshot)
300
+ return helper.createMatcherResult(`A snapshot doesn't exist at ${helper.expectedPath}.`, false);
301
+ const receiver = locator ? "locator" : "page";
302
+ if (!hasSnapshot) {
303
+ const { actual: actual2, previous: previous2, diff: diff2, errorMessage: errorMessage2, log: log2, timedOut: timedOut2 } = await page._expectScreenshot(expectScreenshotOptions);
304
+ if (errorMessage2) {
305
+ const header2 = (0, import_matcherHint.matcherHint)(this, locator, "toHaveScreenshot", receiver, void 0, void 0, timedOut2 ? timeout : void 0);
306
+ return helper.handleDifferent(actual2, void 0, previous2, diff2, header2, errorMessage2, log2, this._stepInfo);
307
+ }
308
+ return helper.handleMissing(actual2, this._stepInfo);
309
+ }
310
+ const expected = await import_fs.default.promises.readFile(helper.expectedPath);
311
+ expectScreenshotOptions.expected = helper.updateSnapshots === "all" ? void 0 : expected;
312
+ const { actual, previous, diff, errorMessage, log, timedOut } = await page._expectScreenshot(expectScreenshotOptions);
313
+ const writeFiles = () => {
314
+ writeFileSync(helper.expectedPath, actual);
315
+ writeFileSync(helper.actualPath, actual);
316
+ console.log(helper.expectedPath + " is re-generated, writing actual.");
317
+ return helper.createMatcherResult(helper.expectedPath + " running with --update-snapshots, writing actual.", true);
318
+ };
319
+ if (!errorMessage) {
320
+ if (helper.updateSnapshots === "all" && actual && (0, import_utils.compareBuffersOrStrings)(actual, expected)) {
321
+ console.log(helper.expectedPath + " is re-generated, writing actual.");
322
+ return writeFiles();
323
+ }
324
+ return helper.handleMatching();
325
+ }
326
+ if (helper.updateSnapshots === "changed" || helper.updateSnapshots === "all")
327
+ return writeFiles();
328
+ const header = (0, import_matcherHint.matcherHint)(this, void 0, "toHaveScreenshot", receiver, void 0, void 0, timedOut ? timeout : void 0);
329
+ return helper.handleDifferent(actual, expectScreenshotOptions.expected, previous, diff, header, errorMessage, log, this._stepInfo);
330
+ }
331
+ function writeFileSync(aPath, content) {
332
+ import_fs.default.mkdirSync(import_path.default.dirname(aPath), { recursive: true });
333
+ import_fs.default.writeFileSync(aPath, content);
334
+ }
335
+ function indent(lines, tab) {
336
+ return lines.replace(/^(?=.+$)/gm, tab);
337
+ }
338
+ function determineFileExtension(file) {
339
+ if (typeof file === "string")
340
+ return "txt";
341
+ if (compareMagicBytes(file, [137, 80, 78, 71, 13, 10, 26, 10]))
342
+ return "png";
343
+ if (compareMagicBytes(file, [255, 216, 255]))
344
+ return "jpg";
345
+ return "dat";
346
+ }
347
+ function compareMagicBytes(file, magicBytes) {
348
+ return Buffer.compare(Buffer.from(magicBytes), file.slice(0, magicBytes.length)) === 0;
349
+ }
350
+ async function loadScreenshotStyles(stylePath) {
351
+ if (!stylePath)
352
+ return;
353
+ const stylePaths = Array.isArray(stylePath) ? stylePath : [stylePath];
354
+ const styles = await Promise.all(stylePaths.map(async (stylePath2) => {
355
+ const text = await import_fs.default.promises.readFile(stylePath2, "utf8");
356
+ return text.trim();
357
+ }));
358
+ return styles.join("\n").trim() || void 0;
359
+ }
360
+ // Annotate the CommonJS export names for ESM import in node:
361
+ 0 && (module.exports = {
362
+ toHaveScreenshot,
363
+ toHaveScreenshotStepTitle,
364
+ toMatchSnapshot
365
+ });
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var toMatchText_exports = {};
20
+ __export(toMatchText_exports, {
21
+ toMatchText: () => toMatchText
22
+ });
23
+ module.exports = __toCommonJS(toMatchText_exports);
24
+ var import_utils = require("@ohos-ports/playwright-core/lib/utils");
25
+ var import_util = require("../util");
26
+ var import_expect = require("./expect");
27
+ var import_matcherHint = require("./matcherHint");
28
+ var import_expectBundle = require("../common/expectBundle");
29
+ async function toMatchText(matcherName, receiver, receiverType, query, expected, options = {}) {
30
+ (0, import_util.expectTypes)(receiver, [receiverType], matcherName);
31
+ const matcherOptions = {
32
+ isNot: this.isNot,
33
+ promise: this.promise
34
+ };
35
+ if (!(typeof expected === "string") && !(expected && typeof expected.test === "function")) {
36
+ throw new Error([
37
+ (0, import_matcherHint.matcherHint)(this, receiver, matcherName, receiver, expected, matcherOptions),
38
+ `${import_utils.colors.bold("Matcher error")}: ${(0, import_expectBundle.EXPECTED_COLOR)("expected")} value must be a string or regular expression`,
39
+ this.utils.printWithType("Expected", expected, this.utils.printExpected)
40
+ ].join("\n\n"));
41
+ }
42
+ const timeout = options.timeout ?? this.timeout;
43
+ const { matches: pass, received, log, timedOut } = await query(!!this.isNot, timeout);
44
+ if (pass === !this.isNot) {
45
+ return {
46
+ name: matcherName,
47
+ message: () => "",
48
+ pass,
49
+ expected
50
+ };
51
+ }
52
+ const stringSubstring = options.matchSubstring ? "substring" : "string";
53
+ const receivedString = received || "";
54
+ const messagePrefix = (0, import_matcherHint.matcherHint)(this, receiver, matcherName, "locator", void 0, matcherOptions, timedOut ? timeout : void 0);
55
+ const notFound = received === import_matcherHint.kNoElementsFoundError;
56
+ let printedReceived;
57
+ let printedExpected;
58
+ let printedDiff;
59
+ if (pass) {
60
+ if (typeof expected === "string") {
61
+ if (notFound) {
62
+ printedExpected = `Expected ${stringSubstring}: not ${this.utils.printExpected(expected)}`;
63
+ printedReceived = `Received: ${received}`;
64
+ } else {
65
+ printedExpected = `Expected ${stringSubstring}: not ${this.utils.printExpected(expected)}`;
66
+ const formattedReceived = (0, import_expect.printReceivedStringContainExpectedSubstring)(receivedString, receivedString.indexOf(expected), expected.length);
67
+ printedReceived = `Received string: ${formattedReceived}`;
68
+ }
69
+ } else {
70
+ if (notFound) {
71
+ printedExpected = `Expected pattern: not ${this.utils.printExpected(expected)}`;
72
+ printedReceived = `Received: ${received}`;
73
+ } else {
74
+ printedExpected = `Expected pattern: not ${this.utils.printExpected(expected)}`;
75
+ const formattedReceived = (0, import_expect.printReceivedStringContainExpectedResult)(receivedString, typeof expected.exec === "function" ? expected.exec(receivedString) : null);
76
+ printedReceived = `Received string: ${formattedReceived}`;
77
+ }
78
+ }
79
+ } else {
80
+ const labelExpected = `Expected ${typeof expected === "string" ? stringSubstring : "pattern"}`;
81
+ if (notFound) {
82
+ printedExpected = `${labelExpected}: ${this.utils.printExpected(expected)}`;
83
+ printedReceived = `Received: ${received}`;
84
+ } else {
85
+ printedDiff = this.utils.printDiffOrStringify(expected, receivedString, labelExpected, "Received string", false);
86
+ }
87
+ }
88
+ const message = () => {
89
+ const resultDetails = printedDiff ? printedDiff : printedExpected + "\n" + printedReceived;
90
+ return messagePrefix + resultDetails + (0, import_util.callLogText)(log);
91
+ };
92
+ return {
93
+ name: matcherName,
94
+ expected,
95
+ message,
96
+ pass,
97
+ actual: received,
98
+ log,
99
+ timeout: timedOut ? timeout : void 0
100
+ };
101
+ }
102
+ // Annotate the CommonJS export names for ESM import in node:
103
+ 0 && (module.exports = {
104
+ toMatchText
105
+ });