@argos-ci/playwright 0.0.7 → 0.0.8-alpha.187

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.
package/LICENSE CHANGED
@@ -1,7 +1,7 @@
1
- Copyright 2023 Smooth Code
1
+ Copyright 2022 Smooth Code
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
4
 
5
5
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
6
 
7
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/dist/index.cjs CHANGED
@@ -1,6 +1,8 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */ const argosScreenshot = async (...args)=>{
1
+ // @ts-ignore
2
+ const argosScreenshot = async (...args)=>{
2
3
  // @ts-ignore
3
- const { argosScreenshot } = await import('./index.mjs');
4
+ const { argosScreenshot } = await import('./index.mjs');
4
5
  return argosScreenshot(...args);
5
6
  };
7
+ // @ts-ignore
6
8
  exports.argosScreenshot = argosScreenshot;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { ElementHandle, LocatorScreenshotOptions, PageScreenshotOptions, Page } from '@playwright/test';
2
-
1
+ import { Page, PageScreenshotOptions, LocatorScreenshotOptions, ElementHandle } from "@playwright/test";
2
+ import { ViewportOption } from "@argos-ci/browser";
3
3
  type LocatorOptions = Parameters<Page["locator"]>[1];
4
4
  type ScreenshotOptions<TBase extends PageScreenshotOptions | LocatorScreenshotOptions> = Omit<TBase, "encoding" | "type" | "omitBackground" | "path">;
5
5
  type ArgosScreenshotOptions = {
@@ -7,7 +7,10 @@ type ArgosScreenshotOptions = {
7
7
  * ElementHandle or string selector of the element to take a screenshot of.
8
8
  */
9
9
  element?: string | ElementHandle;
10
+ /**
11
+ * Viewports to take screenshots of.
12
+ */
13
+ viewports?: ViewportOption[];
10
14
  } & LocatorOptions & ScreenshotOptions<LocatorScreenshotOptions> & ScreenshotOptions<PageScreenshotOptions>;
11
- declare function argosScreenshot(page: Page, name: string, { element, has, hasText, ...options }?: ArgosScreenshotOptions): Promise<void>;
12
-
15
+ declare function argosScreenshot(page: Page, name: string, { element, has, hasText, viewports, ...options }?: ArgosScreenshotOptions): Promise<void>;
13
16
  export { ArgosScreenshotOptions, argosScreenshot };
package/dist/index.mjs CHANGED
@@ -1,78 +1,182 @@
1
- import { mkdir } from 'node:fs/promises';
2
- import { resolve } from 'node:path';
1
+ import { mkdir, readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { resolveViewport } from '@argos-ci/browser';
5
+ import { getGitRepositoryPath, readVersionFromPackage, getScreenshotName, writeMetadata } from '@argos-ci/util';
3
6
 
4
- const screenshotFolder = "./screenshots";
5
- const GLOBAL_STYLES = `
6
- /* Hide carets */
7
- * { caret-color: transparent !important; }
7
+ function getAttachmentName(name, type) {
8
+ return `argos/${type}___${name}`;
9
+ }
8
10
 
9
- /* Hide scrollbars */
10
- ::-webkit-scrollbar {
11
- display: none !important;
12
- }
11
+ const require$2 = createRequire(import.meta.url);
12
+ async function getPlaywrightVersion() {
13
+ const pkgPath = require$2.resolve("playwright/package.json");
14
+ return readVersionFromPackage(pkgPath);
15
+ }
16
+ async function getArgosPlaywrightVersion() {
17
+ const pkgPath = require$2.resolve("@argos-ci/playwright/package.json");
18
+ return readVersionFromPackage(pkgPath);
19
+ }
20
+ async function getLibraryMetadata() {
21
+ const [playwrightVersion, argosPlaywrightVersion] = await Promise.all([
22
+ getPlaywrightVersion(),
23
+ getArgosPlaywrightVersion()
24
+ ]);
25
+ const metadata = {
26
+ automationLibrary: {
27
+ name: "playwright",
28
+ version: playwrightVersion
29
+ },
30
+ sdk: {
31
+ name: "@argos-ci/playwright",
32
+ version: argosPlaywrightVersion
33
+ }
34
+ };
35
+ return metadata;
36
+ }
37
+ async function getTestMetadataFromTestInfo(testInfo) {
38
+ const repositoryPath = await getGitRepositoryPath();
39
+ const testMetadata = {
40
+ id: testInfo.testId,
41
+ title: testInfo.title,
42
+ titlePath: testInfo.titlePath,
43
+ location: {
44
+ file: repositoryPath ? relative(repositoryPath, testInfo.file) : testInfo.file,
45
+ line: testInfo.line,
46
+ column: testInfo.column
47
+ }
48
+ };
49
+ return testMetadata;
50
+ }
13
51
 
14
- /* Generic hide */
15
- [data-visual-test="transparent"] {
16
- color: transparent !important;
17
- font-family: monospace !important;
18
- opacity: 0 !important;
19
- }
52
+ const require$1 = createRequire(import.meta.url);
53
+ function checkIsUsingArgosReporter(testInfo) {
54
+ const reporterPath = require$1.resolve("@argos-ci/playwright/reporter");
55
+ return testInfo.config.reporter.some((reporter)=>reporter[0].includes("@argos-ci/playwright/reporter") || reporter[0] === reporterPath);
56
+ }
20
57
 
21
- [data-visual-test="removed"] {
22
- display: none !important;
23
- }
24
- `;
25
- // Check if the fonts are loaded
26
- function waitForFontLoading() {
27
- return document.fonts.status === "loaded";
58
+ const require = createRequire(import.meta.url);
59
+ const screenshotFolder = "./screenshots";
60
+ /**
61
+ * Inject Argos script into the page.
62
+ */ async function injectArgos(page) {
63
+ const fileName = require.resolve("@argos-ci/browser/global.js");
64
+ const content = await readFile(fileName, "utf-8");
65
+ await page.addScriptTag({
66
+ content
67
+ });
28
68
  }
29
- // Check if the images are loaded
30
- function waitForImagesLoading() {
31
- const allImages = Array.from(document.images);
32
- allImages.forEach((img)=>img.loading = "eager");
33
- return allImages.every((img)=>img.complete);
69
+ async function getTestInfo() {
70
+ try {
71
+ const { test } = await import('@playwright/test');
72
+ return test.info();
73
+ } catch (error) {
74
+ return null;
75
+ }
34
76
  }
35
- // Disable spellcheck to avoid red underlines
36
- function disableSpellCheck() {
37
- const query = "[contenteditable]:not([contenteditable=false]):not([spellcheck=false]), input:not([spellcheck=false]), textarea:not([spellcheck=false])";
38
- const inputs = document.querySelectorAll(query);
39
- inputs.forEach((input)=>input.setAttribute("spellcheck", "false"));
40
- return true;
77
+ function getViewportSize(page) {
78
+ const viewportSize = page.viewportSize();
79
+ if (!viewportSize) {
80
+ throw new Error("Can't take screenshots without a viewport.");
81
+ }
82
+ return viewportSize;
41
83
  }
42
- async function argosScreenshot(page, name, { element , has , hasText , ...options } = {}) {
43
- if (!page) throw new Error("A Playwright `page` object is required.");
44
- if (!name) throw new Error("The `name` argument is required.");
84
+ async function argosScreenshot(page, name, { element, has, hasText, viewports, ...options } = {}) {
85
+ if (!page) {
86
+ throw new Error("A Playwright `page` object is required.");
87
+ }
88
+ if (!name) {
89
+ throw new Error("The `name` argument is required.");
90
+ }
45
91
  const handle = typeof element === "string" ? page.locator(element, {
46
92
  has,
47
93
  hasText
48
94
  }) : element ?? page;
49
- mkdir(screenshotFolder, {
50
- recursive: true
51
- });
52
- // Inject global styles
53
- await page.addStyleTag({
54
- content: GLOBAL_STYLES
55
- });
56
- // Wait for all busy elements to be loaded
57
- await page.waitForSelector('[aria-busy="true"]', {
58
- state: "hidden"
59
- });
60
- // Code injection to improve the screenshot stability
95
+ const testInfo = await getTestInfo();
96
+ const useArgosReporter = Boolean(testInfo && checkIsUsingArgosReporter(testInfo));
61
97
  await Promise.all([
62
- page.waitForFunction(waitForImagesLoading),
63
- page.waitForFunction(waitForFontLoading),
64
- page.waitForFunction(disableSpellCheck)
98
+ // Create the screenshot folder if it doesn't exist
99
+ useArgosReporter ? null : mkdir(screenshotFolder, {
100
+ recursive: true
101
+ }),
102
+ // Inject Argos script into the page
103
+ injectArgos(page)
65
104
  ]);
66
- await handle.screenshot({
67
- path: resolve(screenshotFolder, `${name}.png`),
68
- type: "png",
69
- fullPage: true,
70
- mask: [
71
- page.locator('[data-visual-test="blackout"]')
72
- ],
73
- animations: "disabled",
74
- ...options
75
- });
105
+ const originalViewportSize = getViewportSize(page);
106
+ await page.evaluate(()=>window.__ARGOS__.prepareForScreenshot());
107
+ async function collectMetadata(testInfo) {
108
+ const [colorScheme, mediaType, libMetadata, testMetadata] = await Promise.all([
109
+ page.evaluate(()=>window.__ARGOS__.getColorScheme()),
110
+ page.evaluate(()=>window.__ARGOS__.getMediaType()),
111
+ getLibraryMetadata(),
112
+ testInfo ? getTestMetadataFromTestInfo(testInfo) : null
113
+ ]);
114
+ const viewportSize = getViewportSize(page);
115
+ const browser = page.context().browser();
116
+ if (!browser) {
117
+ throw new Error("Can't take screenshots without a browser.");
118
+ }
119
+ const browserName = browser.browserType().name();
120
+ const browserVersion = browser.version();
121
+ const metadata = {
122
+ url: page.url(),
123
+ viewport: viewportSize,
124
+ colorScheme,
125
+ mediaType,
126
+ test: testMetadata,
127
+ browser: {
128
+ name: browserName,
129
+ version: browserVersion
130
+ },
131
+ ...libMetadata
132
+ };
133
+ return metadata;
134
+ }
135
+ async function stabilizeAndScreenshot(name) {
136
+ await page.waitForFunction(()=>window.__ARGOS__.waitForStability());
137
+ const metadata = await collectMetadata(testInfo);
138
+ const screenshotPath = useArgosReporter ? null : resolve(screenshotFolder, `${name}.png`);
139
+ const [screenshot] = await Promise.all([
140
+ handle.screenshot({
141
+ path: screenshotPath ?? undefined,
142
+ type: "png",
143
+ fullPage: handle === page,
144
+ mask: [
145
+ page.locator('[data-visual-test="blackout"]')
146
+ ],
147
+ animations: "disabled",
148
+ ...options
149
+ }),
150
+ screenshotPath ? writeMetadata(screenshotPath, metadata) : null
151
+ ]);
152
+ if (useArgosReporter) {
153
+ await Promise.all([
154
+ testInfo.attach(getAttachmentName(name, "metadata"), {
155
+ body: JSON.stringify(metadata),
156
+ contentType: "application/json"
157
+ }),
158
+ testInfo.attach(getAttachmentName(name, "screenshot"), {
159
+ body: screenshot,
160
+ contentType: "image/png"
161
+ })
162
+ ]);
163
+ }
164
+ }
165
+ // If no viewports are specified, take a single screenshot
166
+ if (!viewports) {
167
+ await stabilizeAndScreenshot(name);
168
+ return;
169
+ }
170
+ // Take screenshots for each viewport
171
+ for (const viewport of viewports){
172
+ const viewportSize = resolveViewport(viewport);
173
+ await page.setViewportSize(viewportSize);
174
+ await stabilizeAndScreenshot(getScreenshotName(name, {
175
+ viewportWidth: viewportSize.width
176
+ }));
177
+ }
178
+ // Restore the original viewport size
179
+ await page.setViewportSize(originalViewportSize);
76
180
  }
77
181
 
78
182
  export { argosScreenshot };
@@ -0,0 +1,14 @@
1
+ import { FullConfig, FullResult, Reporter, Suite, TestCase, TestResult } from "@playwright/test/reporter";
2
+ import { UploadParameters } from "@argos-ci/core";
3
+ type ArgosReporterOptions = Omit<UploadParameters, "files" | "root">;
4
+ declare class ArgosReporter implements Reporter {
5
+ uploadDir: string;
6
+ config: ArgosReporterOptions;
7
+ constructor(config: ArgosReporterOptions);
8
+ onBegin(_config: FullConfig, _suite: Suite): Promise<void>;
9
+ onTestEnd(test: TestCase, result: TestResult): Promise<void>;
10
+ onEnd(_result: FullResult): Promise<{
11
+ status: "failed";
12
+ } | undefined>;
13
+ }
14
+ export { ArgosReporter as default, ArgosReporterOptions };
@@ -0,0 +1,131 @@
1
+ import { upload } from '@argos-ci/core';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { writeFile, copyFile, mkdir } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { relative, join } from 'node:path';
6
+ import { getGitRepositoryPath, readVersionFromPackage } from '@argos-ci/util';
7
+ import { createRequire } from 'node:module';
8
+
9
+ function getOriginalAttachmentName(name) {
10
+ return name.replace(/^argos\/[^/]+___/, "");
11
+ }
12
+ function getAttachementFilename(name) {
13
+ if (name.startsWith("argos/screenshot")) {
14
+ return `${getOriginalAttachmentName(name)}.png`;
15
+ }
16
+ if (name.startsWith("argos/metadata")) {
17
+ return `${getOriginalAttachmentName(name)}.png.argos.json`;
18
+ }
19
+ throw new Error(`Unknown attachment name: ${name}`);
20
+ }
21
+
22
+ const require = createRequire(import.meta.url);
23
+ async function getPlaywrightVersion() {
24
+ const pkgPath = require.resolve("playwright/package.json");
25
+ return readVersionFromPackage(pkgPath);
26
+ }
27
+ async function getArgosPlaywrightVersion() {
28
+ const pkgPath = require.resolve("@argos-ci/playwright/package.json");
29
+ return readVersionFromPackage(pkgPath);
30
+ }
31
+ async function getLibraryMetadata() {
32
+ const [playwrightVersion, argosPlaywrightVersion] = await Promise.all([
33
+ getPlaywrightVersion(),
34
+ getArgosPlaywrightVersion()
35
+ ]);
36
+ const metadata = {
37
+ automationLibrary: {
38
+ name: "playwright",
39
+ version: playwrightVersion
40
+ },
41
+ sdk: {
42
+ name: "@argos-ci/playwright",
43
+ version: argosPlaywrightVersion
44
+ }
45
+ };
46
+ return metadata;
47
+ }
48
+ async function getTestMetadataFromTestCase(testCase) {
49
+ const repositoryPath = await getGitRepositoryPath();
50
+ const testMetadata = {
51
+ title: testCase.title,
52
+ titlePath: testCase.titlePath(),
53
+ location: {
54
+ file: repositoryPath ? relative(repositoryPath, testCase.location.file) : testCase.location.file,
55
+ line: testCase.location.line,
56
+ column: testCase.location.column
57
+ }
58
+ };
59
+ return testMetadata;
60
+ }
61
+ async function getMetadataFromTestCase(testCase) {
62
+ const [libMetadata, testMetadata] = await Promise.all([
63
+ getLibraryMetadata(),
64
+ getTestMetadataFromTestCase(testCase)
65
+ ]);
66
+ const metadata = {
67
+ test: testMetadata,
68
+ ...libMetadata
69
+ };
70
+ return metadata;
71
+ }
72
+
73
+ async function createTempDirectory() {
74
+ const osTmpDirectory = tmpdir();
75
+ const path = join(osTmpDirectory, "argos." + randomBytes(16).toString("hex"));
76
+ await mkdir(path, {
77
+ recursive: true
78
+ });
79
+ return path;
80
+ }
81
+ class ArgosReporter {
82
+ uploadDir;
83
+ config;
84
+ constructor(config){
85
+ this.config = config;
86
+ }
87
+ async onBegin(_config, _suite) {
88
+ this.uploadDir = await createTempDirectory();
89
+ }
90
+ async onTestEnd(test, result) {
91
+ await Promise.all(result.attachments.map(async (attachment)=>{
92
+ if (attachment.name.startsWith("argos/")) {
93
+ if (!attachment.body) {
94
+ throw new Error("Missing attachment body");
95
+ }
96
+ const path = join(this.uploadDir, getAttachementFilename(attachment.name));
97
+ await writeFile(path, attachment.body);
98
+ return;
99
+ }
100
+ // Error screenshots are sent to Argos
101
+ if (attachment.name === "screenshot" && attachment.contentType === "image/png" && attachment.path) {
102
+ const metadata = await getMetadataFromTestCase(test);
103
+ const name = test.titlePath().join(" ");
104
+ const path = join(this.uploadDir, `${name} (failed).png`);
105
+ await Promise.all([
106
+ writeFile(path + ".argos.json", JSON.stringify(metadata)),
107
+ copyFile(attachment.path, path)
108
+ ]);
109
+ }
110
+ }));
111
+ }
112
+ async onEnd(_result) {
113
+ try {
114
+ await upload({
115
+ files: [
116
+ "*.png"
117
+ ],
118
+ root: this.uploadDir,
119
+ ...this.config
120
+ });
121
+ } catch (error) {
122
+ console.error(error);
123
+ return {
124
+ status: "failed"
125
+ };
126
+ }
127
+ return;
128
+ }
129
+ }
130
+
131
+ export { ArgosReporter as default };
package/package.json CHANGED
@@ -1,10 +1,14 @@
1
1
  {
2
2
  "name": "@argos-ci/playwright",
3
3
  "description": "Visual testing solution to avoid visual regression. Playwright commands and utilities for Argos visual testing.",
4
- "version": "0.0.7",
4
+ "version": "0.0.8-alpha.187+b2cbada",
5
5
  "author": "Smooth Code",
6
6
  "license": "MIT",
7
- "repository": "github:argos-ci/argos-playwright",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/argos-ci/argos-javascript.git",
10
+ "directory": "packages/playwright"
11
+ },
8
12
  "keywords": [
9
13
  "playwright",
10
14
  "argos",
@@ -18,9 +22,6 @@
18
22
  "publishConfig": {
19
23
  "access": "public"
20
24
  },
21
- "engines": {
22
- "node": ">=16"
23
- },
24
25
  "type": "module",
25
26
  "types": "./dist/index.d.ts",
26
27
  "exports": {
@@ -30,32 +31,32 @@
30
31
  "types": "./dist/index.d.ts",
31
32
  "default": "./dist/index.mjs"
32
33
  },
34
+ "./reporter": {
35
+ "import": "./dist/reporter.mjs",
36
+ "types": "./dist/reporter.d.ts",
37
+ "default": "./dist/reporter.mjs"
38
+ },
33
39
  "./package.json": "./package.json"
34
40
  },
41
+ "engines": {
42
+ "node": ">=16.0.0"
43
+ },
44
+ "dependencies": {
45
+ "@argos-ci/browser": "0.0.0",
46
+ "@argos-ci/core": "0.12.1-alpha.7+b2cbada",
47
+ "@argos-ci/util": "0.0.1-alpha.187+b2cbada"
48
+ },
49
+ "devDependencies": {
50
+ "@argos-ci/cli": "0.6.1-alpha.7+b2cbada",
51
+ "@argos-ci/playwright": "workspace:.",
52
+ "@playwright/test": "^1.38.1",
53
+ "@types/node": "^16.0.0"
54
+ },
35
55
  "scripts": {
36
56
  "prebuild": "rm -rf dist",
37
57
  "build": "rollup -c",
38
- "test": "npx playwright test",
39
- "format": "prettier --write . --ignore-path .gitignore",
40
- "check-format": "prettier --check .",
41
- "lint": "eslint --ignore-path .gitignore .",
42
- "prepublishOnly": "npm run build",
43
- "release": "standard-version && conventional-github-releaser --preset angular"
58
+ "test": "pnpm exec playwright test",
59
+ "e2e": "WITH_ARGOS_REPORTER=true pnpm run test"
44
60
  },
45
- "devDependencies": {
46
- "@argos-ci/cli": "^0.4.4",
47
- "@playwright/test": "^1.30.0",
48
- "@swc/cli": "^0.1.62",
49
- "@swc/core": "^1.3.35",
50
- "@typescript-eslint/eslint-plugin": "^5.52.0",
51
- "@typescript-eslint/parser": "^5.52.0",
52
- "conventional-github-releaser": "^3.1.5",
53
- "eslint": "^8.34.0",
54
- "prettier": "^2.8.4",
55
- "rollup": "^3.17.1",
56
- "rollup-plugin-dts": "^5.2.0",
57
- "rollup-plugin-swc3": "^0.8.0",
58
- "standard-version": "^9.5.0",
59
- "typescript": "^4.9.5"
60
- }
61
+ "gitHead": "b2cbadab77b42d32946e7ed315290e9b9bd7d245"
61
62
  }