Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ The same test, recorded twice. `--video` includes the test title, action caption

`npx playwright test --video` makes a narrated video of your tests with captions, a moving cursor and a camera that follows the action. Use `--demo` for a version without test names and results. Add `narrate()` calls to explain what's happening, or let Flashwright generate captions from the actions and assertions.

It needs `ffmpeg`. Recording adds waits for the page to paint, and captions include typed text, including passwords, so use test data you're happy to share. [Examples, voice setup and recording options](docs/videos.md).
It needs `ffmpeg`. Recording adds waits for the page to paint, and captions include typed text (password fields show as dots), so use test data you're happy to share. [Examples, voice setup and recording options](docs/videos.md).

## Quality-of-life features

Expand Down
3 changes: 2 additions & 1 deletion docs/src/test-api/class-testconfig.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,12 +427,13 @@ export default defineConfig({
- `captions` ?<[boolean]> Whether captions are drawn under the page. Defaults to `true`.
- `voice` ?<[string]|[boolean]|[function]> Which voice reads the narration: `'auto'`, `'system'`, `'kokoro'`, `false` for none, or a function that takes the text and returns the audio. Defaults to `'auto'`, which is Kokoro once `npx playwright install-voice` has set it up and the system's voice before that.
- `voiceName` ?<[string]> A voice of the engine, such as `'Samantha'` for macOS or `'af_heart'` for Kokoro.
- `showPasswords` ?<[boolean]> Whether captions show the text typed into password fields: inputs of type `password`, or with `autocomplete="current-password"` or `"new-password"`. Defaults to `false`, which captions it as eight dots.

Turns the run into one finished video with a voice, captions, a moving cursor and a camera, in `video.mp4` in the output directory, next to a clip of each test in the test's output directory. See [`property: Fixtures.narrate`]. The video is put together after the tests, which run about as fast as without it, so its timing is not the test's. It needs `ffmpeg`.

In `'on'` mode the video also shows each test's title and result, and what it clicks, types and asserts. In `'demo'` mode it shows only the page and what [`property: Fixtures.narrate`] said, and it leaves out tests that failed.

Recording replaces [`property: TestOptions.video`], turns off the screenshots of [`property: TestOptions.trace`], and gives each test a new context. Captions show the text that tests type, including passwords, so use test data you are happy to share.
Recording replaces [`property: TestOptions.video`], turns off the screenshots of [`property: TestOptions.trace`], and gives each test a new context. Captions show the text that tests type, except into password fields, so use test data you are happy to share.

**Usage**

Expand Down
3 changes: 2 additions & 1 deletion docs/videos.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,14 @@ export default defineConfig({
captions: true, // --no-video-captions; the subtitle track stays, off unless a player asks for it
voice: 'auto', // 'auto', 'system', 'kokoro', false (--no-video-voice), or a function that returns the audio, for a paid voice
voiceName: 'Samantha',
showPasswords: false, // true captions what is typed into password fields instead of dots
},
});
```

## Recording limitations

Captions show the text that tests type, including passwords, and the page shows what your app shows, so use test data you are happy to share. Recording replaces the `video` option, turns off the screenshots of `trace` and gives each test a new context, and a test cannot use `page.screencast` itself in that run. `summary.json` in [agent mode](agents.md#agent-mode) has the video's path.
Captions show the text that tests type, except into password fields (`type="password"`, or `autocomplete="current-password"` or `"new-password"`), which they show as eight dots; `showPasswords: true` shows it. Other fields and the page show what your app shows, so use test data you are happy to share. Recording replaces the `video` option, turns off the screenshots of `trace` and gives each test a new context, and a test cannot use `page.screencast` itself in that run. `summary.json` in [agent mode](agents.md#agent-mode) has the video's path.

## Reproduce the README example

Expand Down
1 change: 1 addition & 0 deletions packages/playwright-core/src/client/channels.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4358,6 +4358,7 @@ export type PageScreencastInputActionEvent = {
timestamp: number,
point?: Point,
box?: Rect,
secret?: boolean,
};
export type PageWebSocketRouteEvent = {
webSocketRoute: WebSocketRouteChannel,
Expand Down
1 change: 1 addition & 0 deletions packages/playwright-core/src/server/channels.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4359,6 +4359,7 @@ export type PageScreencastInputActionEvent = {
timestamp: number,
point?: Point,
box?: Rect,
secret?: boolean,
};
export type PageWebSocketRouteEvent = {
webSocketRoute: WebSocketRouteChannel,
Expand Down
11 changes: 8 additions & 3 deletions packages/playwright-core/src/server/screencast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { debugLogger } from '@utils/debugLogger';
import { Page } from './page';
import { nullProgress } from './progress';
import { ElementHandle } from './dom';
import { isSecretInput } from './secretInput';

import type { InstrumentationListener, SdkObject } from './instrumentation';
import type * as types from './types';
Expand All @@ -31,7 +32,7 @@ export type ScreencastClient = {
// Flashwright: rejects with the error that closing would report when the client could not start.
launched?: () => Promise<void>;
// Flashwright: told about every input action, and makes actions wait for the frame that shows them.
onInputAction?: (action: { timestamp: number, point?: types.Point, box?: types.Rect }) => void;
onInputAction?: (action: { timestamp: number, point?: types.Point, box?: types.Rect, secret?: boolean }) => void;
dispose: () => void;
size?: types.Size;
quality?: number;
Expand Down Expand Up @@ -227,8 +228,12 @@ export class Screencast implements InstrumentationListener {

async onBeforeInputAction(progress: Progress, sdkObject: SdkObject, point?: types.Point, box?: types.Rect): Promise<void> {
if (sdkObject.attribution.page === this.page) {
for (const client of this._clients.keys())
client.onInputAction?.({ timestamp: Date.now(), point, box });
const clients = [...this._clients.keys()].filter(client => client.onInputAction);
const timestamp = Date.now();
// Flashwright: a video's captions leave out what is typed into a password field.
const secret = clients.length ? await isSecretInput(progress, sdkObject) || undefined : undefined;
for (const client of clients)
client.onInputAction!({ timestamp, point, box, secret });
}
if (!this._actions)
return;
Expand Down
53 changes: 53 additions & 0 deletions packages/playwright-core/src/server/secretInput.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Copyright (c) Microsoft Corporation.
*
* 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.
*/

import { ElementHandle } from './dom';
import { Page } from './page';

import type { SdkObject } from './instrumentation';
import type { Progress } from './progress';

// Flashwright: whether an action types into a password field, so that `playwright test --video`
// can leave the text out of its captions. Asked only for the actions that type text, and only
// while a video follows the actions.

const kElementMethods = new Set(['fill', 'type']);
const kKeyboardMethods = new Set(['keyboardType', 'keyboardInsertText']);

export async function isSecretInput(progress: Progress, sdkObject: SdkObject): Promise<boolean> {
const method = progress.metadata.method;
try {
if (sdkObject instanceof ElementHandle && kElementMethods.has(method)) {
const result = await progress.race(sdkObject.evaluateInUtility(([injected, node]) => {
const element = injected.retarget(node, 'follow-label');
return !!element && element.nodeName === 'INPUT' && ((element as HTMLInputElement).type.toLowerCase() === 'password' || /\b(current|new)-password\b/i.test(element.getAttribute('autocomplete') ?? ''));
}, {}));
return result === true;
}
if (sdkObject instanceof Page && kKeyboardMethods.has(method)) {
// Only the focused element of the main frame and its shadow roots; typing inside a child frame is not checked.
const utility = await progress.race(sdkObject.mainFrame().utilityContext());
return await progress.race(utility.evaluate(() => {
let element = document.activeElement;
while (element?.shadowRoot?.activeElement)
element = element.shadowRoot.activeElement;
return !!element && element.nodeName === 'INPUT' && ((element as HTMLInputElement).type.toLowerCase() === 'password' || /\b(current|new)-password\b/i.test(element.getAttribute('autocomplete') ?? ''));
}));
}
} catch {
}
return false;
}
1 change: 1 addition & 0 deletions packages/playwright/src/common/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ export class FullConfigInternal {
captions: takeFirst(configCLIOverrides.narratedVideo?.captions, userConfig.narratedVideo?.captions, true),
voice: takeFirst(configCLIOverrides.narratedVideo?.voice, userConfig.narratedVideo?.voice, 'auto'),
voiceName: userConfig.narratedVideo?.voiceName,
showPasswords: takeFirst(userConfig.narratedVideo?.showPasswords, false),
},
preserveOutput: takeFirst(userConfig.preserveOutput, 'always'),
projects: [],
Expand Down
2 changes: 1 addition & 1 deletion packages/playwright/src/isomorphic/teleReceiver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -824,7 +824,7 @@ export const baseFullConfig: reporterTypes.FullConfig = {
grepInvert: null,
maxFailures: 0,
metadata: {},
narratedVideo: { mode: 'off', zoom: true, captions: true, voice: 'auto' },
narratedVideo: { mode: 'off', zoom: true, captions: true, voice: 'auto', showPasswords: false },
preserveOutput: 'always',
testOrder: 'longest-first',
projects: [],
Expand Down
7 changes: 4 additions & 3 deletions packages/playwright/src/narratedVideoRecorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ export type Recording = {
duration: number;
outputDir: string;
frames: { file: string, time: number, page: number, width: number, height: number }[];
inputs: { time: number, page: number, point?: RecordedPoint, box?: RecordedBox }[];
// `secret` when the action typed into a password field.
inputs: { time: number, page: number, point?: RecordedPoint, box?: RecordedBox, secret?: boolean }[];
// `file` is the picture of the page that the voice speaks over.
narrations: { order: number, text: string, time: number, page?: number, file?: string }[];
steps: RecordedStep[];
Expand Down Expand Up @@ -219,8 +220,8 @@ export class NarratedVideoRecorder {
this._addFrame(data, index, viewportWidth, viewportHeight);
this._lastPaintedPage = page;
},
_onInputAction: (action: { timestamp: number, point?: RecordedPoint, box?: RecordedBox }) => {
this._inputs.push({ time: action.timestamp, page: index, point: action.point, box: action.box });
_onInputAction: (action: { timestamp: number, point?: RecordedPoint, box?: RecordedBox, secret?: boolean }) => {
this._inputs.push({ time: action.timestamp, page: index, point: action.point, box: action.box, secret: action.secret });
},
} as any), { internal: true }).catch(() => {});
this._started.push(start);
Expand Down
14 changes: 9 additions & 5 deletions packages/playwright/src/runner/narratedVideo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ const kInputMethods = new Set(['click', 'dblclick', 'tap', 'fill', 'press', 'typ
const kPointerMethods = new Set(['click', 'dblclick', 'tap', 'fill', 'check', 'uncheck', 'setChecked', 'selectOption', 'mouseClick']);

const quote = (text: string) => `\u201c${text}\u201d`;
// The same length for every password, so the video does not tell how long it is.
const kMaskedText = '\u2022'.repeat(8);

function describeTarget(selector = ''): { text: string, name?: string } {
const parts = selector.split(' >> ');
Expand All @@ -79,8 +81,9 @@ function describeTarget(selector = ''): { text: string, name?: string } {
return { text: (name ? quote(name) : 'the element') + (context ? ` for ${quote(context)}` : ''), name };
}

export function describeAction(step: Recording['steps'][0]): string {
export function describeAction(step: Recording['steps'][0], secret = false): string {
const params = step.params ?? {};
const typed = (text: string) => quote(secret ? kMaskedText : text.slice(0, 80));
const target = describeTarget(params.selector);
switch (step.method) {
case 'goto': {
Expand All @@ -93,11 +96,11 @@ export function describeAction(step: Recording['steps'][0]): string {
}
case 'fill':
case 'type':
return params.value ? `Type ${quote(params.value.slice(0, 80))} into ${target.text}` : `Clear ${target.text}`;
return params.value ? `Type ${typed(params.value)} into ${target.text}` : `Clear ${target.text}`;
case 'press': return `Press ${params.key} in ${target.text}`;
case 'keyboardPress': return `Press ${params.key}`;
case 'keyboardType':
case 'keyboardInsertText': return `Type ${quote((params.text ?? '').slice(0, 80))}`;
case 'keyboardInsertText': return `Type ${typed(params.text ?? '')}`;
case 'check': return `Check ${target.text}`;
case 'uncheck': return `Uncheck ${target.text}`;
case 'selectOption': return `Choose an option in ${target.text}`;
Expand Down Expand Up @@ -210,7 +213,8 @@ function planClip(dir: string, recording: Recording, options: NarratedVideoOptio

const inputFor = (start: number, end: number | undefined) => {
const inputs = recording.inputs.filter(input => input.time >= start - 2 && input.time <= (end ?? Infinity) + 2);
return inputs.find(input => input.point) ?? inputs.find(input => input.box) ?? inputs[0];
const input = inputs.find(input => input.point) ?? inputs.find(input => input.box) ?? inputs[0];
return { ...input, secret: inputs.some(input => input.secret) && !options.showPasswords };
};

type Event = { order: number, kind: 'action' | 'assertion' | 'speech', time: number, end: number, text: string, file?: string, failed?: boolean, method?: string, point?: RecordedPoint, box?: RecordedBox, page?: number };
Expand All @@ -223,7 +227,7 @@ function planClip(dir: string, recording: Recording, options: NarratedVideoOptio
continue;
seenAction = true;
const input = inputFor(step.start, step.end);
events.push({ order: step.order, kind: 'action', time: step.start, end: step.end ?? step.start, text: describeAction(step), method: step.method, point: input?.point, box: input?.box, page: input?.page });
events.push({ order: step.order, kind: 'action', time: step.start, end: step.end ?? step.start, text: describeAction(step, input.secret), method: step.method, point: input.point, box: input.box, page: input.page });
} else if (step.category === 'expect' && !demo) {
events.push({ order: step.order, kind: 'assertion', time: step.start, end: step.end ?? step.start, text: describeAssertion(step), failed: step.failed });
}
Expand Down
5 changes: 3 additions & 2 deletions packages/playwright/types/test.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -935,6 +935,7 @@ export type NarratedVideoOptions = {
captions?: boolean;
voice?: 'auto' | 'system' | 'kokoro' | false | ((text: string) => Promise<Buffer>);
voiceName?: string;
showPasswords?: boolean;
};

/**
Expand Down Expand Up @@ -1147,8 +1148,8 @@ interface TestConfig<TestArgs = {}, WorkerArgs = {}> {
*
* Recording replaces [testOptions.video](https://playwright.dev/docs/api/class-testoptions#test-options-video), turns
* off the screenshots of [testOptions.trace](https://playwright.dev/docs/api/class-testoptions#test-options-trace),
* and gives each test a new context. Captions show the text that tests type, including passwords, so use test data
* you are happy to share.
* and gives each test a new context. Captions show the text that tests type, except into password fields, so use test
* data you are happy to share.
*
* **Usage**
*
Expand Down
1 change: 1 addition & 0 deletions packages/protocol/spec/page.yml
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,7 @@ Page:
timestamp: float
point: Point?
box: Rect?
secret: boolean?

webSocketRoute:
parameters:
Expand Down
1 change: 1 addition & 0 deletions packages/protocol/src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2482,6 +2482,7 @@ scheme.PageScreencastInputActionEvent = tObject({
timestamp: tFloat,
point: tOptional(tType('Point')),
box: tOptional(tType('Rect')),
secret: tOptional(tBoolean),
});
scheme.PageWebSocketRouteEvent = tObject({
webSocketRoute: tChannel(['WebSocketRoute']),
Expand Down
43 changes: 42 additions & 1 deletion tests/playwright-test/flashwright-narrated-video.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,14 +515,55 @@ test('captions say what is typed', async () => {
expect(describe('fill', { selector: 'internal:label="Password"i', value: 'hunter2' })).toBe('Type \u201chunter2\u201d into \u201cPassword\u201d');
expect(describe('fill', { selector: 'internal:label="Email"i', value: '' })).toBe('Clear \u201cEmail\u201d');
expect(describe('keyboardType', { text: 'hello' })).toBe('Type \u201chello\u201d');
const describeSecret = (method: string, params: any) => narratedVideo.describeAction({ order: 0, title: '', category: 'pw:api', start: 0, method, params }, true);
expect(describeSecret('fill', { selector: 'internal:label="Password"i', value: 'hunter2' })).toBe('Type \u201c\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u201d into \u201cPassword\u201d');
expect(describeSecret('fill', { selector: 'internal:label="Password"i', value: 'a much longer passphrase' })).toBe('Type \u201c\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u201d into \u201cPassword\u201d');
expect(describeSecret('fill', { selector: 'internal:label="Password"i', value: '' })).toBe('Clear \u201cPassword\u201d');
expect(describeSecret('keyboardType', { text: 'hunter2' })).toBe('Type \u201c\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u201d');
});

test('typing into a password field is recorded as secret', async ({ runInlineTest }) => {
const result = await runInlineTest({
'playwright.config.js': voiceConfig(),
'a.spec.ts': `
import { test } from '@playwright/test';
test('sign in', async ({ page }) => {
await page.setContent(\`
<label>Email <input name=email></label>
<label>Password <input type=password name=password></label>
<label>New password <input autocomplete="new-password" name=next></label>
\`);
await page.getByLabel('Email').fill('ann@example.com');
await page.getByText('Password', { exact: true }).fill('hunter2');
await page.getByLabel('New password').pressSequentially('hunter3');
await page.getByLabel('Email').focus();
await page.keyboard.type('x');
await page.locator('[name=password]').focus();
await page.keyboard.insertText('hunter4');
});
`,
}, { video: true }, { FLASHWRIGHT_KEEP_VIDEO_WORK: '1' });
expect(result.exitCode).toBe(0);
const root = test.info().outputPath('test-results', '.video-recordings');
const recording = JSON.parse(fs.readFileSync(path.join(root, fs.readdirSync(root)[0], 'recording.json'), 'utf8'));
const secretAt = (method: string) => {
const step = recording.steps.find((step: any) => step.method === method && step.category === 'pw:api');
return recording.inputs.some((input: any) => input.secret && input.time >= step.start - 2 && input.time <= step.end + 2);
};
const fills = recording.steps.filter((step: any) => step.method === 'fill');
const secretIn = (step: any) => recording.inputs.some((input: any) => input.secret && input.time >= step.start - 2 && input.time <= step.end + 2);
expect(fills.map(secretIn)).toEqual([false, true]);
expect(secretAt('type')).toBe(true);
expect(secretAt('keyboardType')).toBe(false);
expect(secretAt('keyboardInsertText')).toBe(true);
});

test('types', async ({ runTSC }) => {
const result = await runTSC({
'playwright.config.ts': `
import { defineConfig } from '@playwright/test';
export default defineConfig({
narratedVideo: { mode: 'demo', zoom: false, captions: true, voice: async text => Buffer.from(text), voiceName: 'Samantha' },
narratedVideo: { mode: 'demo', zoom: false, captions: true, voice: async text => Buffer.from(text), voiceName: 'Samantha', showPasswords: true },
});
// @ts-expect-error
defineConfig({ narratedVideo: { mode: 'sometimes' } });
Expand Down
1 change: 1 addition & 0 deletions utils/generate_types/overrides-test.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export type NarratedVideoOptions = {
captions?: boolean;
voice?: 'auto' | 'system' | 'kokoro' | false | ((text: string) => Promise<Buffer>);
voiceName?: string;
showPasswords?: boolean;
};

interface TestConfig<TestArgs = {}, WorkerArgs = {}> {
Expand Down