Skip to content
Merged
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
46 changes: 43 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,32 @@ jobs:
- name: Check the package contents
run: npm pack --dry-run

compat:
# Loads the example's tests with the oldest supported and other Playwright versions. Fixtures
# are checked when the tests load, so this catches fixtures a version does not have.
needs: test
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
playwright: ['1.49.1', '1.56.1', 'latest']
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm pack
- name: List the example's tests with @playwright/test ${{ matrix.playwright }}
working-directory: examples/basic
env:
TESTINGBOT_KEY: dummy
TESTINGBOT_SECRET: dummy
run: |
npm install --no-save @playwright/test@${{ matrix.playwright }} ../../testingbot-playwright-*.tgz
npx playwright test --list

e2e:
# Runs the example project on TestingBot. Needs the TESTINGBOT_KEY / TESTINGBOT_SECRET secrets,
# which are not available to pull requests from forks.
Expand Down Expand Up @@ -56,9 +82,23 @@ jobs:
- name: Run the example on TestingBot
if: env.TESTINGBOT_KEY != '' && env.TESTINGBOT_SECRET != ''
working-directory: examples/basic
env:
TESTINGBOT_BUILD: github-${{ github.run_id }}
run: |
npm install
npm install --no-save ../../testingbot-playwright-*.tgz
npx playwright test
npx playwright test --trace on --reporter=list,json,html
env:
TESTINGBOT_BUILD: github-${{ github.run_id }}
PLAYWRIGHT_JSON_OUTPUT_NAME: results.json
PLAYWRIGHT_HTML_OPEN: never
- name: Check that no report or trace contains the credentials
if: env.TESTINGBOT_KEY != '' && env.TESTINGBOT_SECRET != ''
working-directory: examples/basic
run: |
leaks=0
for f in $(find test-results playwright-report results.json testingbot-sessions.json -type f 2>/dev/null); do
case "$f" in *.zip) content=$(unzip -p "$f") ;; *) content=$(cat "$f") ;; esac
for value in "$TESTINGBOT_KEY" "$TESTINGBOT_SECRET"; do
if printf '%s' "$content" | grep -aqF "$value"; then echo "::error::$f contains TestingBot credentials"; leaks=1; fi
done
done
exit $leaks
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ TestingBot sessions:
- **Opting out.** A project with `use: { testingbot: false }` is left alone and runs locally. You can also pin a project to a browser with `use: { testingbot: { browserName: 'chrome', browserVersion: '120', platform: 'WIN10' } }`.
- **Build.** All sessions of a run are grouped in one build: `TESTINGBOT_BUILD` if set, otherwise a generated `playwright <date>` name. Pass `build: 'my build'` or `build: false`.
- **Reporter.** The TestingBot reporter is added after your reporters. Pass `reporter: { outputFile: 'testingbot.json' }` to also write the sessions as JSON (useful in CI), or `reporter: false` to leave it out.
- **`connectOptions`.** Each project also gets `use.connectOptions`, so the `browser` fixture of plain `@playwright/test` connects to TestingBot as well (one session per worker, without status reporting).
- **Credentials stay out of reports and traces.** Playwright copies each project's `use` into its reports, and records the parameters of `connect` in traces. The config therefore holds no credentials: the fixtures of this package add them when they connect, in a way the trace does not record. The `browser` fixture is replaced too, so tests that call `browser.newContext()` share the worker's TestingBot session.

### Options

Expand Down Expand Up @@ -170,13 +170,13 @@ const browser = await chromium.connect(getConnectUrl({
}))
```

Use `toPlaywrightBrowserName('edge')` (`chromium`) to pick the browser type, and `runExecutor(page, { action: 'setSessionStatus', arguments: { passed: true } })` to send the result. `startTunnel()` and `stopTunnel()` start and stop a tunnel.
The URL contains your credentials, so keep it out of `playwright.config` (`use.connectOptions`): Playwright writes that into its reports and traces. Use `toPlaywrightBrowserName('edge')` (`chromium`) to pick the browser type, and `runExecutor(page, { action: 'setSessionStatus', arguments: { passed: true } })` to send the result. `startTunnel()` and `stopTunnel()` start and stop a tunnel.

## Limitations

- In the default session-per-test mode the `context` fixture is provided by this package. The context options from `use` are applied (viewport, locale, `baseURL`, `storageState`, ...), but Playwright's own `video` option is not: TestingBot records video itself (`tbOptions: { screenrecorder: true }`). Traces and screenshots work as usual.
- Tests that use the `browser` fixture directly (`browser.newContext()`) use the per-worker session from `connectOptions` and get no status.
- Tests must import `test` from `@testingbot/playwright` for names and status. With `test` from `@playwright/test` the tests still run on TestingBot, one session per worker, without names or status.
- Tests that use the `browser` fixture directly (`browser.newContext()`) share one session per worker, which gets no status.
- Tests must import `test` from `@testingbot/playwright`. With `test` from `@playwright/test`, TestingBot refuses the connection with `Missing key or secret`, since the config holds no credentials.

## Development

Expand Down
1 change: 1 addition & 0 deletions examples/basic/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ test-results/
playwright-report/
testingbot-sessions.json
package-lock.json
results.json
9 changes: 5 additions & 4 deletions src/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,16 +106,17 @@ export function buildCapabilities(options: ConnectUrlOptions = {}, includeCreden
}

/**
* Returns the WebSocket URL to pass to `browserType.connect()` or to
* `use.connectOptions.wsEndpoint` in `playwright.config`.
* Returns the WebSocket URL to pass to `browserType.connect()`. It contains your credentials:
* do not put it in `playwright.config` (`use.connectOptions`), where Playwright copies it into
* traces and reports. `withTestingBot()` and the `test` of this package handle that for you.
*
* ```ts
* const browser = await chromium.connect(getConnectUrl({ browserName: 'chrome', platform: 'WIN11', name: 'My test' }))
* ```
*/
export function getConnectUrl(options: ConnectUrlOptions = {}): string {
export function getConnectUrl(options: ConnectUrlOptions = {}, includeCredentials = true): string {
const endpoint = options.endpoint ?? options.env?.TESTINGBOT_PLAYWRIGHT_ENDPOINT ?? process.env.TESTINGBOT_PLAYWRIGHT_ENDPOINT ?? DEFAULT_ENDPOINT
const capabilities = buildCapabilities(options, true)
const capabilities = buildCapabilities(options, includeCredentials)
const separator = endpoint.includes('?') ? '&' : '?'
return `${endpoint}${separator}capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`
}
Expand Down
6 changes: 4 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,10 @@ export function withTestingBot<T = {}, W = {}>(config: PlaywrightTestConfig<T, W
use: {
...use,
browserName: toPlaywrightBrowserName(spec.browserName),
// Used by the `browser` fixture of plain `@playwright/test` (one session per worker).
connectOptions: { wsEndpoint: getConnectUrl({ ...testingbot, name: testingbot.name ?? project.name, env }) },
// Without credentials: Playwright writes `use` to its reports (the JSON reporter) and traces.
// The fixtures of this package add them when they connect. Tests that import `test` from
// plain `@playwright/test` are rejected by TestingBot instead of running a local browser.
connectOptions: { wsEndpoint: getConnectUrl({ ...testingbot, name: testingbot.name ?? project.name, env }, false) },
testingbot
} as Project['use']
}
Expand Down
121 changes: 52 additions & 69 deletions src/fixtures.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { test as base, expect } from '@playwright/test'
import type { Browser, BrowserContext, BrowserContextOptions } from '@playwright/test'
import type { Browser, BrowserContext, BrowserContextOptions, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, TestType } from '@playwright/test'
import { getConnectUrl, redact, toPlaywrightBrowserName } from './capabilities'
import { findCredentials } from './credentials'
import { pageForExecutor, runExecutor, testUrl } from './executor'
Expand Down Expand Up @@ -37,16 +37,22 @@ interface WorkerSession {

interface WorkerState {
remote?: WorkerSession
remoteConnecting?: Promise<Browser>
remoteConnecting?: Promise<WorkerSession>
local?: Promise<Browser>
}

type PlaywrightApi = Pick<typeof import('@playwright/test'), 'chromium' | 'firefox' | 'webkit'>

async function connect(playwright: PlaywrightApi, browserName: string, wsEndpoint: string, timeout?: number): Promise<Browser> {
const type = playwright[toPlaywrightBrowserName(browserName)]
const run = () => type.connect(wsEndpoint, timeout ? { timeout } : undefined)
try {
return await type.connect(wsEndpoint, timeout ? { timeout } : undefined)
// The connect URL carries the credentials, and Playwright Test records the parameters of every
// API call in the trace (and so in the HTML report). Calls inside an internal API zone are not
// recorded. `_wrapApiCall` is private: 1.49-1.52 take a boolean, later versions `{ internal }`;
// an object is truthy for the former. Without it, connect normally.
const wrap = (type as unknown as { _wrapApiCall?: (fn: typeof run, options: unknown) => Promise<Browser> })._wrapApiCall
return typeof wrap === 'function' ? await wrap.call(type, run, { internal: true }) : await run()
} catch (error) {
const credentials = findCredentials()
const err = error as Error
Expand All @@ -55,6 +61,16 @@ async function connect(playwright: PlaywrightApi, browserName: string, wsEndpoin
}
}

/** The shared session of a worker (`sessionPerTest: false`, and the `browser` fixture). */
function workerSession(playwright: PlaywrightApi, state: WorkerState, testingbot: TestingBotProjectOptions, projectName: string, parallelIndex: number): Promise<WorkerSession> {
state.remoteConnecting ??= connect(
playwright,
testingbot.browserName ?? 'chrome',
getConnectUrl({ ...testingbot, name: testingbot.name ?? `${projectName} (worker ${parallelIndex})` })
).then((browser) => (state.remote ??= { browser, results: [] }))
return state.remoteConnecting
}

async function markSession(browser: Browser, name: string | undefined, result: { passed: boolean; reason?: string } | undefined, context?: BrowserContext): Promise<string | undefined> {
if (!browser.isConnected()) return undefined
const { page, cleanup } = await pageForExecutor(browser, context)
Expand Down Expand Up @@ -85,7 +101,14 @@ async function markSession(browser: Browser, name: string | undefined, result: {
* session (named after the test) and its pass/fail status is sent to TestingBot.
* Projects without the `testingbot` option run locally as usual.
*/
export const test = base.extend<TestingBotTestFixtures, TestingBotWorkerFixtures>({
// `_combinedContextOptions` is Playwright Test's own (private) fixture with the context options of
// `use`, merged with `contextOptions`. It exists, test-scoped, in every supported version.
const playwrightTest = base as unknown as TestType<
PlaywrightTestArgs & PlaywrightTestOptions & { _combinedContextOptions: BrowserContextOptions },
PlaywrightWorkerArgs & PlaywrightWorkerOptions
>

export const test = playwrightTest.extend<TestingBotTestFixtures, TestingBotWorkerFixtures>({
testingbot: [undefined, { option: true, scope: 'worker' }],

_testingbotWorker: [
Expand All @@ -104,6 +127,22 @@ export const test = base.extend<TestingBotTestFixtures, TestingBotWorkerFixtures
{ scope: 'worker', auto: true, box: true }
],

// Playwright's own `browser` fixture would connect with `connectOptions`, which carries no
// credentials (see `withTestingBot()`). Tests that use `browser` directly share the worker session.
browser: [
async ({ testingbot, _testingbotWorker, playwright, browserName, headless, channel, launchOptions, connectOptions }, use, workerInfo) => {
if (testingbot) {
await use((await workerSession(playwright, _testingbotWorker, testingbot, workerInfo.project.name, workerInfo.parallelIndex)).browser)
return
}
_testingbotWorker.local ??= connectOptions
? playwright[browserName].connect(connectOptions.wsEndpoint, connectOptions)
: playwright[browserName].launch({ headless, channel, ...launchOptions })
await use(await _testingbotWorker.local)
},
{ scope: 'worker', timeout: 0 }
],

testingbotSession: [
async ({ testingbot }, use) => {
await use({ remote: !!testingbot })
Expand All @@ -122,67 +161,15 @@ export const test = base.extend<TestingBotTestFixtures, TestingBotWorkerFixtures
channel,
launchOptions,
connectOptions,
acceptDownloads,
bypassCSP,
clientCertificates,
colorScheme,
deviceScaleFactor,
extraHTTPHeaders,
forcedColors,
geolocation,
hasTouch,
httpCredentials,
ignoreHTTPSErrors,
isMobile,
javaScriptEnabled,
locale,
offline,
permissions,
proxy,
reducedMotion,
screen,
serviceWorkers,
storageState,
timezoneId,
userAgent,
viewport,
baseURL,
contextOptions
_combinedContextOptions
},
use,
testInfo
) => {
const explicit: BrowserContextOptions = {
acceptDownloads,
bypassCSP,
clientCertificates,
colorScheme,
deviceScaleFactor,
extraHTTPHeaders,
forcedColors,
geolocation,
hasTouch,
httpCredentials: httpCredentials as BrowserContextOptions['httpCredentials'],
ignoreHTTPSErrors,
isMobile,
javaScriptEnabled,
locale,
offline,
permissions,
proxy,
reducedMotion,
screen,
serviceWorkers,
storageState,
timezoneId,
userAgent,
viewport,
baseURL
}
const options: BrowserContextOptions = { ...contextOptions }
for (const [key, value] of Object.entries(explicit)) {
if (value !== undefined) (options as Record<string, unknown>)[key] = value
}
// Playwright merges `contextOptions` with the context options from `use` (viewport, locale,
// baseURL, ...) in this fixture. Asking for the options one by one breaks on Playwright
// versions that lack one of them (forcedColors, reducedMotion, contrast, ...).
const options: BrowserContextOptions = { ...(_combinedContextOptions ?? {}) }

// Local project: behave like Playwright Test, one browser per worker.
if (!testingbot) {
Expand All @@ -201,14 +188,10 @@ export const test = base.extend<TestingBotTestFixtures, TestingBotWorkerFixtures

// One TestingBot session per worker (sessionPerTest: false).
if (testingbot.sessionPerTest === false) {
if (!_testingbotWorker.remote) {
const started = Date.now()
_testingbotWorker.remoteConnecting ??= connect(playwright, browserType, getConnectUrl({ ...testingbot, name: testingbot.name ?? `${testInfo.project.name} (worker ${testInfo.parallelIndex})` }))
const browser = await _testingbotWorker.remoteConnecting
_testingbotWorker.remote ??= { browser, results: [] }
testInfo.setTimeout(testInfo.timeout + (Date.now() - started))
}
const session = _testingbotWorker.remote
const started = Date.now()
const session = await workerSession(playwright, _testingbotWorker, testingbot, testInfo.project.name, testInfo.parallelIndex)
// Waiting for a free TestingBot session should not count against the test timeout.
testInfo.setTimeout(testInfo.timeout + (Date.now() - started))
const context = await session.browser.newContext(options)
await use(context)
const result = outcome(testInfo)
Expand Down
5 changes: 4 additions & 1 deletion test/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ describe('withTestingBot', () => {
expect(use(chrome).testingbot).toEqual({ build: 'b1', browserName: 'chrome', browserVersion: 'latest', platform: 'WIN11', tbOptions: {} })
expect(use(safari).testingbot.tbOptions).toEqual({ screenrecorder: true })
const caps = decodeCapabilities(use(chrome).connectOptions.wsEndpoint)
expect(caps).toMatchObject({ browserName: 'chrome', platform: 'WIN11', 'tb:options': { key: KEY, secret: SECRET, build: 'b1', name: 'chrome@latest:WIN11' } })
expect(caps).toMatchObject({ browserName: 'chrome', platform: 'WIN11', 'tb:options': { build: 'b1', name: 'chrome@latest:WIN11' } })
// Playwright copies `use` into reports and traces, so the config holds no credentials.
expect(JSON.stringify(config)).not.toContain(SECRET)
expect(JSON.stringify(config)).not.toContain(KEY)
})

it('never puts credentials in the testingbot option or metadata', () => {
Expand Down
Loading