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
12 changes: 12 additions & 0 deletions .changeset/quiet-skips-keep-failures.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"e2e": minor
---

Keep soft assertion failures in the report when a test skips itself, and show
them in the CLI under `Skipped After Failure`. A failed attempt followed by a
skip on retry also appears there with its original error.

Add `failOnSkippedFailure: true` to fail the run with exit code 1 for these
tests. The default is `false`, preserving the existing exit code. Tests retain
their skipped status and reason, teardown still runs, and a skip does not
trigger another retry.
13 changes: 13 additions & 0 deletions docs/reference/config.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ export interface E2EConfig {
cleanupTimeout?: number;
/** Retries per test, 0 through 10; default 1 in CI, else 0. */
retries?: number;
/** Fail the run when a test skips itself after a soft failure or an earlier failed attempt; default false. */
failOnSkippedFailure?: boolean;
/** Parallel workers, 1 through 1024; default 1 in CI, else half the cores. An engine may cap it lower. */
workers?: number;
/** `{ store }` hands every artifact to a host store as it is produced. */
Expand Down Expand Up @@ -158,6 +160,17 @@ Every numeric value must be a safe integer. `projectId` falls back to
`package.json`. `workers` never exceeds what a target's engine declares. A
targeted agent action is bounded by the smaller of `actionTimeout` and 15 s.

## failOnSkippedFailure

Set `failOnSkippedFailure: true` to fail the run with exit code 1 when a test
skips after a soft assertion failure or skips a retry after an earlier failed
attempt. The default is `false`.

The test keeps its `skipped` status and reason. Its failures remain in the
report, and the CLI shows them under `Skipped After Failure` with either
setting. Clean skips, successful retries, and engine cleanup diagnostics do
not trigger this policy. A skip still stops the body and does not retry.

## targets

```ts
Expand Down
8 changes: 6 additions & 2 deletions docs/reference/expect.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -462,11 +462,15 @@ ASSERTION_FAILED: 2 soft assertions failed
A soft locator or `browser` matcher is still a recorded `expect.<matcher>` step,
marked failed, so the report shows where in the flow it landed. A soft value
matcher is not a step, the same as a hard one; its failure appears in the
final error only.
attempt's error records.

When the body throws on its own, or times out, that error stays the
attempt's verdict and the soft failures are recorded beside it under
`secondaryErrors`. A body that skips itself with `test.skip(...)` drops them.
`secondaryErrors`. A body that skips itself with `test.skip(...)` keeps them
there too. The CLI shows `Skipped After Failure`; set
[`failOnSkippedFailure: true`](/reference/config) to make that run fail with
exit code 1. Without that option, the test stays skipped and does not affect
the exit code.

A soft `toMatchSchema` returns the schema's output when the value matches
and `undefined` after a kept failure, and its type says so.
Expand Down
15 changes: 11 additions & 4 deletions docs/reference/test.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -97,16 +97,23 @@ group titles and then the test's own, are a `COLLECTION_ERROR`.

## Members

A skipped test never affects the exit code. With `test.only`, other tests
A skipped test does not affect the exit code by default. With `test.only`, other tests
are reported as `filtered`, and a CI run fails with `ONLY_IN_CI`.

Call `test.skip(condition, reason)` inside a test for conditions you learn at
runtime, such as a disabled feature flag. When the condition is true, the call
throws: the body stops at that line, as Playwright's does, and the test is
reported `skipped` with `reason`, with no retry. Nothing after the call runs.
Steps before it stay in the report as they ran, but they do not decide the
status: a failed `expect.soft` before the call is dropped. Hooks and fixtures still run their teardown. When the condition is
a precondition, call it first, before any step.
Steps before it stay in the report as they ran. Soft failures before the call
remain in the attempt's `secondaryErrors`, and the CLI lists the test under
`Skipped After Failure`. A failed attempt followed by a skip on retry appears
there too, with its original error. Hooks and fixtures still run their teardown.
When the condition is a precondition, call it first, before any step.

Set [`failOnSkippedFailure: true`](/reference/config) to fail the run with exit
code 1 when a runtime skip follows a failure in that test. The test remains
`skipped` with its reason, and the skip does not trigger another retry. Clean
skips and retries that pass are unaffected. The default is `false`.

A setup test cannot skip because other tests depend on its sessions; the
call fails with `INVALID_ARGUMENT`. Outside a test body, the conditional
Expand Down
10 changes: 10 additions & 0 deletions packages/e2e/src/config/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export interface ResolvedConfig {
readonly assertionTimeout: number;
readonly cleanupTimeout: number;
readonly retries: number;
readonly failOnSkippedFailure: boolean;
readonly workers: number;
/** Host store every produced artifact is handed to; undefined keeps files local only. */
readonly artifactStore: ArtifactStore | undefined;
Expand Down Expand Up @@ -154,6 +155,7 @@ const TOP_LEVEL_KEYS = new Set([
'assertionTimeout',
'cleanupTimeout',
'retries',
'failOnSkippedFailure',
'workers',
'artifacts',
'output',
Expand Down Expand Up @@ -266,6 +268,11 @@ export function resolveConfig(
boundedInt(raw.workers, 'workers', 1, 1024) ??
(ci ? 1 : Math.max(1, Math.floor(os.availableParallelism() / 2)));

const failOnSkippedFailure = raw.failOnSkippedFailure === undefined ? false : raw.failOnSkippedFailure;
if (typeof failOnSkippedFailure !== 'boolean') {
throw new ConfigurationError('INVALID_CONFIG', 'failOnSkippedFailure must be a boolean');
}

const artifactStore = resolveArtifactStore(raw);
const { reporters, customReporters } = resolveReporters(raw, cli);

Expand All @@ -291,6 +298,7 @@ export function resolveConfig(
assertionTimeout,
cleanupTimeout,
retries,
failOnSkippedFailure,
workers,
artifactStore,
output,
Expand Down Expand Up @@ -900,9 +908,11 @@ function computeConfigDigest(
// reporter object changes nothing about what a run records, so it never
// enters the digest either; the built-in ids digest as they always have,
// so adding a reporter to a config leaves its cache valid.
// `failOnSkippedFailure` decides only the exit code, never what runs.
// `targets` digest by declaration below and never enter the clone: an
// engine holds `secrets.get()` handles, which refuse to serialize.
const {
failOnSkippedFailure: _failOnSkippedFailure,
artifacts: _artifacts,
output: _output,
trace: _trace,
Expand Down
8 changes: 6 additions & 2 deletions packages/e2e/src/report/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { packageVersion } from '../internal/package-version.ts';
import { projectRelativePath } from '../internal/source.ts';
import type { VcsInfo } from '../internal/vcs.ts';
import type { SkipInfo } from '../collect/select.ts';
import { someSkippedAfterFailure } from '../run/records.ts';
import type {
ArtifactRecord,
AttemptRecord,
Expand Down Expand Up @@ -555,17 +556,20 @@ function computeSummary(results: readonly ResultRecord[]): ReportSummary {
* nothing contradicts that. One genuine failure keeps the run failed, and so
* does any run-level error (a launch that never came up, a cleanup or report
* write that failed): it is its own fact about the run, not a blocked step,
* and it must stay visible to a host reading the status. Derivation requires
* and it must stay visible to a host reading the status. So does a skip after
* a failure under `failOnSkippedFailure`. Derivation requires
* positive evidence, never absence of it.
*/
function deriveRunStatus(
status: BuildReportOptions['status'],
results: readonly ResultRecord[],
serialGroups: readonly SerialGroupRecord[],
runErrors: readonly RunError[],
failOnSkippedFailure: boolean,
): BuildReportOptions['status'] | 'blocked' {
if (status !== 'failed' && status !== 'error') return status;
if (runErrors.length > 0) return status;
if (failOnSkippedFailure && someSkippedAfterFailure(results, serialGroups)) return status;
// Serial members carry no attempts of their own; their failing error lives
// on the group's last attempt (or its failing member).
const groupCode = new Map<string, string | undefined>();
Expand Down Expand Up @@ -700,7 +704,7 @@ export function buildReport(options: BuildReportOptions): Report1Document {
name: 'e2e',
version: packageVersion(import.meta.url, '../../package.json', '0.0.0'),
},
status: deriveRunStatus(options.status, options.results, options.serialGroups, options.runErrors),
status: deriveRunStatus(options.status, options.results, options.serialGroups, options.runErrors, config?.failOnSkippedFailure === true),
exitCode: options.exitCode,
startedAt: options.startedAt,
finishedAt: timestamp(),
Expand Down
28 changes: 19 additions & 9 deletions packages/e2e/src/report/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import picocolors from 'picocolors';
import type { SerializedError } from '../internal/errors.ts';
import { packageVersion } from '../internal/package-version.ts';
import type { RunEvent, RunEventFact, RunEventOf, RunEventResult, SetupStep } from '../run/events.ts';
import type { ArtifactRecord, AttemptRecord, FailureEvidence, ResultStatus, SerialGroupRecord } from '../run/records.ts';
import { failureBeforeSkip, type ArtifactRecord, type AttemptRecord, type FailureEvidence, type ResultStatus, type SerialGroupRecord } from '../run/records.ts';
import type { Reporter, ReporterSummary } from '../types.ts';
import { codeFrame, userFrame } from './code-frame.ts';
import {
Expand Down Expand Up @@ -179,7 +179,7 @@ function serialMemberDetails(group: SerialGroupRecord, testId: string): ResultDe
};
}

/** One failed pair, held for the `Failed Tests` section. */
/** One failed pair, held for the `Failed Tests` section, or a skipped one for `Skipped After Failure`. */
interface Failure {
readonly group: FileGroup;
readonly title: string;
Expand Down Expand Up @@ -226,6 +226,7 @@ export class ListReporter implements Reporter {
/** Whether a live window paints; without one, finished steps stream permanently. */
private readonly live: boolean;
private readonly failures: Failure[] = [];
private readonly skippedFailures: Failure[] = [];
/** Every finished test's run, for the `Repeats` summary of a `--repeat-each` run. */
private readonly runs: { key: string; label: string; run: RepeatRun }[] = [];
/**
Expand Down Expand Up @@ -650,6 +651,8 @@ export class ListReporter implements Reporter {
const steps = this.pairs.get(key)?.steps ?? [];
this.pairs.delete(key);
const group = this.group(result.test.file, result.target.name);
// Read before `detailsOf` releases the result's serial group.
const skippedAfter = failureBeforeSkip(result, (id) => this.pendingSerial.get(id)?.group);
const { durationMs, usage, models, cache, error, videos, failure, screenPath } = this.detailsOf(result);
addUsage(this.runUsage, usage);
addModelTally(this.runModels, models);
Expand Down Expand Up @@ -684,6 +687,9 @@ export class ListReporter implements Reporter {
if (statusBucket(result.status) === 'failed') {
this.failures.push({ group, title, status: result.status, error, videos, failure, screenPath });
}
if (skippedAfter !== undefined) {
this.skippedFailures.push({ group, title, status: result.status, error: skippedAfter.error, videos, ...failureOf(skippedAfter) });
}
if (group.planned !== undefined && group.lines.length >= group.planned) this.printGroup(group);
this.window.redraw();
}
Expand Down Expand Up @@ -820,6 +826,9 @@ export class ListReporter implements Reporter {
const cache = cacheText(pc, this.runCache);
if (cache !== undefined) rows.push(padTitle(pc, 'Cache') + cache);
if (final) rows.push(...this.repeatRows());
if (this.skippedFailures.length > 0) {
rows.push(padTitle(pc, 'Warnings') + pc.yellow(`${this.skippedFailures.length} skipped after failure`));
}
if (this.errors.length > 0) {
const count = this.errors.length;
rows.push(padTitle(pc, 'Errors') + pc.bold(pc.red(`${count} error${count === 1 ? '' : 's'}`)));
Expand Down Expand Up @@ -912,15 +921,15 @@ export class ListReporter implements Reporter {
}

/** vitest's `Failed Tests` section: a banner, then each failure with its code frame. */
private printFailures(): void {
private printFailures(heading: string, failures: readonly Failure[]): void {
const { pc } = this;
if (this.failures.length === 0) return;
if (failures.length === 0) return;
this.print('');
this.print(this.errorBanner(`Failed Tests ${this.failures.length}`));
this.print(this.errorBanner(`${heading} ${failures.length}`));
this.print('');
this.failures.forEach(({ group, title, status, error, videos, failure, screenPath }, index) => {
failures.forEach(({ group, title, status, error, videos, failure, screenPath }, index) => {
this.print(
`${pc.bold(pc.bgRed(' FAIL '))} ${this.badge(group.target)} ${bounded(group.file)}${this.separator}${title}`,
`${pc.bold(pc.bgRed(status === 'skipped' ? ' SKIP ' : ' FAIL '))} ${this.badge(group.target)} ${bounded(group.file)}${this.separator}${title}`,
);
if (error === undefined) {
this.print(pc.red(`${pc.bold(status)}: no error was recorded`));
Expand All @@ -932,7 +941,7 @@ export class ListReporter implements Reporter {
}
this.printEvidence(failure, screenPath);
this.printVideos(videos);
const marker = `[${index + 1}/${this.failures.length}]`;
const marker = `[${index + 1}/${failures.length}]`;
const { before, after } = rule(marker, 'right');
this.print('');
this.print(pc.red(pc.dim(`${before}${marker}${after}`)));
Expand Down Expand Up @@ -1029,7 +1038,8 @@ export class ListReporter implements Reporter {
if (!group.printed && group.lines.length > 0) this.printGroup(group);
}
this.printExplore();
this.printFailures();
this.printFailures('Failed Tests', this.failures);
this.printFailures('Skipped After Failure', this.skippedFailures);
this.printErrors();
this.print('');
for (const row of this.summaryRows(true)) this.print(row);
Expand Down
12 changes: 6 additions & 6 deletions packages/e2e/src/run/execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1039,14 +1039,14 @@ export class TargetExecutor implements SerialHost {
await (registered.fn as SetupFn)(fixtures);
} catch (cause) {
// The body's own failure stays the verdict; the step it abandoned
// and the soft failures it kept are noted beside it.
// and the soft failures it kept are noted beside it. A skip keeps
// only the soft failures: the step it abandoned is not one.
const notAwaited = await abandonNotAwaited();
const softFailure = soft.close();
if (!isRuntimeSkip(cause)) {
for (const secondary of [notAwaited, softFailure]) {
if (secondary !== undefined) {
secondaryErrors.push(serializeError(secondary, { phase: 'body', projectRoot: this.config.projectRoot, redact }));
}
const kept = isRuntimeSkip(cause) ? [softFailure] : [notAwaited, softFailure];
for (const secondary of kept) {
if (secondary !== undefined) {
secondaryErrors.push(serializeError(secondary, { phase: 'body', projectRoot: this.config.projectRoot, redact }));
}
}
throw cause;
Expand Down
43 changes: 43 additions & 0 deletions packages/e2e/src/run/records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,49 @@ export interface ResultRecord {
*/
export type WireResultRecord = Omit<ResultRecord, 'target'>;

/** The failure a runtime skip followed, with the evidence its attempt captured. */
export interface FailureBeforeSkip {
readonly error: SerializedError;
readonly failure: FailureEvidence | undefined;
/** The failing attempt's artifacts; for a serial member, the group attempt's. */
readonly artifacts: readonly ArtifactRecord[];
}

/**
* The failure a test's `test.skip(...)` followed: the last attempt that
* failed before a skipped retry, or a soft failure the skipping attempt kept.
* Engine cleanup diagnostics after the skip are not one. A serial member's
* attempts live on its group, which `groupOf` looks up only for such a member.
*/
export function failureBeforeSkip(
result: Pick<ResultRecord, 'status' | 'skip' | 'attempts' | 'serialGroupId' | 'test'>,
groupOf: (id: string) => SerialGroupRecord | undefined,
): FailureBeforeSkip | undefined {
if (result.status !== 'skipped' || result.skip?.cause !== 'explicit') return undefined;
const runs =
result.serialGroupId === undefined
? result.attempts
: (groupOf(result.serialGroupId)?.attempts ?? []).flatMap((attempt) =>
attempt.members
.filter((member) => member.testId === result.test.id)
.map((member) => ({ ...member, artifacts: attempt.artifacts })),
);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For a serial member this walks every group attempt, including an interrupted retry that ran after the attempt that decided the skip. An INTERRUPTED error recorded there gets reported as the failure before the skip. Could the walk stop at the last member record that is skipped with an explicit cause, or skip interrupted retries like cutRetry does?

for (const run of runs.toReversed()) {
const error = run.error ?? run.secondaryErrors.find((secondary) => secondary.phase !== 'cleanup');
if (error !== undefined) return { error, failure: run.failure, artifacts: run.artifacts };
}
return undefined;
}

/** Whether any skipped result followed a failure: what `failOnSkippedFailure` fails a run for. */
export function someSkippedAfterFailure(
results: readonly ResultRecord[],
serialGroups: readonly SerialGroupRecord[],
): boolean {
const groups = new Map(serialGroups.map((group) => [group.id, group]));
return results.some((result) => failureBeforeSkip(result, (id) => groups.get(id)) !== undefined);
}

/** Strips the live target from a result for transport. */
export function encodeResult(record: ResultRecord): WireResultRecord {
const { target: _target, ...rest } = record;
Expand Down
3 changes: 2 additions & 1 deletion packages/e2e/src/run/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import { writeJsonReport } from '../report/write.ts';
import { createRunEventEmitter, toEventResult, type RunEventSink, type RunExitCode, type RunStatus, type RunEventFact, type SetupStep } from './events.ts';
import { allocateAppPorts } from './app-ports.ts';
import { inProcessSpawner } from './in-process.ts';
import type { ResultRecord, RunError, SerialGroupRecord } from './records.ts';
import { someSkippedAfterFailure, type ResultRecord, type RunError, type SerialGroupRecord } from './records.ts';
import { runUnits } from './scheduler.ts';
import { buildWorkPlans, plannedSlots, type TargetWorkPlan } from './units.ts';
import { SessionStore } from './sessions.ts';
Expand Down Expand Up @@ -402,6 +402,7 @@ export async function run(options: RunOptions = {}): Promise<RunOutcome> {
combineExitCodes(
[
...resultExitCodes(results),
...(loaded.config?.failOnSkippedFailure === true && someSkippedAfterFailure(results, serialGroups) ? [1] : []),
...runErrors.map((runError) => exitCodeForCategory(runError.error.category)),
...(interruptController.signal.aborted ? [130] : []),
].filter((code) => code !== 130 || !(runAborted || stoppedEarly)),
Expand Down
2 changes: 2 additions & 0 deletions packages/e2e/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1414,6 +1414,8 @@ export interface E2EConfig {
cleanupTimeout?: number;
/** Retries per test, 0 through 10; default 1 in CI, else 0. */
retries?: number;
/** Fail the run when a test skips itself after a soft failure or an earlier failed attempt; default false. */
failOnSkippedFailure?: boolean;
/** Parallel workers, 1 through 1024; default 1 in CI, else half the cores. An engine may cap it lower. */
workers?: number;
/** `{ store }` hands every artifact to a host store as it is produced. */
Expand Down
Loading
Loading