-
Notifications
You must be signed in to change notification settings - Fork 6
PER-8985 feat: toHaveScreenshot drop-in — route existing Playwright assertions through Percy #640
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
10582e1
feat(dropin): toHaveScreenshot drop-in — route existing Playwright as…
Shivanshu-07 7f63c81
ci: run on Node 18/20 — @playwright/test >=1.60 requires Node 18
Shivanshu-07 734bd25
ci: install Playwright browsers explicitly
Shivanshu-07 1a64847
ci: fix coverage run — istanbul-ignore browser-executed evaluates, sc…
Shivanshu-07 deea22a
ci: istanbul-ignore the ENV_INFO fallback chain
Shivanshu-07 b86f508
ci: test matrix on Node 20/22 (18 is EOL)
Shivanshu-07 865c3df
fix: validate path segments at the drop-in filesystem boundary
Shivanshu-07 caa8f45
feat(dropin): dispatch toHaveScreenshot by Percy project type — reuse…
Shivanshu-07 1b4808e
feat(dropin): CLI-driven baseline seeding + web-only capture
Shivanshu-07 c59ae7b
feat(dropin): restore app-project capture — dual dispatch by project …
Shivanshu-07 0fe6ec7
Merge origin/master into feat/tohavescreenshot-dropin
Shivanshu-07 bc92e2c
feat(dropin): enabled:false / PERCY_DROPIN_DISABLE — pure-native opt-out
Shivanshu-07 6393fe3
fix: declare @percy/sdk-utils ^1.32.0 as a direct dependency
Shivanshu-07 e2239c1
test: guard the responsiveSnapshotCapture-true log read against the s…
Shivanshu-07 ed2682a
review: gate/reporter correctness, identity parity, config-error latc…
Shivanshu-07 6077ec4
review: address PR feedback — dedupe token check, single version-info…
Shivanshu-07 f0307d4
test: poll the shared-server log assertion in the responsive-mobile spec
Shivanshu-07 700a41e
chore: strip design-doc tags and narration from drop-in comments
Shivanshu-07 a8d60a7
test: extend the shared-server log polling guard to the remaining sin…
Shivanshu-07 1742f8b
test: repost-and-retry the responsive-mobile log assertion
Shivanshu-07 a9fc5dc
test: run the suite single-worker — the shared testing server is glob…
Shivanshu-07 f8b7e18
feat: dispatch toHaveScreenshot to Percy on Automate for automate pro…
Shivanshu-07 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| // `percy playwright:setup-baseline` — explicitly (re-)establish a Percy project's baseline from | ||
| // the Playwright baseline screenshots committed in the repo, WITHOUT running any tests. | ||
| // | ||
| // Discovered by @percy/cli through this package's `"@percy/cli": { "commands": [...] }` entry | ||
| // (the same mechanism @percy/storybook uses), so installing @percy/playwright is all it takes. | ||
| // Unlike the automatic first-build seeding `percy exec` performs on an empty project, this | ||
| // command works on ESTABLISHED projects too: the build is created with the explicit | ||
| // `dropin-baseline-setup` attribute the API accepts as a deliberate, user-triggered re-baseline | ||
| // and auto-approves at finalize. | ||
| // | ||
| // ESM on purpose: @percy/cli-command and @percy/cli-exec are ESM-only; the CLI imports command | ||
| // modules with dynamic import, so this file never enters the (CJS) SDK require graph. | ||
| import command from '@percy/cli-command'; | ||
|
|
||
| const BASELINE_SOURCE = 'playwright-dropin-baseline'; | ||
|
|
||
| export const setupBaseline = command('setup-baseline', { | ||
| description: 'Upload committed Playwright baseline screenshots as the auto-approved Percy baseline (no tests run)', | ||
|
|
||
| examples: [ | ||
| '$0' | ||
| ], | ||
|
|
||
| percy: { | ||
| skipDiscovery: true | ||
| } | ||
| }, async function * ({ percy, log, exit }) { | ||
| if (!percy) exit(1, 'Percy is disabled'); | ||
|
|
||
| // Web projects seed rendered snapshots; app projects seed raw comparison uploads (no render | ||
| // flow — like App Percy). Automate projects are drop-in supported but NOT seedable — their | ||
| // baseline comes from the first remote run — and anything else is a wrong token. | ||
| let { SEEDABLE_PROJECT_TYPES, seedingUnsupportedError } = await import('../dropin/config.js') | ||
| .then(m => m.default || m); | ||
| let projectType = percy.client.tokenType(); | ||
| if (!SEEDABLE_PROJECT_TYPES.includes(projectType)) { | ||
| exit(1, seedingUnsupportedError(projectType)); | ||
| } | ||
|
|
||
| // The provider owns all Playwright knowledge (config resolution, snapshot discovery, identity | ||
| // mapping); the CLI's exec package owns the upload loop. Nothing is reimplemented here. | ||
| let { default: provider } = await import('../dropin/baseline/provider.js'); | ||
|
|
||
| // uploadBaselines ships in the companion @percy/cli release — an older CLI resolves the | ||
| // package but not the export. Fail with guidance, not a bare TypeError. | ||
| let uploadBaselines; | ||
| try { | ||
| ({ uploadBaselines } = await import('@percy/cli-exec')); | ||
| } catch { /* handled below */ } | ||
| if (typeof uploadBaselines !== 'function') { | ||
| exit(1, 'playwright:setup-baseline requires a newer @percy/cli — ' + | ||
| 'upgrade with `npm i -D @percy/cli@latest` and retry.'); | ||
| } | ||
|
|
||
| let { baselines = [], degraded, reason } = | ||
| (await provider.discoverBaselines({ cwd: process.cwd(), log })) || {}; | ||
|
|
||
| if (degraded) { | ||
| exit(1, `Could not map your committed Playwright baselines (${reason}). ` + | ||
| 'Custom snapshot path templates and projects without an explicit browser/viewport ' + | ||
| 'cannot be mapped automatically.'); | ||
| } | ||
| if (!baselines.length) { | ||
| exit(1, 'No committed Playwright baseline screenshots found ' + | ||
| '(looked for Playwright\'s *-snapshots directories).'); | ||
| } | ||
|
|
||
| log.info(`Uploading ${baselines.length} committed baseline snapshot(s) as the project baseline...`); | ||
|
|
||
| let res = await percy.client.createBuild({ | ||
| projectType, | ||
| source: BASELINE_SOURCE, | ||
| dropinBaselineSetup: true | ||
| }); | ||
|
|
||
| let buildId = res.data.id; | ||
| let seeded = await uploadBaselines(percy.client, buildId, baselines, { log, projectType }); | ||
| await percy.client.finalizeBuild(buildId); | ||
|
|
||
| if (!seeded) exit(1, 'No baseline snapshots could be uploaded.'); | ||
|
|
||
| log.info(`Baseline established from ${seeded}/${baselines.length} snapshot(s) and ` + | ||
| `auto-approved: ${res.data.attributes['web-url']}`); | ||
| }); | ||
|
|
||
| // Topic wrapper so the command surfaces as `percy playwright:setup-baseline`. | ||
| export const playwright = command('playwright', { | ||
| description: 'Playwright drop-in utilities', | ||
| commands: [setupBaseline] | ||
| }); | ||
|
|
||
| export default playwright; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| 'use strict'; | ||
|
|
||
| // Screenshot seam for the toHaveScreenshot drop-in — the AUTOMATE-project dispatch target. | ||
| // | ||
| // This is a thin wrapper around the repo's own `percyScreenshot()` (index.js): the drop-in hands | ||
| // off to the EXACT Percy-on-Automate entry point a hand-written `percyScreenshot(page, name)` | ||
| // test would use, so it inherits the session-details lookup, the CLI `/percy/automateScreenshot` | ||
| // handoff and the remote capture — nothing is reimplemented here and the two entry points can | ||
| // never drift apart. | ||
| // | ||
| // SEMANTICS (vs the web/app flows): the capture happens on the REMOTE BrowserStack browser via | ||
| // the Automate session — no local pixels or DOM ever leave the test process, and the comparison | ||
| // tag identity (browser/os/width/device) comes from the real session, not from the Playwright | ||
| // config. That has two consequences surfaced here: | ||
| // • The suite MUST be running on BrowserStack Automate (e.g. via browserstack-node-sdk). A | ||
| // local browser has no session to capture through — that is a configuration error, reported | ||
| // with a clear message instead of percyScreenshot's raw JSON-parse noise. | ||
| // • Locator subjects and raw-pixel options (mask/clip/…) cannot apply to a remote capture; | ||
| // they degrade to a full-page capture and are surfaced once at warn level. | ||
| const utils = require('@percy/sdk-utils'); | ||
| const { Utils } = require('../utils'); | ||
|
|
||
| const log = utils.logger('playwright-dropin'); | ||
|
|
||
| // Lazy-required at capture time: the root module may itself be mid-load when the drop-in entry is | ||
| // evaluated (specs import both as ESM), and a top-level require here trips Node's CJS↔ESM | ||
| // interop on a partially-initialized module. | ||
| function rootPercyScreenshot(...args) { | ||
| return require('../index.js').percyScreenshot(...args); | ||
| } | ||
|
|
||
| // toHaveScreenshot options that only make sense for a LOCAL capture — the remote Automate | ||
| // capture cannot apply them. `fullPage` is the one local capture option with a POA equivalent | ||
| // and is mapped through instead. | ||
| const LOCAL_ONLY_OPTS = Object.freeze([ | ||
| 'clip', 'mask', 'maskColor', 'omitBackground', 'scale', 'animations', 'caret', 'style', 'stylePath' | ||
| ]); | ||
|
|
||
| // One-per-run notices — every assertion in a suite hits the same degradations, so warn once. | ||
| let _localOptsWarned = false; | ||
| let _locatorWarned = false; | ||
| function _resetNotices() { _localOptsWarned = false; _locatorWarned = false; } | ||
|
|
||
| // A Locator exposes `.page()`; a Page does not. | ||
| function resolvePage(pageOrLocator) { | ||
| return pageOrLocator && typeof pageOrLocator.page === 'function' | ||
| ? pageOrLocator.page() | ||
| : pageOrLocator; | ||
| } | ||
|
|
||
| // Take a Percy-on-Automate screenshot for a Page or Locator subject by delegating to the SDK's | ||
| // own `percyScreenshot`. Returns percyScreenshot's return value (the comparison detail when | ||
| // `sync` is set, undefined otherwise or on a swallowed error; the sync classifier owns the | ||
| // undefined case). Throws ONLY the configuration error below — percyScreenshot catches its own | ||
| // runtime errors. `deps` is injectable for tests. | ||
| async function screenshotViaAutomate(pageOrLocator, name, { sync } = {}, options = {}, deps = {}) { | ||
| const percyScreenshot = deps.percyScreenshot || rootPercyScreenshot; | ||
| const sessionDetails = deps.sessionDetails || (page => Utils.sessionDetails(page)); | ||
| const page = resolvePage(pageOrLocator); | ||
|
|
||
| if (page !== pageOrLocator && !_locatorWarned) { | ||
| _locatorWarned = true; | ||
| log.warn('Percy: element screenshots are not supported on Automate projects — capturing the ' + | ||
| 'full page for Locator subjects (the snapshot name is unchanged, so baselines stay stable)'); | ||
| } | ||
|
|
||
| const ignored = LOCAL_ONLY_OPTS.filter(k => options && options[k] !== undefined); | ||
| if (ignored.length && !_localOptsWarned) { | ||
| _localOptsWarned = true; | ||
| log.warn(`Percy: ignoring toHaveScreenshot option(s) on an Automate project: ${ignored.join(', ')} — ` + | ||
| 'the capture happens on the remote BrowserStack browser, not from local pixels'); | ||
| } | ||
|
|
||
| // Session preflight. `getSessionDetails` only answers on a BrowserStack Automate browser — on a | ||
| // local browser the executor script evaluates to nothing and percyScreenshot would surface an | ||
| // opaque JSON-parse error. Detect that here and raise a CONFIGURATION error (same class as a | ||
| // wrong token: the user must fix their setup, so it is allowed to fail the assertion) with the | ||
| // actual fix in the message. Detection is per-assertion, not latched — hybrid suites that run | ||
| // some Playwright projects locally and some on BrowserStack keep working for the remote ones. | ||
| let session = null; | ||
| try { | ||
| session = await sessionDetails(page); | ||
| } catch { /* handled below — an unreachable/undecodable session is the same config error */ } | ||
| if (!session || !session.hashed_id) { | ||
| const err = new Error('Percy: the configured token is for a Percy on Automate project, but ' + | ||
| 'this browser is not a BrowserStack Automate session — run the suite on BrowserStack ' + | ||
| '(e.g. via browserstack-node-sdk), or use a web/app project token for local runs.'); | ||
| err.isConfigurationError = true; | ||
| throw err; | ||
| } | ||
|
|
||
| const poaOptions = {}; | ||
| if (options && options.fullPage !== undefined) poaOptions.fullPage = options.fullPage; | ||
| if (sync) poaOptions.sync = true; | ||
|
|
||
| return percyScreenshot(page, name, poaOptions); | ||
| } | ||
|
|
||
| module.exports = { screenshotViaAutomate, resolvePage, LOCAL_ONLY_OPTS, _resetNotices }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| 'use strict'; | ||
|
|
||
| // Playwright reporter used ONLY to capture the RESOLVED config outside a test run. | ||
| // | ||
| // Baseline discovery (discover.js) reconstructs snapshot identity from the resolved config | ||
| // (projects' browserName/viewport, snapshot path templates). Inside a test run that config came | ||
| // from globalSetup's FullConfig; the CLI-driven seeding flow runs BEFORE any test run, so | ||
| // resolve-config.js spawns `npx playwright test --list --reporter=<this file>` — Playwright | ||
| // resolves its own config (including TS configs) and hands it to `onBegin`, which serializes the | ||
| // minimal shape discovery needs to the file named by PERCY_PW_CONFIG_OUT. `--list` performs test | ||
| // discovery only; no test executes. | ||
| const fs = require('fs'); | ||
|
|
||
| const screenshotTpl = obj => | ||
| obj && obj.expect && obj.expect.toHaveScreenshot && obj.expect.toHaveScreenshot.pathTemplate; | ||
|
|
||
| class PercyConfigReporter { | ||
| onBegin(config) { | ||
| const out = process.env.PERCY_PW_CONFIG_OUT; | ||
| if (!out) return; | ||
|
|
||
| const shape = { | ||
| rootDir: config.rootDir, | ||
| snapshotDir: config.snapshotDir, | ||
| snapshotPathTemplate: config.snapshotPathTemplate, | ||
| expect: screenshotTpl(config) | ||
| ? { toHaveScreenshot: { pathTemplate: screenshotTpl(config) } } | ||
| : undefined, | ||
| projects: (config.projects || []).map(p => ({ | ||
| name: p.name || '', | ||
| use: { | ||
| browserName: p.use && p.use.browserName, | ||
| viewport: p.use && p.use.viewport | ||
| }, | ||
| snapshotPathTemplate: p.snapshotPathTemplate, | ||
| expect: screenshotTpl(p) | ||
| ? { toHaveScreenshot: { pathTemplate: screenshotTpl(p) } } | ||
| : undefined | ||
| })) | ||
| }; | ||
|
|
||
| // Local-only handoff: resolve-config.js (the spawning side) reads this file immediately and | ||
| // deletes it in its `finally` — nothing here is uploaded or persisted beyond the one call. | ||
| fs.writeFileSync(out, JSON.stringify(shape)); | ||
| } | ||
|
|
||
| // Keep `--list` output clean; this reporter only writes the config file. | ||
| printsToStdio() { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| module.exports = PercyConfigReporter; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.