|
| 1 | +// Copyright 2024 The Chromium Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +import type * as Mocha from 'mocha'; |
| 6 | + |
| 7 | +import {AsyncScope} from '../../conductor/async-scope.js'; |
| 8 | +import type {Platform} from '../../conductor/platform.js'; |
| 9 | +import {ScreenshotError} from '../../conductor/screenshot-error.js'; |
| 10 | +import {TestConfig} from '../../conductor/test_config.js'; |
| 11 | +import type {BrowserSettings, BrowserWrapper} from '../shared/browser-helper.js'; |
| 12 | +import type {DevToolsFronendPage, DevtoolsSettings} from '../shared/frontend-helper.js'; |
| 13 | +import type {InspectedPage} from '../shared/target-helper.js'; |
| 14 | +declare global { |
| 15 | + namespace Mocha { |
| 16 | + export interface TestFunction { |
| 17 | + (title: string, fn: TestCallbackWithState): void; |
| 18 | + |
| 19 | + skipOnPlatforms: (platforms: Platform[], title: string, fn: Mocha.AsyncFunc) => void; |
| 20 | + } |
| 21 | + export interface Suite { |
| 22 | + settings: SuiteSettings; |
| 23 | + state: State; |
| 24 | + browser: BrowserWrapper; |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +export type HarnessSettings = BrowserSettings&DevtoolsSettings; |
| 30 | +export type SuiteSettings = Partial<HarnessSettings>; |
| 31 | + |
| 32 | +export interface State { |
| 33 | + devToolsPage: DevToolsFronendPage; |
| 34 | + inspectedPage: InspectedPage; |
| 35 | + browser: BrowserWrapper; |
| 36 | +} |
| 37 | + |
| 38 | +/* eslint-disable-next-line @typescript-eslint/no-explicit-any */ |
| 39 | +export type TestCallbackWithState = (state: State) => PromiseLike<any>; |
| 40 | + |
| 41 | +async function takeScreenshots(state: State): Promise<{target?: string, frontend?: string}> { |
| 42 | + try { |
| 43 | + const {devToolsPage, inspectedPage} = state; |
| 44 | + const targetScreenshot = await inspectedPage.screenshot(); |
| 45 | + const frontendScreenshot = await devToolsPage.screenshot(); |
| 46 | + return {target: targetScreenshot, frontend: frontendScreenshot}; |
| 47 | + } catch (err) { |
| 48 | + console.error('Error taking a screenshot', err); |
| 49 | + return {}; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +async function createScreenshotError(test: Mocha.Runnable|undefined, error: Error): Promise<Error> { |
| 54 | + if (!test?.parent?.state) { |
| 55 | + console.error('Missing browsing state. Unable to take screenshots for the error:', error); |
| 56 | + return error; |
| 57 | + } |
| 58 | + const sate = test.parent.state; |
| 59 | + console.error('Taking screenshots for the error:', error); |
| 60 | + if (!TestConfig.debug) { |
| 61 | + try { |
| 62 | + const screenshotTimeout = 5_000; |
| 63 | + let timer: NodeJS.Timeout; |
| 64 | + const {target, frontend} = await Promise.race([ |
| 65 | + takeScreenshots(sate).then(result => { |
| 66 | + clearTimeout(timer); |
| 67 | + return result; |
| 68 | + }), |
| 69 | + new Promise(resolve => { |
| 70 | + timer = setTimeout(resolve, screenshotTimeout); |
| 71 | + }).then(() => { |
| 72 | + console.error(`Could not take screenshots within ${screenshotTimeout}ms.`); |
| 73 | + return {target: undefined, frontend: undefined}; |
| 74 | + }), |
| 75 | + ]); |
| 76 | + return ScreenshotError.fromBase64Images(error, target, frontend); |
| 77 | + } catch (e) { |
| 78 | + console.error('Unexpected error saving screenshots', e); |
| 79 | + return e; |
| 80 | + } |
| 81 | + } |
| 82 | + return error; |
| 83 | +} |
| 84 | + |
| 85 | +export function makeInstrumentedTestFunction(fn: Mocha.AsyncFunc, label: string) { |
| 86 | + return async function testFunction(this: Mocha.Context) { |
| 87 | + const abortController = new AbortController(); |
| 88 | + let resolver; |
| 89 | + let rejecter: (reason?: unknown) => void; |
| 90 | + const testPromise = new Promise((resolve, reject) => { |
| 91 | + resolver = resolve; |
| 92 | + rejecter = reject; |
| 93 | + }); |
| 94 | + // AbortSignal for the current test function. |
| 95 | + AsyncScope.abortSignal = abortController.signal; |
| 96 | + // Promisify the function in case it is sync. |
| 97 | + const promise = (async () => await fn.call(this))(); |
| 98 | + const actualTimeout = this.timeout(); |
| 99 | + // Disable test timeout. |
| 100 | + this.timeout(0); |
| 101 | + const t = actualTimeout !== 0 ? setTimeout(async () => { |
| 102 | + abortController.abort(); |
| 103 | + const stacks = []; |
| 104 | + const scopes = AsyncScope.scopes; |
| 105 | + for (const scope of scopes.values()) { |
| 106 | + const {descriptions, stack} = scope; |
| 107 | + if (stack) { |
| 108 | + const stepDescription = descriptions ? `${descriptions.join(' > ')}:\n` : ''; |
| 109 | + stacks.push(`${stepDescription}${stack.join('\n')}\n`); |
| 110 | + } |
| 111 | + } |
| 112 | + const err = new Error(`A test function (${label}) for "${this.test?.title}" timed out`); |
| 113 | + if (stacks.length > 0) { |
| 114 | + const msg = `Pending async operations during timeout:\n${stacks.join('\n\n')}`; |
| 115 | + err.cause = new Error(msg); |
| 116 | + } |
| 117 | + rejecter(await createScreenshotError(this.test, err)); |
| 118 | + }, actualTimeout) : 0; |
| 119 | + promise |
| 120 | + .then( |
| 121 | + resolver, |
| 122 | + async err => { |
| 123 | + // Suppress errors after the test was aborted. |
| 124 | + if (abortController.signal.aborted) { |
| 125 | + return; |
| 126 | + } |
| 127 | + rejecter(await createScreenshotError(this.test, err)); |
| 128 | + }) |
| 129 | + .finally(() => { |
| 130 | + clearTimeout(t); |
| 131 | + this.timeout(actualTimeout); |
| 132 | + }); |
| 133 | + return await testPromise; |
| 134 | + }; |
| 135 | +} |
0 commit comments