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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
6 changes: 5 additions & 1 deletion tests/browser/helpers/app_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { test as base, expect } from "@playwright/test";
import { consola } from "consola";

// Local imports
import { orderedTest } from "./screenshot_order";
import { screenshotPath } from "./screenshot_path";
import { waitForActionSettled } from "./wait_for_action_settled";

Expand Down Expand Up @@ -69,7 +70,7 @@ async function doNothing(): Promise<void> {
// Default of the app hooks
}

const test = base.extend<AppTestFixtures, AppWorkerFixtures>({
const appTest = base.extend<AppTestFixtures, AppWorkerFixtures>({
suiteId: ["default", { option: true, scope: "worker" }],

launchApp: [
Expand Down Expand Up @@ -210,5 +211,8 @@ const test = base.extend<AppTestFixtures, AppWorkerFixtures>({
],
});

// Numbers the screenshots by declaration order
const test = orderedTest(appTest);

export { test };
export type { AppTestFixtures, AppWorkerFixtures, LaunchedApp, RunningApp };
117 changes: 117 additions & 0 deletions tests/browser/helpers/caller_location.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Playwright locates a test, a describe or a test.use by the frame calling it (wrapFunctionWithLocation of
// Playwright/lib/transform/transform.js captures a 2 frames stack trace and reads its second frame): called by a
// Wrapper, they would all be located in the wrapper. While the wrapper calls Playwright, the stack traces get the
// Frames of the wrapper on top of their limit, and lose them: they keep the location of the test file declaring them

type AnyFunction = (...args: unknown[]) => unknown;
type CallSite = NodeJS.CallSite;
// Undefined when no prepareStackTrace is installed
type PrepareStackTrace = NonNullable<typeof Error.prepareStackTrace> | undefined;
type ErrorProperty = "captureStackTrace" | "prepareStackTrace";

// Frames of wrapperFileNames: itself, callWithCallerLocation, then the wrapper calling callWithCallerLocation
const OWN_FRAME = 0;
const WRAPPER_FRAME = 2;
// Frames of the wrapper and of this file, in a describe of the wrapper too
const WRAPPER_FRAMES = 10;

function isCallable(value: unknown): value is AnyFunction {
return typeof value === "function";
}

function restoreErrorProperty(
property: ErrorProperty,
descriptor: PropertyDescriptor | undefined,
): void {
if (descriptor === undefined) {
Reflect.deleteProperty(Error, property);
} else {
Object.defineProperty(Error, property, descriptor);
}
}

function defineErrorValue(property: ErrorProperty, value: unknown): void {
Object.defineProperty(Error, property, { configurable: true, writable: true, value });
}

function fileName(callSite: CallSite | undefined): string {
return callSite?.getFileName() ?? "";
}

// Defined, not set: a wrapper called in a describe of a wrapper must see its own frames
function wrapperFileNames(): Set<string> {
const descriptor = Object.getOwnPropertyDescriptor(Error, "prepareStackTrace");
let fileNames = new Set<string>();
defineErrorValue("prepareStackTrace", (_error: Error, callSites: CallSite[]): string => {
fileNames = new Set([fileName(callSites[OWN_FRAME]), fileName(callSites[WRAPPER_FRAME])]);
return "";
});
try {
// Reading the stack calls prepareStackTrace
const { stack } = new Error("Stack of the wrapper");
if (stack === undefined) {
return new Set();
}
return fileNames;
} finally {
restoreErrorProperty("prepareStackTrace", descriptor);
}
}

// Read through the accessor of a wrapper calling this wrapper from one of its describes
function currentPrepareStackTrace(): PrepareStackTrace {
const prepare: unknown = Reflect.get(Error, "prepareStackTrace");
if (isCallable(prepare)) {
return prepare;
}
return undefined;
}

function withoutFrames(prepare: PrepareStackTrace, hiddenFiles: Set<string>): PrepareStackTrace {
if (prepare === undefined) {
return undefined;
}
return (error, callSites): unknown =>
prepare(
error,
callSites.filter((callSite) => !hiddenFiles.has(fileName(callSite))),
);
}

function withWrapperFrames(capture: AnyFunction): AnyFunction {
return (...args: unknown[]): void => {
const limit = Error.stackTraceLimit;
Error.stackTraceLimit = limit + WRAPPER_FRAMES;
try {
Reflect.apply(capture, Error, args);
} finally {
Error.stackTraceLimit = limit;
}
};
}

function callWithCallerLocation(func: AnyFunction, thisArg: unknown, args: unknown[]): unknown {
const hiddenFiles = wrapperFileNames();
const prepareDescriptor = Object.getOwnPropertyDescriptor(Error, "prepareStackTrace");
const captureDescriptor = Object.getOwnPropertyDescriptor(Error, "captureStackTrace");
let prepare = currentPrepareStackTrace();
Object.defineProperty(Error, "prepareStackTrace", {
configurable: true,
get: (): PrepareStackTrace => prepare,
set: (value: PrepareStackTrace): void => {
prepare = withoutFrames(value, hiddenFiles);
},
});
const capture: unknown = captureDescriptor?.value;
if (isCallable(capture)) {
defineErrorValue("captureStackTrace", withWrapperFrames(capture));
}
try {
return Reflect.apply(func, thisArg, args);
} finally {
restoreErrorProperty("captureStackTrace", captureDescriptor);
restoreErrorProperty("prepareStackTrace", prepareDescriptor);
}
}

export { callWithCallerLocation };
159 changes: 159 additions & 0 deletions tests/browser/helpers/screenshot_order.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// Numbers the screenshot of each test by its declaration order, so the screenshots of a folder sort like the tests of
// Their test file or suite. Playwright gives no position to a running test: the apps' test (see ./app_test.ts) is
// Wrapped to count the tests when they are declared and keep the number in an annotation of the test. The numbering
// Restarts for each test file (at its test.use({ suiteId })) and each describe (each shared suite has its own folder)

// Third party imports
import type { TestInfo } from "@playwright/test";

// Local imports
import { callWithCallerLocation } from "./caller_location";

const SCREENSHOT_INDEX_ANNOTATION = "screenshotIndex";
const INDEX_DIGITS = 3;
// Test.skip(title, body)...: declarations, unlike their test.skip(condition) form inside a test or a describe
const DECLARING_MODIFIERS = new Set(["skip", "fixme", "fail", "only"]);
const DESCRIBE_VARIANTS = new Set(["only", "skip", "fixme", "serial", "parallel"]);

interface Annotation {
type: string;
description?: string;
}

interface TestDetails {
annotation?: Annotation | Annotation[];
}

type AnyFunction = (...args: unknown[]) => unknown;

// Number of tests declared so far in the test file, then in each open describe
const counters: number[] = [0];

function isCallable(value: unknown): value is AnyFunction {
return typeof value === "function";
}

function nextIndex(): number {
const index = (counters.pop() ?? 0) + 1;
counters.push(index);
return index;
}

// Prefix of the screenshot of the test declared at this index: 001-<name>
function screenshotFileName(index: number, name: string): string {
return `${String(index).padStart(INDEX_DIGITS, "0")}-${name}`;
}

function screenshotIndex(testInfo: TestInfo): number {
const annotation = testInfo.annotations.find(({ type }) => type === SCREENSHOT_INDEX_ANNOTATION);
if (annotation?.description === undefined) {
throw new Error(`${testInfo.title}: declared without the test of ./app_test.ts`);
}
return Number(annotation.description);
}

function annotationList(details: TestDetails): Annotation[] {
if (details.annotation === undefined) {
return [];
}
return [details.annotation].flat();
}

// Test(title, body) or test(title, details, body): adds the index to the annotations of the details
function withIndex(args: unknown[]): unknown[] {
const [title, ...rest] = args;
const body = rest.pop();
const details = (rest[0] ?? {}) as TestDetails;
const annotation: Annotation = {
type: SCREENSHOT_INDEX_ANNOTATION,
description: String(nextIndex()),
};
return [title, { ...details, annotation: [...annotationList(details), annotation] }, body];
}

function declaresTest(args: unknown[]): boolean {
return typeof args[0] === "string" && isCallable(args.at(-1));
}

// A describe numbers its tests from 1, then its parent goes on with its own numbering
function orderedDescribe(describe: AnyFunction): AnyFunction {
return new Proxy(describe, {
apply: (target, thisArg, args: unknown[]): unknown => {
counters.push(0);
try {
return callWithCallerLocation(target, thisArg, args);
} finally {
counters.pop();
}
},
get: (target, property, receiver): unknown => {
const value: unknown = Reflect.get(target, property, receiver);
if (typeof property === "string" && DESCRIBE_VARIANTS.has(property) && isCallable(value)) {
return orderedDescribe(value);
}
return value;
},
});
}

function orderedModifier(modifier: AnyFunction): AnyFunction {
return (...args: unknown[]) => {
if (declaresTest(args)) {
return callWithCallerLocation(modifier, undefined, withIndex(args));
}
return callWithCallerLocation(modifier, undefined, args);
};
}

// Test.use({ suiteId }) is called once at the top of each test file: its tests are numbered from 1
function orderedUse(use: AnyFunction): AnyFunction {
return (fixtures: unknown) => {
if (typeof fixtures === "object" && fixtures !== null && "suiteId" in fixtures) {
counters.splice(0, counters.length, 0);
}
return callWithCallerLocation(use, undefined, [fixtures]);
};
}

function orderedProperty(property: string | symbol, value: unknown): unknown {
if (!isCallable(value)) {
return value;
}
if (property === "describe") {
return orderedDescribe(value);
}
if (property === "use") {
return orderedUse(value);
}
if (typeof property === "string" && DECLARING_MODIFIERS.has(property)) {
return orderedModifier(value);
}
return value;
}

// Wraps Playwright's test (a function with properties): the tests of the apps extending it are numbered too
function orderedTest<Test extends object>(test: Test): Test {
return new Proxy(test, {
apply: (target, thisArg, args: unknown[]): unknown => {
if (!isCallable(target)) {
throw new TypeError("Only a Playwright test can be numbered");
}
return callWithCallerLocation(target, thisArg, withIndex(args));
},
get: (target, property, receiver): unknown => {
const value: unknown = Reflect.get(target, property, receiver);
if (property === "extend" && isCallable(value)) {
return (...args: unknown[]): unknown => {
const extended = callWithCallerLocation(value, undefined, args);
if (typeof extended !== "function") {
throw new TypeError("Playwright's test.extend must return a test");
}
return orderedTest(extended);
};
}
return orderedProperty(property, value);
},
});
}

export { orderedTest, screenshotFileName, screenshotIndex };
11 changes: 8 additions & 3 deletions tests/browser/helpers/screenshot_path.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
// Where the apps built on this layer store the screenshot taken at the end of each test (see ./app_test.ts):
// Screenshots/<test file path>/<test name>.png, relative to the pathTemplate of their Playwright config
// Screenshots/<test file path>/<index>-<test name>.png, relative to the pathTemplate of their Playwright config (the
// Index is the declaration order of the test, see ./screenshot_order.ts)

// Node imports
import path from "node:path";

// Third party imports
import type { TestInfo } from "@playwright/test";

// Local imports
import { screenshotFileName, screenshotIndex } from "./screenshot_order";

const SUITE_TEST_FILE_EXTENSION = ".test.ts";
// Built suite files of this layer, where the tests of its suites are located
const SUITE_FILE_REGEX = /tests[/\\]browser[/\\]suites[/\\](?<suite>.+)\.js$/u;
Expand All @@ -20,16 +24,17 @@ function sanitizeForFilePath(name: string): string {
// Tests/browser/tests/<suite>.test.ts; the other tests keep their path in the test folder of the app
function screenshotPath(testInfo: TestInfo): string[] {
const titles = testInfo.titlePath.slice(1);
const index = screenshotIndex(testInfo);
const suite = SUITE_FILE_REGEX.exec(testInfo.file)?.groups?.suite;
if (suite !== undefined) {
return [
...`${suite.replaceAll("\\", "/")}${SUITE_TEST_FILE_EXTENSION}`.split("/"),
`${sanitizeForFilePath(titles.slice(1).join(" "))}.png`,
`${screenshotFileName(index, sanitizeForFilePath(titles.slice(1).join(" ")))}.png`,
];
}
return [
...path.relative(testInfo.project.testDir, testInfo.file).split(path.sep),
`${sanitizeForFilePath(titles.join(" "))}.png`,
`${screenshotFileName(index, sanitizeForFilePath(titles.join(" ")))}.png`,
];
}

Expand Down
15 changes: 11 additions & 4 deletions tests/browser/shim/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { page as vitestPage } from "vitest/browser";
// Local imports
import { APP_TEST_ID, startViewerApp, stopViewerApp } from "@ogw_tests/browser/utils/app";
import { type Locator, Page } from "./playwright";
import { screenshotFileName } from "@ogw_tests/browser/helpers/screenshot_order";
import { waitForActionSettled } from "@ogw_tests/browser/helpers/wait_for_action_settled";

const START_TIMEOUT = 180_000;
Expand Down Expand Up @@ -51,16 +52,22 @@ function registerAppHooks(): void {
afterAll(stopViewerApp);
}

// Like Playwright's {testName} in the snapshot path
function screenshotName(title: string): string {
return title
// Tests declared in this file, which numbers the screenshots like the apps (see ../helpers/screenshot_order.ts)
let declaredTests = 0;

// Like Playwright's {testName} in the snapshot path, prefixed by the declaration order
function screenshotName(index: number, title: string): string {
const name = title
.toLowerCase()
.replaceAll(/[^a-z0-9]+/gu, "-")
.replaceAll(/^-|-$/gu, "");
return screenshotFileName(index, name);
}

function test(title: string, body: (fixtures: Fixtures) => Promise<void>): void {
registerAppHooks();
declaredTests += 1;
const index = declaredTests;
// Test.slow() is called inside the body, once the timeout already runs: it is read from the source
const timeout = body.toString().includes("test.slow(")
? TEST_TIMEOUT * SLOW_FACTOR
Expand All @@ -78,7 +85,7 @@ function test(title: string, body: (fixtures: Fixtures) => Promise<void>): void

await expect
.element(vitestPage.getByTestId(APP_TEST_ID))
.toMatchScreenshot(screenshotName(title), {
.toMatchScreenshot(screenshotName(index, title), {
screenshotOptions: {
mask: screenshotMask.locators.flatMap((locator) =>
shimLocator(locator)
Expand Down
Loading
Loading